From 40b41da91666312a7a512b49b53eecdd712e8aa7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:07:38 +0200 Subject: [PATCH] Turn guard: a search-heavy /plan that keeps failing is stopped by the app, and a full context never ends in silence A /plan on a small model searched again after every refused search and rewrote its plan after each one until the context reached 100%, then the turn ended with no answer and no message. The bridge now counts what the turn shows (turn-guard.mjs): 3 failed searches in a row, 10 searches in a plan turn (25 otherwise), a plan written from 1. again 4 times, a local model's context at 93%. The turn is stopped the way Stop stops it but ends as a normal turn: the plan it had is still proposed (the plan card says why it stopped early), any other turn ends with one plain translated sentence with a next step (frames carry the English sentence as `key`, the page translates it, 8 languages), and the Harness's own /compact is asked for so the next message has room. A turn that ends with no words at all always gets a message: "I ran out of room in this chat..." at 85% of the window or more, otherwise "I stopped without writing an answer...". Settings -> Tools says results may come from Bing when DuckDuckGo is busy. Tests: counting (pure) and three end-to-end runs through the real Harness with the scripted model (searchloop / bloat) and the real search code on a pretend web that refuses (bridge option searchMock), no network. --- apps/host/server/agent/README.md | 10 ++ apps/host/server/agent/agent-bridge.mjs | 42 ++++- apps/host/server/agent/plan.mjs | 4 +- .../server/agent/plugins/strata-search.mjs | 5 +- apps/host/server/agent/profile.mjs | 4 +- apps/host/server/agent/turn-guard.mjs | 105 ++++++++++++ apps/host/src/components/PlanCard.tsx | 1 + apps/host/src/components/SettingsTools.tsx | 2 +- apps/host/src/lib/plan.ts | 2 +- apps/host/src/lib/store.ts | 5 +- apps/host/src/locales/de.json | 6 + apps/host/src/locales/en.json | 6 + apps/host/src/locales/es.json | 6 + apps/host/src/locales/ja.json | 6 + apps/host/src/locales/ko.json | 6 + apps/host/src/locales/pt.json | 6 + apps/host/src/locales/ru.json | 6 + apps/host/src/locales/zh.json | 6 + apps/host/tests/agent-turn-guard.test.mjs | 152 ++++++++++++++++++ apps/host/tests/helpers/scripted-worker.mjs | 25 ++- apps/host/tests/runtime-api.test.mjs | 2 + 21 files changed, 392 insertions(+), 15 deletions(-) create mode 100644 apps/host/server/agent/turn-guard.mjs create mode 100644 apps/host/tests/agent-turn-guard.test.mjs diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.md index 8bfb7f4a..22fed672 100644 --- a/apps/host/server/agent/README.md +++ b/apps/host/server/agent/README.md @@ -121,3 +121,13 @@ A model on OpenRouter whose model list names `reasoning` in `supported_parameter ## Pictures Pictures are on by default for every model that can read them: an API model reads them unless the person switched it off (Settings > Models > "Read pictures with this model") or its server says it cannot; a local model reads them when it was loaded with Read pictures (on by default). `src/lib/pictures.ts` is the one answer used by the composer and by Send; the agent route declares image input from the same flag. + +## Turn guard (`turn-guard.mjs`) + +A turn that keeps failing the same way is stopped by the app, never left to the model. Seen on a search-heavy `/plan`: every web search was refused, the model searched again and rewrote its plan after each one until the context reached 100%, then the turn ended with no answer and no message. + +- **Counted, from what the turn shows:** web searches that failed in a row (3), searches in one turn (10 in a plan turn, 25 otherwise), a plan turn that starts its numbered list from `1.` again (4 times), and a context of 93% or more (the Harness's own compaction did not keep up). +- **Stopped the way Stop stops** (`session/cancel`, helpers first) but ended as a normal turn (`done`, not cancelled, no error card), so the plan the model had written is still proposed. The plan card carries the reason (`plan.caution`); any other turn ends with one `delta` frame that has `own: true` and `key` (the English sentence, translated by the page; `GUARD_NOTES` are in the interface catalog in all eight languages). Each sentence says what happened and gives one next step. +- **Compaction:** after a guard stop (and after a turn the model server refused because the context was full) the bridge asks the Harness for `/compact` on that session, so the next message has room. Best effort and logged. +- **Never silent:** a turn that ends (`completed` or `max-tokens`) with no answer text gets "I ran out of room in this chat..." when the last request used 85% of the window or more, otherwise "I stopped without writing an answer..." (not when tool cards were shown, not after Stop, not after an error, which says why by itself). Goal runs have their own ending lines and are not guarded. +- Tests: `tests/agent-turn-guard.test.mjs` (counting, always; end to end with the real Harness, the scripted model's `searchloop` and `bloat` scripts and `searchMock: 'limited'` on the bridge, which runs the real search code on a pretend web that refuses, no network). diff --git a/apps/host/server/agent/agent-bridge.mjs b/apps/host/server/agent/agent-bridge.mjs index aa5ab556..9589f785 100644 --- a/apps/host/server/agent/agent-bridge.mjs +++ b/apps/host/server/agent/agent-bridge.mjs @@ -26,6 +26,7 @@ import { ChildProjector } from './children.mjs'; import { nearestBudget } from './llm-shape.mjs'; import { DeliverableTracker, ActivityGroups } from './deliverables.mjs'; import { SkillsUsed, skillInfoFrom } from './skills-used.mjs'; +import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs'; import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs'; /** @@ -85,7 +86,7 @@ const deferred = () => { let resolve; const promise = new Promise(r => { resolve * @param {string} [options.nodePath] the Node runtime that runs the Harness * @param {(line:string)=>void} [options.log] */ -export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) { +export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000 }) { const root = join(dataDir, 'agent'); const home = join(root, 'home'); const sessionsFile = join(root, 'sessions.json'); @@ -129,7 +130,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */ let shapeTargets = {}; function buildProfileNow() { - const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase }); + const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock }); shapeTargets = profile.shapeTargets ?? {}; return profile; } @@ -294,6 +295,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true }); // What the assistant itself wrote in this run (not our own step lines): a plan turn reads its plan from it, a step reads its summary. const written = { all: '', step: '' }; + // The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known. + let guard = null; const raw = frame => { try { send(frame); } catch { send = () => {}; attached = false; } }; // What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends. const tracker = new DeliverableTracker(workspacePath); @@ -301,7 +304,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = const groups = new ActivityGroups({ emit: raw }); const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) }); const emit = frame => { - if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (hideDeltas) return; } + if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; } if (frame.own) { const { own, ...rest } = frame; frame = rest; } if (frame.type === 'delta' && frame.text) groups.text(); if (frame.type === 'agent-tool' && frame.tool) { @@ -309,6 +312,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = if (frame.tool.state === 'done' && (frame.tool.name === 'write' || frame.tool.name === 'edit')) { try { made = tracker.check(frame.tool.args?.file_path ?? frame.tool.args?.path); } catch { made = null; } } raw(frame); if (made) raw(made); + if (guard) trip(guard.card(frame.tool)); groups.card(frame.tool, made); skills.card(frame.tool); return; @@ -351,6 +355,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = await applyMode(runtime, sessionId, appliedMode); const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval }); + if (!goal) guard = new TurnGuard({ plan: !!planTask, contextMax: route.kind === 'local' ? route.contextWindow : 0 }); // a saved connection's window is often only assumed: never judged by a guess projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); }; const turn = { sessionId, projector, route, requestId, live: false, lastSeq: -1, @@ -387,13 +392,19 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = clearInterval(turn.watchdog); turn.follow?.close(); for (const child of turn.children.values()) child.follow?.close(); - if (turn.stopping && !failure) projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; + if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } }; reporter.clear(); const extra = []; try { for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ } groups.end(); if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); } try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ } + // The turn guard: a turn the app stopped, or one that ended with no words, always ends with one plain message (a plan card carries it itself). + let noteReason = turn.guard ?? null; + if (!noteReason && guard && !failure && !turn.stopping && !turn.goalRun) { + noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens }); + } + if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); } for (const f of extra) emit(f); const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow }); for (const f of frames.slice(0, -1)) emit(f); @@ -406,6 +417,8 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = c.turn = null; turn.ended.resolve({ reason: projector.ended, failure: failure ?? null }); notifyIdle(); + // A turn that filled the context, or that the guard stopped, leaves a long history behind: summarise the older part now so the next message has room. + if (noteReason === 'context' || noteReason === 'searches' || noteReason === 'searches-failed' || noteReason === 'rewrites' || /context window|too long|exceeds/i.test(String(projector.ended?.error?.message ?? ''))) void compactSession(runtime, sessionId); } emit({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], ...(planTask ? { planning: true } : {}) }); @@ -423,6 +436,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = onError: e => finishTurn(`The agent lost the session stream: ${e.message}`), }); + /** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */ + function trip(reason) { + if (!reason || turn.guard || turn.finished || turn.stopping) return; + turn.guard = reason; + log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`); + void stop(chatId).catch(() => {}); + } + function handle(item) { if (turn.finished) return; turn.lastActivity = Date.now(); @@ -438,6 +459,7 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = } } else if (!turn.live) return; for (const f of projector.consume(item)) emit(f); + if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens)); if (item.type === 'event') watchParent(item.event); } @@ -547,10 +569,10 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = /** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */ function settlePlan(failure) { if (planTask) { - if (failure || turn.stopping) return []; + if (failure || (turn.stopping && !turn.guard)) return []; const parsed = parsePlan(written.all, planTask); if (!parsed) return []; - const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask }); + const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) }); return [publishPlan('proposed', plan)]; } const run = turn.plan; @@ -1075,6 +1097,14 @@ export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = * Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the * Harness acknowledges a cancel as admitted, not as done. */ + /** Summarise the older part of a session with the Harness's own /compact. Best effort: the next message compacts again by itself when it must. */ + async function compactSession(runtime, sessionId) { + try { + const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }); + log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`); + } catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); } + } + async function stop(chatId, { waitMs = 20_000 } = {}) { const c = chats.get(chatId); const turn = c?.turn; diff --git a/apps/host/server/agent/plan.mjs b/apps/host/server/agent/plan.mjs index 06639107..2c7e372f 100644 --- a/apps/host/server/agent/plan.mjs +++ b/apps/host/server/agent/plan.mjs @@ -193,9 +193,9 @@ export class PlanStore { } catch { /* the plan still lives in memory */ } } get(chatId) { return this.plans.get(chatId) ?? null; } - create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed' }) { + create(chatId, { title, steps, request = '', source = 'plan', state = 'proposed', caution = null }) { const now = new Date().toISOString(); - const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false }; + const plan = { id: randomUUID(), chatId, title, request, source, state, steps, createdAt: now, updatedAt: now, goalStarted: false, ...(caution ? { caution } : {}) }; this.plans.set(chatId, plan); this.#save(); return plan; } diff --git a/apps/host/server/agent/plugins/strata-search.mjs b/apps/host/server/agent/plugins/strata-search.mjs index 57d63334..cf5bda68 100644 --- a/apps/host/server/agent/plugins/strata-search.mjs +++ b/apps/host/server/agent/plugins/strata-search.mjs @@ -15,7 +15,10 @@ export const inject = ['web']; export function apply(ctx, config = {}) { const keyOf = () => (config.keyEnv ? process.env[config.keyEnv] ?? '' : ''); - const provider = config.provider === 'exa' ? createExaSearch({ key: keyOf }) + // Tests only (the bridge option `searchMock`): the same search code on a pretend web, so nothing leaves the machine. + const pretend = config.mock === 'limited' ? { fetch: async url => new Response('please verify you are human: captcha', { status: /duckduckgo/.test(String(url)) ? 202 : 429 }) } : null; + const provider = pretend ? createDuckDuckGoSearch(pretend) + : config.provider === 'exa' ? createExaSearch({ key: keyOf }) : config.provider === 'perplexity' ? createPerplexitySearch({ key: keyOf }) : createDuckDuckGoSearch(); ctx.web.registerSearchProvider(provider); diff --git a/apps/host/server/agent/profile.mjs b/apps/host/server/agent/profile.mjs index b82be830..99d5a5ce 100644 --- a/apps/host/server/agent/profile.mjs +++ b/apps/host/server/agent/profile.mjs @@ -163,7 +163,7 @@ export function outputBudget(context, maxOutput = null) { /** What a local model, or an OpenAI-style server on this network, takes for the thinking level (see the comment where a local route is built). */ const THINKING_COMPAT = { supportsStore: false, thinkingFormat: 'chat-template', chatTemplateKwargs: { enable_thinking: { $var: 'thinking.enabled' }, reasoning_effort: { $var: 'thinking.effort', omitWhenOff: true } } }; -export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null }) { +export function buildProfile({ local = [], connections = [], gate = true, tools = NO_TOOLS_SETTINGS, skillsDir = null, proxyBase = null, searchMock = null }) { const providers = {}; const env = {}; const routes = []; @@ -271,7 +271,7 @@ export function buildProfile({ local = [], connections = [], gate = true, tools const webRows = !searchOn ? [] : keyed === 'deepseek' ? [{ id: 'web', config: { searchProvider: 'deepseek-official', fetchProvider: 'http' } }, { id: 'web-search-deepseek', config: { apiKeyEnv: 'STRATA_SEARCH_KEY' } }] : [{ id: 'web', config: { searchProvider: keyed ?? DDG_PROVIDER_ID, fetchProvider: 'http' } }, { id: 'web-search-deepseek', disabled: true }, - { insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY' } }] }]; + { insert: [{ id: 'strata-web-search', name: SEARCH_PLUGIN, config: { provider: keyed ?? 'duckduckgo', keyEnv: 'STRATA_SEARCH_KEY', ...(searchMock ? { mock: searchMock } : {}) } }] }]; /** The models a helper agent may be started on: the table the model-choice plugin and the Harness's allow-list are written from. */ const subagentRoutes = routes.map(r => ({ provider: r.route, model: r.modelId, name: r.name, connection: r.connectionName, local: r.kind === 'local' })); const entries = [ diff --git a/apps/host/server/agent/turn-guard.mjs b/apps/host/server/agent/turn-guard.mjs new file mode 100644 index 00000000..f28ce3f4 --- /dev/null +++ b/apps/host/server/agent/turn-guard.mjs @@ -0,0 +1,105 @@ +/** + * 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. + * Pure (no I/O); the bridge feeds it what the turn shows and acts on what it answers. + * + * Why: a search-heavy /plan on a small model searched again after every refusal and rewrote its plan after every search until the context + * reached 100%, then the turn ended with no answer and no message. Nothing here relies on the model behaving: the app counts. + * + * searches-failed this many web searches in a row failed (web search was limited, or could not be reached) + * searches this many searches in one turn (a plan or an ordinary answer needs a handful, not dozens) + * rewrites a plan turn wrote its numbered plan from "1." again this many times + * context the context is nearly full: the Harness compaction did not keep up + * + * What the person is told is `guardNote`: fixed English sentences that are also in the interface catalog in all eight languages (the page + * translates a `delta` frame that carries `key`). Each says what happened and gives one next step. + */ + +export const GUARD_LIMITS = Object.freeze({ + failedSearches: 3, + searchesPlan: 10, + searchesTurn: 25, + planRewrites: 4, + contextFraction: 0.93, + /** A turn that ends with no words at all and a context this full is "out of room", not "nothing to say". */ + contextEmptyFraction: 0.85, +}); + +const SEARCH_TOOLS = new Set(['web_search']); +const 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; + +/** The plain sentences, keyed by reason. `values` are the slots the page fills in. */ +const NOTES = { + '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.', + 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.', + rewrites: 'I kept rewriting the plan, so I stopped here with the latest version. Tell me what to change, or approve it.', + 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.', + empty: 'I stopped without writing an answer. Send your message again, or say “continue”.', +}; +export const GUARD_NOTES = Object.freeze({ ...NOTES }); + +/** A `delta` frame the page shows as ordinary assistant text and translates (`key` is the English sentence). */ +export function guardNote(reason) { + const text = NOTES[reason]; + return text ? { type: 'delta', own: true, text: `\n\n${text}`, key: text, noteReason: reason } : null; +} + +export class TurnGuard { + /** + * @param {{plan?: boolean, contextMax?: number, limits?: Partial}} [options] + */ + constructor({ plan = false, contextMax = 0, limits = {} } = {}) { + this.plan = plan; this.contextMax = Number(contextMax) || 0; + this.limits = { ...GUARD_LIMITS, ...limits }; + this.seen = new Set(); + this.searches = 0; this.failedInARow = 0; this.failedTotal = 0; + this.rewrites = 0; this.written = ''; + this.reason = null; + } + + #fire(reason) { this.reason ??= reason; return this.reason; } + + /** A tool card frame (`agent-tool`). Counts a search once, when it has finished. Returns the reason to stop, or null. */ + card(tool) { + if (this.reason || !tool || !SEARCH_TOOLS.has(tool.name)) return this.reason; + const done = tool.state === 'done' || tool.state === 'error' || tool.state === 'denied'; + if (!done || this.seen.has(tool.id)) return this.reason; + this.seen.add(tool.id); + this.searches += 1; + const failed = tool.state === 'error' || SEARCH_FAILED.test(String(tool.result ?? '')); + if (failed) { this.failedInARow += 1; this.failedTotal += 1; } else this.failedInARow = 0; + if (this.failedInARow >= this.limits.failedSearches) return this.#fire('searches-failed'); + if (this.searches >= (this.plan ? this.limits.searchesPlan : this.limits.searchesTurn)) return this.#fire(this.failedTotal >= this.searches / 2 ? 'searches-failed' : 'searches'); + return this.reason; + } + + /** Text the assistant wrote (not our own lines). A plan turn that starts its numbered list again and again is rewriting. */ + text(delta) { + if (this.reason || !this.plan || !delta) return this.reason; + this.written += delta; + if (this.written.length > 200_000) this.written = this.written.slice(-100_000); + if (!delta.includes('\n') && !/\d[.)]\s/.test(delta)) return this.reason; + this.rewrites = (this.written.match(/(?:^|\n)[ \t]{0,3}1[.)][ \t]+\S/g) ?? []).length; + if (this.rewrites >= this.limits.planRewrites) return this.#fire('rewrites'); + return this.reason; + } + + /** What the context holds now (tokens of the last request). */ + context(tokens) { + if (this.reason || !this.contextMax || !Number.isFinite(tokens)) return this.reason; + if (tokens / this.contextMax >= this.limits.contextFraction) return this.#fire('context'); + return this.reason; + } + + /** + * 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, + * `wrote` whether any answer text was shown, `acted` whether tool cards were shown, `contextTokens` the last request's size. Returns a reason or null. + */ + silent({ ended, wrote, contextTokens, acted = false, stoppedByPerson = false }) { + if (this.reason) return this.reason; + if (stoppedByPerson || wrote) return null; + const kind = ended?.kind; + if (kind !== 'completed' && kind !== 'max-tokens') return null; // an error says why by itself; Stop is the person's own + if (this.contextMax && Number(contextTokens) / this.contextMax >= this.limits.contextEmptyFraction) return 'context'; + return acted ? null : 'empty'; // cards of work done are an answer of a kind; no cards and no words is not + } +} diff --git a/apps/host/src/components/PlanCard.tsx b/apps/host/src/components/PlanCard.tsx index acaa1618..920bb1d3 100644 --- a/apps/host/src/components/PlanCard.tsx +++ b/apps/host/src/components/PlanCard.tsx @@ -59,6 +59,7 @@ export function PlanCard({ chatId, planId }: { chatId: string | null | undefined return
{tr("Plan")}{planCount(plan)}
+ {plan.caution ?

{tr(plan.caution)}

: null} {proposed ?

{tr("Nothing runs until you approve.")}

: null} {proposed ?
void run(() => approvePlan(chatId, plan.id))}>{tr("Approve")} diff --git a/apps/host/src/components/SettingsTools.tsx b/apps/host/src/components/SettingsTools.tsx index 480a124a..b6ace950 100644 --- a/apps/host/src/components/SettingsTools.tsx +++ b/apps/host/src/components/SettingsTools.tsx @@ -130,7 +130,7 @@ export function SettingsTools({ preview }: { preview?: ToolsState }) {

{tr('Web search')}

- +