okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-i18n: French as the ninth app language and the Polish README52ba0b781

main
6.0 KiB105 linesraw
1/**
2 * The turn guard: a turn that keeps failing the same way, or keeps rewriting the same thing, is stopped by the app and ends with a plain message.
3 * Pure (no I/O); the bridge feeds it what the turn shows and acts on what it answers.
4 *
5 * Why: a search-heavy /plan on a small model searched again after every refusal and rewrote its plan after every search until the context
6 * reached 100%, then the turn ended with no answer and no message. Nothing here relies on the model behaving: the app counts.
7 *
8 *   searches-failed   this many web searches in a row failed (web search was limited, or could not be reached)
9 *   searches          this many searches in one turn (a plan or an ordinary answer needs a handful, not dozens)
10 *   rewrites          a plan turn wrote its numbered plan from "1." again this many times
11 *   context           the context is nearly full: the Harness compaction did not keep up
12 *
13 * What the person is told is `guardNote`: fixed English sentences that are also in the interface catalog in all nine languages (the page
14 * translates a `delta` frame that carries `key`). Each says what happened and gives one next step.
15 */
16
17export const GUARD_LIMITS = Object.freeze({
18  failedSearches: 3,
19  searchesPlan: 10,
20  searchesTurn: 25,
21  planRewrites: 4,
22  contextFraction: 0.93,
23  /** A turn that ends with no words at all and a context this full is "out of room", not "nothing to say". */
24  contextEmptyFraction: 0.85,
25});
26
27const SEARCH_TOOLS = new Set(['web_search']);
28const SEARCH_FAILED = /web search is limited|search could not reach|could not reach the internet|WEB_RATE_LIMITED|WEB_PROVIDER_ERROR|did not accept the key|too many searches/i;
29
30/** The plain sentences, keyed by reason. `values` are the slots the page fills in. */
31const NOTES = {
32  'searches-failed': 'Web search is limited right now, so I stopped searching and went on with what I have. Try again in a minute, or add a search key in Settings → Tools → Web search.',
33  searches: 'I searched a lot and stopped so this chat does not fill up. This is what I have so far. Tell me what to look into next.',
34  rewrites: 'I kept rewriting the plan, so I stopped here with the latest version. Tell me what to change, or approve it.',
35  context: 'I ran out of room in this chat, so I stopped. Strata is summarising the older messages to make space. Say “continue” to go on, or start a new chat.',
36  empty: 'I stopped without writing an answer. Send your message again, or say “continue”.',
37};
38export const GUARD_NOTES = Object.freeze({ ...NOTES });
39
40/** A `delta` frame the page shows as ordinary assistant text and translates (`key` is the English sentence). */
41export function guardNote(reason) {
42  const text = NOTES[reason];
43  return text ? { type: 'delta', own: true, text: `\n\n${text}`, key: text, noteReason: reason } : null;
44}
45
46export class TurnGuard {
47  /**
48   * @param {{plan?: boolean, contextMax?: number, limits?: Partial<typeof GUARD_LIMITS>}} [options]
49   */
50  constructor({ plan = false, contextMax = 0, limits = {} } = {}) {
51    this.plan = plan; this.contextMax = Number(contextMax) || 0;
52    this.limits = { ...GUARD_LIMITS, ...limits };
53    this.seen = new Set();
54    this.searches = 0; this.failedInARow = 0; this.failedTotal = 0;
55    this.rewrites = 0; this.written = '';
56    this.reason = null;
57  }
58
59  #fire(reason) { this.reason ??= reason; return this.reason; }
60
61  /** A tool card frame (`agent-tool`). Counts a search once, when it has finished. Returns the reason to stop, or null. */
62  card(tool) {
63    if (this.reason || !tool || !SEARCH_TOOLS.has(tool.name)) return this.reason;
64    const done = tool.state === 'done' || tool.state === 'error' || tool.state === 'denied';
65    if (!done || this.seen.has(tool.id)) return this.reason;
66    this.seen.add(tool.id);
67    this.searches += 1;
68    const failed = tool.state === 'error' || SEARCH_FAILED.test(String(tool.result ?? ''));
69    if (failed) { this.failedInARow += 1; this.failedTotal += 1; } else this.failedInARow = 0;
70    if (this.failedInARow >= this.limits.failedSearches) return this.#fire('searches-failed');
71    if (this.searches >= (this.plan ? this.limits.searchesPlan : this.limits.searchesTurn)) return this.#fire(this.failedTotal >= this.searches / 2 ? 'searches-failed' : 'searches');
72    return this.reason;
73  }
74
75  /** Text the assistant wrote (not our own lines). A plan turn that starts its numbered list again and again is rewriting. */
76  text(delta) {
77    if (this.reason || !this.plan || !delta) return this.reason;
78    this.written += delta;
79    if (this.written.length > 200_000) this.written = this.written.slice(-100_000);
80    if (!delta.includes('\n') && !/\d[.)]\s/.test(delta)) return this.reason;
81    this.rewrites = (this.written.match(/(?:^|\n)[ \t]{0,3}1[.)][ \t]+\S/g) ?? []).length;
82    if (this.rewrites >= this.limits.planRewrites) return this.#fire('rewrites');
83    return this.reason;
84  }
85
86  /** What the context holds now (tokens of the last request). */
87  context(tokens) {
88    if (this.reason || !this.contextMax || !Number.isFinite(tokens)) return this.reason;
89    if (tokens / this.contextMax >= this.limits.contextFraction) return this.#fire('context');
90    return this.reason;
91  }
92
93  /**
94   * The turn is over. If the person has seen no words from it, which sentence do they get? `ended` is the Harness's turn end reason,
95   * `wrote` whether any answer text was shown, `acted` whether tool cards were shown, `contextTokens` the last request's size. Returns a reason or null.
96   */
97  silent({ ended, wrote, contextTokens, acted = false, stoppedByPerson = false }) {
98    if (this.reason) return this.reason;
99    if (stoppedByPerson || wrote) return null;
100    const kind = ended?.kind;
101    if (kind !== 'completed' && kind !== 'max-tokens') return null;       // an error says why by itself; Stop is the person's own
102    if (this.contextMax && Number(contextTokens) / this.contextMax >= this.limits.contextEmptyFraction) return 'context';
103    return acted ? null : 'empty';                                         // cards of work done are an answer of a kind; no cards and no words is not
104  }
105}