Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Turn guard: a search-heavy /plan that keeps failing is stopped by the app, and a full context never ends in silence
Niko122140b41da91666
diff --git a/apps/host/server/agent/README.md b/apps/host/server/agent/README.mdindex 8bfb7f4ae..22fed6721 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## PicturesPictures 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.mjsindex aa5ab5561..9589f785d 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 guessprojector.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.mjsindex 066391071..2c7e372ff 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.mjsindex 57d633348..cf5bda681 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('<html>please verify you are human: captcha</html>', { 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.mjsindex b82be8308..99d5a5cef 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, toolsconst 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.mjsnew file mode 100644index 000000000..f28ce3f46--- /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<typeof GUARD_LIMITS>}} [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.tsxindex acaa16187..920bb1d31 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 | undefinedreturn <section className="plan" data-state={plan.state} aria-label={tr("Plan")}><div className="plan__head"><b>{tr("Plan")}</b><span>{planCount(plan)}</span></div><PlanSteps plan={plan}/>+ {plan.caution ? <p className="plan__note" role="status">{tr(plan.caution)}</p> : null}{proposed ? <p className="plan__note">{tr("Nothing runs until you approve.")}</p> : null}{proposed ? <div className="plan__acts"><Btn size="sm" variant="primary" icon="check" disabled={busy || streaming} onClick={() => void run(() => approvePlan(chatId, plan.id))}>{tr("Approve")}</Btn>diff --git a/apps/host/src/components/SettingsTools.tsx b/apps/host/src/components/SettingsTools.tsxindex 480a124a7..b6ace950d 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 }) {<section className="settings-section"><h2 className="h4" style={{ marginBottom: 10 }}>{tr('Web search')}</h2><div className="st-card st-card--flush">- <Field label={tr('Where results come from')} hint={tr(keyed ? 'Searches use your own account with this service.' : 'Results come from DuckDuckGo. You do not need an account or a key.')}>+ <Field label={tr('Where results come from')} hint={tr(keyed ? 'Searches use your own account with this service.' : 'Results come from DuckDuckGo, or from Bing when DuckDuckGo is busy. You do not need an account or a key.')}><Select ariaLabel={tr('Where results come from')} value={state.search.provider} options={SEARCH_CHOICES} onChange={value => { setKey(''); void save({ search: { provider: value } }); }} /></Field>{keyed ? <Field label={tr('Your key')} hint={tr(state.search.keySet ? 'A key is saved on this computer. Enter a new one to replace it.' : 'Saved on this computer only. Strata never shows it again.')}>diff --git a/apps/host/src/lib/plan.ts b/apps/host/src/lib/plan.tsindex 09a6f0e70..e15bdcb23 100644--- a/apps/host/src/lib/plan.ts+++ b/apps/host/src/lib/plan.ts@@ -10,7 +10,7 @@ import { api, ApiError } from './client';export type PlanState = 'proposed' | 'approved' | 'rejected' | 'running' | 'paused' | 'done' | 'stopped';export type StepState = 'pending' | 'running' | 'done' | 'failed' | 'skipped';export interface PlanStep { id: string; text: string; detail?: string; summary?: string; state: StepState }-export interface Plan { id: string; title: string; source: 'plan' | 'goal'; state: PlanState; steps: PlanStep[] }+export interface Plan { id: string; title: string; source: 'plan' | 'goal'; state: PlanState; steps: PlanStep[]; /** A plain sentence (an interface string) when the app stopped the planning turn early. */ caution?: string }export interface QueuedMessage { id: string; text: string; deliverAt: 'step' | 'end' }const PLAN_STATES = ['proposed', 'approved', 'rejected', 'running', 'paused', 'done', 'stopped'];diff --git a/apps/host/src/lib/store.ts b/apps/host/src/lib/store.tsindex b38a25855..64ce3c3df 100644--- a/apps/host/src/lib/store.ts+++ b/apps/host/src/lib/store.ts@@ -1498,6 +1498,9 @@ export async function approvePlan(sessionId: string, planId: string) {/** "Start as goal" (and Resume on a paused plan): the host streams the run like any chat turn. */export async function startPlanGoal(planId: string) { await sendMessage('', { planId }); }+/** The text of a `delta` frame. A line from the app itself carries `key` (the English sentence) so it is shown in the person's language. */+const deltaText = (frame: Record<string, unknown>) => typeof frame.key === 'string' ? tr(frame.key, Array.isArray(frame.values) ? frame.values : undefined) : String(frame.text ?? '');+export async function sendMessage(text: string, options: { fromLoop?: boolean; goalAction?: 'resume'; planId?: string; shown?: string; title?: string; markdown?: boolean } = {}) {if (state.streaming) {// Typed while the assistant works: behind a running goal it waits in the queue; otherwise there is nothing to do but wait.@@ -1649,7 +1652,7 @@ export async function sendMessage(text: string, options: { fromLoop?: boolean; g} else if (type === 'agent') {patchSession(sessionId, s => ({ ...s, agents: updateAgent(s.agents ?? [], frame.agent) }));} else if (type === 'delta') {- patchAssistant((m) => { const content=m.content+String(frame.text??''); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,...(m.blocks?{blocks:appendText(m.blocks,String(frame.text??''))}:{}),tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; });+ patchAssistant((m) => { const content=m.content+deltaText(frame); if (m.reasoningStartedAt && m.reasoningMs === undefined) m = { ...m, reasoningMs: Date.now() - m.reasoningStartedAt }; const count=Math.max(1,Math.ceil((content.length+(m.reasoning?.length??0))/4)); return {...m,content,...(m.blocks?{blocks:appendText(m.blocks,deltaText(frame))}:{}),tokens:m.usageSource==='estimated'&&m.tps?m.tokens:count,inputTokens:m.inputTokens??Math.ceil((body.length+prior.reduce((n,p)=>n+p.content.length,0))/4),usageSource:'estimated'}; });} else if (type === 'deliverable') {const file = readDeliverable(frame);if (file) patchAssistant(m => ({ ...m, deliverables: mergeDeliverable(m.deliverables, file) }));diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.jsonindex d392b247e..7bff1dbf9 100644--- a/apps/host/src/locales/de.json+++ b/apps/host/src/locales/de.json@@ -1,5 +1,11 @@{"s0001": "% PCIe",+ "s7331": "Die Ergebnisse kommen von DuckDuckGo, oder von Bing, wenn DuckDuckGo ausgelastet ist. Sie brauchen kein Konto und keinen Schlüssel.",+ "s7321": "Die Websuche ist gerade eingeschränkt, deshalb habe ich die Suche beendet und mit dem weitergemacht, was ich habe. Versuchen Sie es in einer Minute erneut oder fügen Sie unter Einstellungen → Tools → Websuche einen Suchschlüssel hinzu.",+ "s7322": "Ich habe viel gesucht und aufgehört, damit dieser Chat nicht überläuft. Das ist mein Stand bisher. Sagen Sie mir, was ich als Nächstes nachschlagen soll.",+ "s7323": "Ich habe den Plan immer wieder umgeschrieben und höre hier mit der letzten Fassung auf. Sagen Sie mir, was ich ändern soll, oder genehmigen Sie ihn.",+ "s7324": "In diesem Chat ist mir der Platz ausgegangen, deshalb habe ich angehalten. Strata fasst die älteren Nachrichten zusammen, um Platz zu schaffen. Schreiben Sie „weiter“, um fortzufahren, oder starten Sie einen neuen Chat.",+ "s7325": "Ich habe angehalten, ohne eine Antwort zu schreiben. Senden Sie Ihre Nachricht erneut oder schreiben Sie „weiter“.","s7301": "Tippen Sie /loop, wie oft und dann, was zu tun ist. Zum Beispiel: /loop 10m prüfe, ob der Build besteht. Mit „stop after 3 answers“ endet es von selbst. Mit /loop stop halten Sie es an.","s7302": "Sagen Sie, was jedes Mal zu tun ist, nicht nur, wann es endet.","s7303": "Die Schleife ist fertig: Sie lief {0}-mal, wie gewünscht. Mit /loop starten Sie eine neue.",diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.jsonindex bb2df9408..86203261d 100644--- a/apps/host/src/locales/en.json+++ b/apps/host/src/locales/en.json@@ -1,5 +1,11 @@{"s0001": "% PCIe",+ "s7331": "Results come from DuckDuckGo, or from Bing when DuckDuckGo is busy. You do not need an account or a key.",+ "s7321": "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.",+ "s7322": "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.",+ "s7323": "I kept rewriting the plan, so I stopped here with the latest version. Tell me what to change, or approve it.",+ "s7324": "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.",+ "s7325": "I stopped without writing an answer. Send your message again, or say “continue”.","s7301": "Type /loop, how often, then what to do. For example: /loop 10m check whether the build passes. Add \"stop after 3 answers\" to end it by itself. Use /loop stop to stop.","s7302": "Say what to do each time, not only when to stop.","s7303": "The loop is done: it ran {0} times, as you asked. Type /loop to start another.",diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.jsonindex 7f8344dac..dffd2fbc8 100644--- a/apps/host/src/locales/es.json+++ b/apps/host/src/locales/es.json@@ -1,5 +1,11 @@{"s0001": "% PCIe",+ "s7331": "Los resultados vienen de DuckDuckGo, o de Bing cuando DuckDuckGo está ocupado. No necesitas cuenta ni clave.",+ "s7321": "La búsqueda web está limitada ahora mismo, así que dejé de buscar y seguí con lo que tengo. Inténtalo de nuevo en un minuto o añade una clave de búsqueda en Ajustes → Herramientas → Búsqueda web.",+ "s7322": "Busqué mucho y me detuve para que este chat no se llene. Esto es lo que tengo hasta ahora. Dime qué quieres que investigue después.",+ "s7323": "Seguí reescribiendo el plan, así que me detuve aquí con la última versión. Dime qué cambiar o apruébalo.",+ "s7324": "Me quedé sin espacio en este chat, así que me detuve. Strata está resumiendo los mensajes antiguos para liberar espacio. Escribe “continúa” para seguir o empieza un chat nuevo.",+ "s7325": "Me detuve sin escribir una respuesta. Envía tu mensaje de nuevo o escribe “continúa”.","s7301": "Escribe /loop, cada cuánto y luego qué hacer. Por ejemplo: /loop 10m comprueba si la compilación pasa. Añade \"stop after 3 answers\" para que termine solo. Usa /loop stop para pararlo.","s7302": "Indica qué hacer cada vez, no solo cuándo parar.","s7303": "El bucle terminó: se ejecutó {0} veces, como pediste. Escribe /loop para iniciar otro.",diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.jsonindex 93fbf815b..ee8d9188a 100644--- a/apps/host/src/locales/ja.json+++ b/apps/host/src/locales/ja.json@@ -1,5 +1,11 @@{"s0001": "% PCIe",+ "s7331": "結果は DuckDuckGo から取得し、DuckDuckGo が混み合っているときは Bing から取得します。アカウントもキーも不要です。",+ "s7321": "ウェブ検索が現在制限されているため、検索をやめて手元の情報で進めました。1分ほど待ってからもう一度試すか、「設定 → ツール → ウェブ検索」で検索キーを追加してください。",+ "s7322": "検索を重ねたため、このチャットがいっぱいにならないよう止めました。ここまでの内容は以上です。次に調べることを教えてください。",+ "s7323": "計画を何度も書き直していたため、最新の版でここで止めました。変更したい点を教えるか、承認してください。",+ "s7324": "このチャットの空きがなくなったため、止めました。Strata が古いメッセージを要約して空きを作っています。続けるには「続けて」と送るか、新しいチャットを始めてください。",+ "s7325": "回答を書かずに止まってしまいました。もう一度メッセージを送るか、「続けて」と送ってください。","s7301": "/loop、間隔、やることの順に入力します。例:/loop 10m ビルドが通るか確認する。「stop after 3 answers」を付けると自動で止まります。止めるときは /loop stop。","s7302": "止める条件だけでなく、毎回やることも書いてください。","s7303": "ループが終わりました。ご指定どおり {0} 回実行しました。もう一度始めるには /loop と入力します。",diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.jsonindex 5f8aca021..0989e085b 100644--- a/apps/host/src/locales/ko.json+++ b/apps/host/src/locales/ko.json@@ -1,5 +1,11 @@{"s0001": "% PCIe",+ "s7331": "결과는 DuckDuckGo에서 가져오며, DuckDuckGo가 바쁠 때는 Bing에서 가져옵니다. 계정이나 키는 필요하지 않습니다.",+ "s7321": "웹 검색이 지금 제한되어 있어서 검색을 멈추고 가진 정보로 이어갔습니다. 1분 뒤에 다시 시도하거나 설정 → 도구 → 웹 검색에서 검색 키를 추가하세요.",+ "s7322": "검색을 많이 해서 이 대화가 가득 차지 않도록 멈췄습니다. 지금까지 알아낸 내용입니다. 다음에 무엇을 찾아볼지 알려 주세요.",+ "s7323": "계획을 계속 다시 쓰고 있어서 최신 버전으로 여기서 멈췄습니다. 바꿀 부분을 알려 주시거나 승인해 주세요.",+ "s7324": "이 대화의 공간이 다 차서 멈췄습니다. Strata가 오래된 메시지를 요약해 공간을 만들고 있습니다. 계속하려면 “계속해”라고 보내거나 새 대화를 시작하세요.",+ "s7325": "답변을 쓰지 못하고 멈췄습니다. 메시지를 다시 보내거나 “계속해”라고 보내 주세요.","s7301": "/loop, 얼마나 자주, 그리고 할 일을 순서대로 입력하세요. 예: /loop 10m 빌드가 통과하는지 확인. \"stop after 3 answers\"를 붙이면 저절로 끝납니다. 멈추려면 /loop stop.","s7302": "멈출 때만이 아니라 매번 할 일도 적어 주세요.","s7303": "반복이 끝났습니다. 요청하신 대로 {0}번 실행했습니다. 다시 시작하려면 /loop를 입력하세요.",diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.jsonindex 4b9ad438e..627a447dd 100644--- a/apps/host/src/locales/pt.json+++ b/apps/host/src/locales/pt.json@@ -1,5 +1,11 @@{"s0001": "% PCIe",+ "s7331": "Os resultados vêm do DuckDuckGo, ou do Bing quando o DuckDuckGo está ocupado. Você não precisa de conta nem de chave.",+ "s7321": "A pesquisa na web está limitada agora, então parei de pesquisar e segui com o que tenho. Tente de novo em um minuto ou adicione uma chave de pesquisa em Configurações → Ferramentas → Pesquisa na web.",+ "s7322": "Pesquisei bastante e parei para que este chat não encha. Isto é o que tenho até agora. Diga o que devo investigar em seguida.",+ "s7323": "Fiquei reescrevendo o plano, então parei aqui com a versão mais recente. Diga o que mudar ou aprove.",+ "s7324": "Fiquei sem espaço neste chat, então parei. O Strata está resumindo as mensagens antigas para abrir espaço. Diga “continue” para seguir ou comece um chat novo.",+ "s7325": "Parei sem escrever uma resposta. Envie sua mensagem de novo ou diga “continue”.","s7301": "Digite /loop, com que frequência e depois o que fazer. Por exemplo: /loop 10m verifique se a compilação passa. Acrescente \"stop after 3 answers\" para terminar sozinho. Use /loop stop para parar.","s7302": "Diga o que fazer a cada vez, não só quando parar.","s7303": "O loop terminou: rodou {0} vezes, como você pediu. Digite /loop para iniciar outro.",diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.jsonindex a365c401b..1fe03b17e 100644--- a/apps/host/src/locales/ru.json+++ b/apps/host/src/locales/ru.json@@ -1,5 +1,11 @@{"s0001": "% PCIe",+ "s7331": "Результаты берутся из DuckDuckGo, а когда он перегружен, из Bing. Учётная запись и ключ не нужны.",+ "s7321": "Веб-поиск сейчас ограничен, поэтому я прекратил поиск и продолжил с тем, что есть. Повторите через минуту или добавьте ключ поиска в Настройки → Инструменты → Поиск в интернете.",+ "s7322": "Я много искал и остановился, чтобы этот чат не переполнился. Вот что у меня есть на данный момент. Скажите, что искать дальше.",+ "s7323": "Я всё время переписывал план, поэтому остановился на последней версии. Скажите, что изменить, или одобрите его.",+ "s7324": "В этом чате закончилось место, поэтому я остановился. Strata сжимает старые сообщения, чтобы освободить место. Напишите «продолжай», чтобы идти дальше, или начните новый чат.",+ "s7325": "Я остановился, не написав ответ. Отправьте сообщение ещё раз или напишите «продолжай».","s7301": "Введите /loop, как часто и что делать. Например: /loop 10m проверь, проходит ли сборка. Добавьте «stop after 3 answers», чтобы цикл закончился сам. Чтобы остановить, введите /loop stop.","s7302": "Напишите, что делать каждый раз, а не только когда остановиться.","s7303": "Цикл завершён: он выполнился {0} раз, как вы просили. Введите /loop, чтобы запустить новый.",diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.jsonindex 12988d33f..6df5fc02b 100644--- a/apps/host/src/locales/zh.json+++ b/apps/host/src/locales/zh.json@@ -1,5 +1,11 @@{"s0001": "% PCIe",+ "s7331": "结果来自 DuckDuckGo;DuckDuckGo 繁忙时来自 Bing。不需要账号或密钥。",+ "s7321": "网络搜索目前受到限制,所以我停止了搜索,用已有的信息继续。请一分钟后再试,或在“设置 → 工具 → 网络搜索”中添加搜索密钥。",+ "s7322": "我搜索了很多次,为了不让这次对话被占满而停下了。以上是目前的结果。请告诉我接下来要查什么。",+ "s7323": "我一直在重写计划,所以停在这里,保留了最新版本。请告诉我要改什么,或直接批准。",+ "s7324": "这次对话的空间用完了,所以我停了下来。Strata 正在总结较早的消息来腾出空间。说“继续”即可接着做,或者开始新的对话。",+ "s7325": "我停了下来,但没有写出回答。请再发一次消息,或说“继续”。","s7301": "输入 /loop,再写多久一次,然后写要做什么。例如:/loop 10m 检查构建是否通过。加上“stop after 3 answers”可让它自动结束。用 /loop stop 停止。","s7302": "请写明每次要做什么,而不只是何时停止。","s7303": "循环已完成:按你的要求运行了 {0} 次。输入 /loop 可再开始一个。",diff --git a/apps/host/tests/agent-turn-guard.test.mjs b/apps/host/tests/agent-turn-guard.test.mjsnew file mode 100644index 000000000..27bab7c9a--- /dev/null+++ b/apps/host/tests/agent-turn-guard.test.mjs@@ -0,0 +1,152 @@+// The turn guard: a search-heavy /plan that keeps failing searches and rewriting its plan is stopped by the app and ends with a plain message;+// a context at 100% never ends silently. The pure counting always runs; the end-to-end ones need a built Harness (STRATA_HARNESS_DIR) and+// run the real search code on a pretend web that refuses (no network).+import test from 'node:test';+import assert from 'node:assert/strict';+import { mkdtempSync, mkdirSync, rmSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { TurnGuard, GUARD_LIMITS, GUARD_NOTES, guardNote } from '../server/agent/turn-guard.mjs';+import { startScriptedWorker } from './helpers/scripted-worker.mjs';+import { createAgentBridge } from '../server/agent/agent-bridge.mjs';+import { resolveHarness } from '../server/agent/harness-runtime.mjs';++const HARNESS = process.env.STRATA_HARNESS_DIR;+const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;++const search = (id, state, result = '') => ({ id, name: 'web_search', state, result });+const LIMITED = 'Web search is limited right now. Try again in a minute, or add a search key (Exa, Perplexity or DeepSeek) in Settings → Tools → Web search. Do not retry this search';++test('three failed searches in a row stop the turn; a search that worked starts the count again', () => {+ const g = new TurnGuard({ plan: true, contextMax: 32768 });+ assert.equal(g.card(search('a', 'running')), null, 'a running search is not counted yet');+ assert.equal(g.card(search('a', 'error', LIMITED)), null);+ assert.equal(g.card(search('a', 'error', LIMITED)), null, 'the same card twice is one search');+ assert.equal(g.card(search('b', 'done', 'three results')), null);+ assert.equal(g.card(search('c', 'error', LIMITED)), null);+ assert.equal(g.card(search('d', 'done', LIMITED)), null, 'a refusal that arrives as a normal result still counts');+ assert.equal(g.card(search('e', 'error', LIMITED)), 'searches-failed');+ assert.equal(g.card(search('f', 'error', LIMITED)), 'searches-failed', 'once stopped it stays stopped');+ assert.equal(g.searches, 5);+});++test('other tools are not searches; too many searches in one turn stop it even when they work', () => {+ const g = new TurnGuard({ plan: true });+ for (let i = 0; i < 50; i++) assert.equal(g.card({ id: `r${i}`, name: 'read', state: 'done' }), null);+ for (let i = 0; i < GUARD_LIMITS.searchesPlan - 1; i++) assert.equal(g.card(search(`s${i}`, 'done', 'ok')), null);+ assert.equal(g.card(search('last', 'done', 'ok')), 'searches');+ const t = new TurnGuard({ plan: false });+ for (let i = 0; i < GUARD_LIMITS.searchesTurn - 1; i++) assert.equal(t.card(search(`s${i}`, 'done', 'ok')), null);+ assert.equal(t.card(search('last', 'done', 'ok')), 'searches');+});++test('a plan turn that writes its numbered plan from 1. again and again is stopped; a single plan is not', () => {+ const g = new TurnGuard({ plan: true });+ const plan = '## Plan\n\n1. First\n2. Second\n3. Third\n\n';+ let reason = null;+ for (let i = 0; i < GUARD_LIMITS.planRewrites - 1; i++) reason ??= g.text(plan);+ assert.equal(reason, null, `${GUARD_LIMITS.planRewrites - 1} versions are fine`);+ assert.equal(g.text(plan), 'rewrites');+ const one = new TurnGuard({ plan: true });+ for (const piece of ['Some looking around.\n\n## Plan\n\n', '1. First\n', '2. Second\n', ' 1. a sub point\n', '3. Third\n']) assert.equal(one.text(piece), null, piece);+ const ordinary = new TurnGuard({ plan: false });+ for (let i = 0; i < 10; i++) assert.equal(ordinary.text(plan), null, 'only a plan turn counts rewrites');+});++test('a nearly full context stops the turn; a normal one does not', () => {+ const g = new TurnGuard({ contextMax: 10000 });+ assert.equal(g.context(5000), null);+ assert.equal(g.context(9200), null);+ assert.equal(g.context(9300), 'context');+ assert.equal(new TurnGuard({ contextMax: 0 }).context(1e9), null, 'an unknown window is never guessed');+});++test('a turn that ends with no words always gets a plain message: out of room, or nothing written', () => {+ const g = new TurnGuard({ contextMax: 10000 });+ const done = { kind: 'completed' };+ assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700 }), 'context');+ assert.equal(g.silent({ ended: { kind: 'max-tokens' }, wrote: false, contextTokens: 9000 }), 'context');+ assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 3000 }), 'empty');+ assert.equal(g.silent({ ended: done, wrote: false, acted: true, contextTokens: 3000 }), null, 'cards of finished work are an answer of a kind');+ assert.equal(g.silent({ ended: done, wrote: false, acted: true, contextTokens: 9700 }), 'context', 'but a full context is never silent');+ assert.equal(g.silent({ ended: done, wrote: true, contextTokens: 9700 }), null, 'there are words: nothing to add');+ assert.equal(g.silent({ ended: { kind: 'error', error: { message: 'x' } }, wrote: false, contextTokens: 9700 }), null, 'an error says why by itself');+ assert.equal(g.silent({ ended: done, wrote: false, contextTokens: 9700, stoppedByPerson: true }), null, 'Stop is the person\'s own');+});++test('every message is a plain sentence with a next step, carries its interface key, and is in the catalog in all eight languages', () => {+ const langs = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko'];+ const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(readFileSync(new URL(`../src/locales/${l}.json`, import.meta.url), 'utf8'))]));+ const idOf = text => Object.entries(catalogs.en).find(([, v]) => v === text)?.[0];+ for (const [reason, text] of Object.entries(GUARD_NOTES)) {+ const frame = guardNote(reason);+ assert.equal(frame.type, 'delta'); assert.equal(frame.key, text); assert.equal(frame.own, true);+ assert.ok(text.length < 220, reason);+ assert.match(text, /(Try again|Tell me|Say|Send|approve)/i, `${reason} gives a next step`);+ const id = idOf(text);+ assert.ok(id, `${reason} is in the English catalog`);+ for (const l of langs) assert.ok(catalogs[l][id]?.trim(), `${reason} in ${l}`);+ }+ assert.match(GUARD_NOTES.context, /ran out of room/);+});++// ------------------------------------------------------------------------------------------------ with the real Harness++async function rig(t, options = {}) {+ const worker = await startScriptedWorker({ chunkDelayMs: 5 });+ const dir = mkdtempSync(join(tmpdir(), 'strata-guard-'));+ const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });+ const logs = [];+ const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [{ id: 'i', label: 'S', baseUrl: worker.url, modelId: 'scripted-model', context: options.context ?? 32768, slots: 2 }], connections: () => [],+ env: process.env, startTimeoutMs: 90_000, searchMock: 'limited', log: l => logs.push(l) });+ t.after(async () => { await bridge.close(); await worker.close(); try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ } });+ return { worker, bridge, ws, logs, base: (chatId, onFrame) => ({ chatId, workspacePath: ws, mode: 'manual', onFrame }) };+}+const words = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');++test('a search-heavy /plan on a web that keeps refusing stops after 3 failed searches, proposes the plan it has, and says why', { skip }, async (t) => {+ const r = await rig(t);+ const out = [];+ await r.bridge.planCommand({ ...r.base('p1', f => out.push(f)), line: 'SCRIPT:searchloop' });+ const cards = out.filter(f => f.type === 'agent-tool' && f.tool.name === 'web_search' && ['done', 'error'].includes(f.tool.state));+ assert.ok(cards.length >= 3 && cards.length <= 4, `searches stopped at the limit (${cards.length})`);+ assert.ok(cards.some(f => /Web search is limited right now/.test(f.tool.result ?? '')), 'the tool said web search is limited');+ assert.equal(out.filter(f => f.type === 'error').length, 0, 'not an error: a normal end');+ const done = out.find(f => f.type === 'done');+ assert.ok(done && !done.cancelled, 'the turn ended normally');+ const plan = out.find(f => f.type === 'plan');+ assert.equal(plan?.event, 'proposed', 'the plan it had is offered');+ assert.equal(plan.plan.steps.length, 3);+ assert.equal(plan.plan.caution, GUARD_NOTES['searches-failed'], 'and the card says why it stopped early');+ const requests = r.worker.requests.filter(q => q.directive === 'searchloop');+ assert.ok(requests.length <= 5, `the model was not asked again and again (${requests.length} requests)`);+ assert.ok(r.logs.some(l => /turn guard: searches-failed/.test(l)));+});++test('an ordinary turn whose searches keep failing ends with the plain sentence as its last words', { skip }, async (t) => {+ const r = await rig(t);+ const out = [];+ await r.bridge.runTurn({ ...r.base('c1', f => out.push(f)), message: 'SCRIPT:searchloop' });+ assert.equal(out.filter(f => f.type === 'error').length, 0);+ assert.ok(out.find(f => f.type === 'done'));+ const note = out.filter(f => f.type === 'delta' && f.key).at(-1);+ assert.equal(note?.key, GUARD_NOTES['searches-failed']);+ assert.match(words(out), /Settings → Tools → Web search/);+ assert.ok(out.findIndex(f => f.key) < out.findIndex(f => f.type === 'done'), 'the sentence comes before the end of the turn');+});++test('a context at 100% with no answer is never silent: the plain message comes, and the older messages are summarised', { skip }, async (t) => {+ const r = await rig(t, { context: 32768 });+ const out = [];+ await r.bridge.runTurn({ ...r.base('f1', f => out.push(f)), message: 'SCRIPT:bloat 32000' });+ assert.equal(out.filter(f => f.type === 'error').length, 0);+ assert.ok(out.find(f => f.type === 'done'));+ assert.equal(out.filter(f => f.type === 'delta' && f.key).at(-1)?.key, GUARD_NOTES.context);+ assert.match(words(out), /ran out of room/);+ await new Promise(res => setTimeout(res, 1500));+ const compacted = r.logs.find(l => /compact after a stopped turn/.test(l));+ assert.match(compacted ?? '', /compact after a stopped turn: \w+/, `compaction was asked for and the Harness answered (${compacted})`);+ const out2 = [];+ await r.bridge.runTurn({ ...r.base('f2', f => out2.push(f)), message: 'SCRIPT:bloat 3000' });+ assert.equal(out2.filter(f => f.type === 'delta' && f.key).at(-1)?.key, GUARD_NOTES.empty, 'no words at all, plenty of room: still a message');+});diff --git a/apps/host/tests/helpers/scripted-worker.mjs b/apps/host/tests/helpers/scripted-worker.mjsindex 2ebee5e8b..7676ffc5b 100644--- a/apps/host/tests/helpers/scripted-worker.mjs+++ b/apps/host/tests/helpers/scripted-worker.mjs@@ -27,6 +27,8 @@* SCRIPT:planreply a reply ending with a numbered plan of three steps (each step's text carries SCRIPT:goalstep)* SCRIPT:call <tool> <json> one call to any tool with the given JSON arguments* SCRIPT:multi <json> {"calls":[[tool,args],...],"say":"final text"}: all the calls in one reply, then the text once their results are in+ * SCRIPT:searchloop a model that never stops: every reply rewrites a numbered plan and calls web_search again with a new query+ * SCRIPT:bloat <prompt tokens> a reply that is only thinking (no answer text), with usage reporting that many prompt tokens (a context at 100%)** A request whose last message is a tool result is answered with a text that quotes the result.*/@@ -78,9 +80,10 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });const id = `chatcmpl-${requests.length}`;const send = (delta, finish = null, extra = {}) => res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`);+ let promptTokens = 100 + messages.length;const finish = (reason, tokens = 10) => {send({}, reason);- res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: 100 + messages.length, completion_tokens: tokens, total_tokens: 100 + messages.length + tokens } })}\n\n`);+ res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created: 0, model: body.model, choices: [], usage: { prompt_tokens: promptTokens, completion_tokens: tokens, total_tokens: promptTokens + tokens } })}\n\n`);res.write('data: [DONE]\n\n'); res.end();};const toolCall = async (name, call) => {@@ -116,6 +119,26 @@ export async function startScriptedWorker({ port = 0, chunkDelayMs = 40, model =if (/biggest lever/.test(t) && !answered && last.role !== 'tool') return say(['{"step": 2, "why": "The layout decided in step 1 shapes everything after it."}']);if (/IMPROVEMENT PLAN/.test(t) && !answered && last.role !== 'tool') return say(['## Better path\n\n', '1. Improve the first attempt SCRIPT:goalstep\n', '2. Polish and check SCRIPT:goalstep\n']);}+ if (directive?.[1] === 'searchloop') {+ const n = requests.filter(r => r.directive === 'searchloop').length;+ send({ role: 'assistant', content: `Plan, version ${n}:++## Search plan++1. Search for the topic+2. Read the best result+3. Write the summary++` });+ const argsJson = JSON.stringify({ queries: [`topic search number ${n}`] });+ send({ tool_calls: [{ index: 0, id: `call_${requests.length}`, type: 'function', function: { name: 'web_search', arguments: argsJson } }] });+ return finish('tool_calls', 60);+ }+ if (directive?.[1] === 'bloat') {+ promptTokens = parseInt((directive[2] ?? '').trim(), 10) || 100;+ send({ role: 'assistant', content: '', reasoning_content: 'Thinking about it for a long time and never getting to the answer.' });+ return finish('stop', 20);+ }if (directive?.[1] === 'goalstep') {// A goal round: read the goal, mark it complete, then say so.if (!toolMessages.length) return toolCall('get_goal', {});diff --git a/apps/host/tests/runtime-api.test.mjs b/apps/host/tests/runtime-api.test.mjsindex 42fdd2734..a1259f5bd 100644--- a/apps/host/tests/runtime-api.test.mjs+++ b/apps/host/tests/runtime-api.test.mjs@@ -25,6 +25,8 @@ test('HTTP gateway lists all models, routes both protocols exactly, and isolatesconst list=(await call('/v1/models')).body.data;assert.equal(list.length,2);assert.deepEqual(new Set(list.map(i=>i.id)),new Set([a.body.instance.apiModelId,b.body.instance.apiModelId]));assert.equal((await call('/v1/chat/completions',{model:'missing',messages:[{role:'user',content:'hello'}]})).status,409);assert.equal((await call('/v1/messages',{messages:[{role:'user',content:'hello'}]})).status,409);+ assert.equal((await call('/v1/v1/messages',{messages:[{role:'user',content:'hello'}]})).status,409,'an Anthropic client given the /v1 base reaches the same route');+ assert.notEqual((await call('/v1/v1/chat/completions',{model:'missing',messages:[{role:'user',content:'hello'}]})).status,409,'only the messages path is aliased');const controllers=[new AbortController(),new AbortController()];const responseA=await fetch(base+'/v1/chat/completions',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({stream:true,model:a.body.instance.apiModelId,messages:[{role:'user',content:'hello'}]}),signal:controllers[0].signal});const responseB=await fetch(base+'/v1/messages',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({stream:true,model:b.body.instance.apiModelId,messages:[{role:'user',content:'hello'}]}),signal:controllers[1].signal});