okami.mom/strata

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

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
30.6 KiB496 linesraw
1/**
2 * Pure projections from Harness facts to the frames the chat UI already renders.
3 *
4 * No I/O here, so the mapping can be tested without an agent. The inputs are the two things a
5 * `session/follow` stream carries: durable session events (`tool/call`, `approval/asked`,
6 * `tool/result`, `turn/end`, ...) and the process-local `assistant-stream` frames (text and
7 * reasoning deltas, usage).
8 */
9
10import { toolUpdate, TokenCount, fmtTokens } from './status.mjs';
11import { askFor } from './ask.mjs';
12import { FIT_TEXT, fill } from './context-fit.mjs';
13import { isContextOverflow } from './context-budget.mjs';
14import { ToolDraft, cutCalls } from './reply-cut.mjs';
15
16const SHELL = new Set(['pwsh', 'bash', 'job_kill', 'job_output', 'job_list']);
17const WRITE = new Set(['write', 'edit']);
18const READ = new Set(['read', 'glob', 'grep', 'read_image', 'working_directory', 'todo_write', 'get_goal', 'list_agents', 'skill', 'present']);
19
20/** Delegation tools have no card: the helper agents show as rows, and the tool's raw reply ("started subagent <id>") is not for the person. */
21export const NO_CARD = new Set(['subagent', 'subagent_fork', 'send_message', 'interrupt_agent', 'list_agents']);
22
23export function toolScope(name) {
24  if (SHELL.has(name)) return 'shell';
25  if (WRITE.has(name)) return 'write';
26  if (READ.has(name)) return 'read';
27  return 'connected';
28}
29
30/** Shown on a card the mode refused (Plan, Bypass): the model's own error text would say "the user rejected". */
31export const NOT_IN_MODE = 'Not allowed in this mode. Nothing ran.';
32
33const clip = (value, max) => {
34  const text = String(value ?? '');
35  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
36};
37
38export function parseArguments(raw) {
39  if (raw && typeof raw === 'object') return raw;
40  try { const v = JSON.parse(String(raw ?? '{}')); return v && typeof v === 'object' ? v : {}; } catch { return {}; }
41}
42
43/**
44 * One plain sentence and one short detail per tool, so a card never shows raw JSON or an internal tool name as its
45 * explanation. Unknown tools (a connected MCP server's) fall back to a generic sentence with their arguments.
46 */
47const WORDS = {
48  read: a => ['Reads a file.', a.file_path ?? a.path],
49  glob: a => ['Looks for files by name.', a.pattern],
50  grep: a => ['Searches inside files.', a.pattern ?? a.query],
51  read_image: a => ['Looks at a picture.', a.file_path ?? a.path],
52  working_directory: () => ['Checks which folder it is working in.', ''],
53  todo_write: a => ['Updates its to-do list.', Array.isArray(a.todos) ? a.todos.map(t => t?.content ?? t?.title ?? '').filter(Boolean).join('; ') : ''],
54  skill: a => ['Uses a saved skill.', a.name ?? a.skill],
55  present: a => ['Shows you a result.', a.file_path ?? a.path ?? a.title],
56  create_goal: a => ['Sets a goal to work towards.', a.objective],
57  update_goal: a => ['Updates the goal.', a.objective ?? a.status ?? ''],
58  get_goal: () => ['Checks the current goal.', ''],
59  web_fetch: a => ['Opens a web page.', a.url],
60  web_search: a => ['Searches the web.', Array.isArray(a.queries) ? a.queries.join('; ') : a.query],
61  workflow: a => ['Runs a multi-step plan.', a.description ?? a.name ?? ''],
62  job_list: () => ['Checks the background tasks.', ''],
63  job_output: a => ['Reads what a background task printed.', a.job_id ?? a.id],
64  job_kill: a => ['Stops a background task.', a.job_id ?? a.id],
65  lsp: a => ['Looks up how the code fits together.', a.file_path],
66};
67
68/**
69 * What a card says it is doing, in the person's words: [while it runs, when it worked, when it failed]. The UI translates
70 * these fixed sentences and writes the target (a file path, the command) beside them, so a row never shows `pwsh · Ran`.
71 */
72const VERBS = {
73  write: ['Writing a file', 'Wrote a file', "Couldn't write the file"],
74  edit: ['Changing a file', 'Changed a file', "Couldn't change the file"],
75  read: ['Reading a file', 'Read a file', "Couldn't read the file"],
76  read_image: ['Looking at a picture', 'Looked at a picture', "Couldn't look at the picture"],
77  glob: ['Searching for files', 'Searched for files', "Couldn't search for files"],
78  grep: ['Searching inside files', 'Searched inside files', "Couldn't search inside files"],
79  pwsh: ['Running a command', 'Ran a command', 'The command failed'],
80  bash: ['Running a command', 'Ran a command', 'The command failed'],
81  web_fetch: ['Opening a web page', 'Opened a web page', "Couldn't open the web page"],
82  web_search: ['Searching the web', 'Searched the web', "Couldn't search the web"],
83  create_goal: ['Setting the goal', 'Set the goal', "Couldn't set the goal"],
84  update_goal: ['Updating the goal', 'Updated the goal', "Couldn't update the goal"],
85  get_goal: ['Checking the goal', 'Checked the goal', "Couldn't check the goal"],
86  skill: ['Loading your skill', 'Loaded your skill', "Couldn't load the skill"],
87  todo_write: ['Updating its to-do list', 'Updated its to-do list', "Couldn't update its to-do list"],
88  present: ['Showing you a result', 'Showed you a result', "Couldn't show the result"],
89  working_directory: ['Checking the folder', 'Checked the folder', "Couldn't check the folder"],
90  job_list: ['Checking background tasks', 'Checked background tasks', "Couldn't check background tasks"],
91  job_output: ['Reading a background task', 'Read a background task', "Couldn't read the background task"],
92  job_kill: ['Stopping a background task', 'Stopped a background task', "Couldn't stop the background task"],
93};
94const GENERIC_VERBS = ['Using a tool', 'Used a tool', 'The tool failed'];
95/** The browser tool server's tools (Settings -> Tools): the card says what happened to the page, not the tool's internal name. */
96const BROWSER_VERBS = {
97  browser_navigate: ['Opening a page in the browser', 'Opened a page in the browser', "Couldn't open the page"],
98  browser_click: ['Clicking on the page', 'Clicked on the page', "Couldn't click on the page"],
99  browser_hover: ['Pointing at the page', 'Pointed at the page', "Couldn't point at the page"],
100  browser_type: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"],
101  browser_fill_form: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"],
102  browser_press_key: ['Typing on the page', 'Typed on the page', "Couldn't type on the page"],
103  browser_snapshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"],
104  browser_take_screenshot: ['Looking at the page', 'Looked at the page', "Couldn't look at the page"],
105  browser_evaluate: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"],
106  browser_run_code: ['Running a small program on the page', 'Ran a small program on the page', "Couldn't run the program on the page"],
107  browser_wait_for: ['Waiting for the page', 'Waited for the page', "Couldn't wait for the page"],
108  browser_navigate_back: ['Going back a page', 'Went back a page', "Couldn't go back"],
109  browser_tabs: ['Managing browser tabs', 'Managed browser tabs', "Couldn't manage the browser tabs"],
110  browser_close: ['Closing the browser page', 'Closed the browser page', "Couldn't close the browser page"],
111};
112const BROWSER_GENERIC = ['Using the browser', 'Used the browser', 'The browser step failed'];
113const BROWSER_PREFIX = 'mcp__browser__', INSTRUCTIONS_PREFIX = 'mcp__strata-instructions__', COMMANDS_PREFIX = 'mcp__strata-commands__';
114/** The person's own tool's name as they wrote it (spaces for underscores). */
115const ownToolName = name => name.replace(/^mcp__strata-(?:instructions|commands)__/, '').replace(/_/g, ' ');
116/** The three sentences (running, worked, failed) for a tool, and whether this is one the app knows by name. */
117function verbsFor(name) {
118  if (VERBS[name]) return { verbs: VERBS[name], known: true };
119  if (name.startsWith(BROWSER_PREFIX)) return { verbs: BROWSER_VERBS[name.slice(BROWSER_PREFIX.length)] ?? BROWSER_GENERIC, known: true };
120  if (name.startsWith(INSTRUCTIONS_PREFIX)) return { verbs: ['Reading your instructions', 'Read your instructions', "Couldn't read your instructions"], known: true };
121  if (name.startsWith(COMMANDS_PREFIX)) return { verbs: ['Running your tool', 'Ran your tool', 'Your tool failed'], known: true };
122  return { verbs: GENERIC_VERBS, known: false };
123}
124
125/** The sentence for a card in this state (the first for a running or waiting card). */
126export function toolVerb(name, state) {
127  const v = verbsFor(name).verbs;
128  return state === 'error' ? v[2] : state === 'done' ? v[1] : v[0];
129}
130/** The ToolCall fields the card needs, from one Harness tool call. */
131export function presentTool({ callId, name, args, reason = null }) {
132  const scope = toolScope(name);
133  const words = WORDS[name]?.(args);
134  const preview = scope === 'shell' && !words ? args.command ?? ''
135    : scope === 'write' ? args.file_path ?? args.path ?? args.filePath ?? ''
136      : words ? words[1] ?? '' : name.startsWith(INSTRUCTIONS_PREFIX) || name.startsWith(COMMANDS_PREFIX) ? ownToolName(name) : /^mcp__browser__browser_(evaluate|run_code)$/.test(name) ? '' : args.file_path ?? args.path ?? args.pattern ?? args.url ?? args.element ?? args.query ?? args.text ?? args.action ?? (Object.keys(args).length ? JSON.stringify(args) : '');
137  const effect = reason ?? (words ? words[0] : scope === 'shell' ? (args.description ?? 'Runs a command in the workspace.')
138    : scope === 'write' ? 'Changes a file in the workspace.'
139      : scope === 'read' ? 'Reads from the workspace.' : 'Uses a connected tool.');
140  return { id: callId, name, args, preview: clip(preview, 600), effect: clip(effect, 400), scope, verb: toolVerb(name, 'running'), target: clip(verbsFor(name).known ? preview : name, 300), ask: askFor(name, args, typeof args.description === 'string' ? args.description : null) };
141}
142
143/** A tool's failure in plain words, or null when there is nothing better than the original text. */
144export function plainToolError(text) {
145  const t = String(text ?? '');
146  if (/non-public ip|enotfound|getaddrinfo|web fetch failed|econnrefused|econnreset|etimedout|fetch failed/i.test(t)) return 'That web page could not be opened. Check the address and your internet connection.';
147  if (/invalid arguments|missing required property|not a declared property/i.test(t)) return 'The assistant asked this tool in the wrong way. It will usually try again.';
148  if (/unknown or no longer available/i.test(t)) return 'That skill is not available.';
149  if (/cannot modify|must (?:first )?be read|has not been read|changed since/i.test(t)) return 'The file could not be changed. It may need to be read again first, or it changed in the meantime.';
150  if (/sandbox|access denied|permission denied|eacces|eperm/i.test(t)) return 'The computer did not allow this.';
151  if (/timed out|timeout/i.test(t)) return 'This took too long and was stopped.';
152  if (/does not declare image input|image input/i.test(t)) return 'Picture reading is off for this model. Open Models and turn on Read pictures for it (load it again if it is a local model), or choose a model that reads pictures.';
153  if (/extension|not a supported image|cannot read/i.test(t)) return 'This file could not be read.';
154  return null;
155}
156
157/** A failed tool's result: the plain sentence first, the original text after it (the card's disclosure is the Details). */
158export function withPlain(raw) {
159  const plain = plainToolError(raw);
160  return plain ? `${plain}\n\nDetails: ${raw.replace(/^Error:\s*/, '')}` : raw;
161}
162
163/** What a launch that printed nothing proves, and no more. */
164export const LAUNCHED_TEXT = 'The command finished without an error, so the program was started. Strata cannot confirm that a window or page actually opened.';
165
166/** A command whose whole point is to open something: it has no output to show when it worked. */
167const LAUNCH = /(^|[\s;|&(])(start-process|start|invoke-item|ii|explorer(?:\.exe)?|xdg-open|open|notepad(?:\.exe)?|code)(?=[\s;|&)]|$)/i;
168
169/**
170 * A command that succeeded and printed nothing says so in words (the card used to show "(no output)" under a "Ran" that could not
171 * tell the person whether anything happened). Opening a folder or a window is not something a command can prove it did, so the
172 * sentence says only what is known.
173 */
174export function outcomeText(tool, text, args = {}) {
175  if (tool === 'pwsh' || tool === 'bash') {
176    // In the read-only modes PowerShell runs in Constrained Language Mode and complains about the Harness's own output-encoding line:
177    // noise appended after a command that worked. It says nothing about the command, so it is not shown.
178    text = text.replace(/\r?\n?\[stderr\]\r?\n(?:Cannot create type\. Only core types are supported in this language mode\.[\s\S]*?CannotCreateTypeConstrainedLanguage\s*)+$/, '');
179    if (!text.trim()) text = '(no output)';
180  }
181  // Starting a program or opening a folder prints nothing when it worked, and also when it did not (a browser given a file:// address, a
182  // program that closed at once). T9 / #3576: the card used to say "was opened", and the model repeated it ("I previewed it in a browser to
183  // confirm it renders"). It says what is known: the command returned without an error.
184  if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim()) && LAUNCH.test(String(args?.command ?? ''))) return LAUNCHED_TEXT;
185  if ((tool === 'pwsh' || tool === 'bash') && /^\(no output\)$/.test(text.trim())) return 'The command finished without any error. It printed nothing, so there is nothing more to show.';
186  return text;
187}
188
189/** Text of a tool-result message, bounded. */
190export function resultText(message) {
191  const parts = Array.isArray(message?.content) ? message.content : [];
192  const text = parts.map(p => (p?.type === 'text' ? p.text : p?.type ? `[${p.type}]` : '')).join('\n').trim();
193  return clip(text || '(no output)', 4000);
194}
195
196/**
197 * Accumulates one turn's frames. Feed it follow items; it returns the frames to send.
198 * It owns the per-turn state (tool cards, usage, text emitted) so the I/O layer stays thin.
199 */
200export class TurnProjector {
201  /**
202   * `policy` is the session's approval policy for this turn. Under `never` the Harness rejects an ask by itself, so
203   * no question ever reaches the person: the card goes straight from running to denied, without a moment where it
204   * offers Approve and Deny buttons that would do nothing.
205   */
206  constructor({ startedAt = Date.now(), policy = 'ask', window = 0 } = {}) {
207    this.startedAt = startedAt;
208    this.window = Number(window) || 0;   // the model's window, for the figures in the line that says the chat was summarised
209    this.summarizing = false;
210    this.policy = policy;
211    this.byPolicy = new Set();       // callIds the approval policy rejected without asking
212    this.tools = new Map();          // callId -> { card, calledAt }
213    this.tokensIn = 0;
214    this.tokensOut = 0;
215    this.contextTokens = null;       // the LAST model request's prompt + reply: what the context holds now (the sums above count every request again)
216    this.usageSeen = false;
217    this.firstTokenAt = null;
218    this.streams = new Map();        // attemptId -> { first, last, chunks, chars }: the time a model request actually spent producing
219    this.lastStats = 0;
220    this.emittedText = new Map();    // attemptId -> chars sent live
221    this.ended = null;               // the turn/end reason, once seen
222    this.denied = new Set();         // callIds a human or the policy rejected
223    this.asked = new Map();          // approval id -> callId
224    this.onStatus = null;            // (update) => void: what the assistant is doing now (status.mjs); set by the bridge
225    this.reasoning = new TokenCount();
226    this.composing = new Map();      // callId -> ToolDraft: a tool call the model is still writing (still here at a cut reply = it was lost)
227    this.lastOutput = 0;             // tokens the LAST model request produced
228    this.running = [];               // callIds of tools that are running, oldest first
229  }
230
231  #status(update) { if (this.onStatus) this.onStatus(update); }
232
233  /** After a tool ends: another tool still running is what is happening, otherwise the model is working out what to do next. */
234  #afterTool() {
235    const id = this.running.at(-1);
236    const card = id ? this.tools.get(id)?.card : null;
237    if (card) this.#status(toolUpdate('tool', 'tool', card.name, card.args, {}, { args: { tool: card.name, verb: card.verb, target: card.target } }));
238    else this.#status({ phase: 'waiting', code: 'model-working', text: 'Working out the next step…' });
239  }
240
241  #card(callId, patch) {
242    const entry = this.tools.get(callId);
243    if (!entry) return null;
244    entry.card = { ...entry.card, ...patch };
245    entry.card.verb = toolVerb(entry.card.name, entry.card.state);
246    return { type: 'agent-tool', tool: entry.card };
247  }
248
249  /* The speed shown while a reply streams, and after it: everything the model generated (reasoning and tool calls included) over the time its
250     requests spent producing it, not over the whole turn (tool runs and the wait for the prompt are not decoding). One stream per model
251     request; tokens are one per streamed chunk, or characters / 4 when a server batches. */
252  #produced(attemptId, text, out) {
253    const now = Date.now();
254    const s = this.streams.get(attemptId) ?? { first: now, last: now, chunks: 0, chars: 0 };
255    s.last = now; s.chunks += 1; s.chars += text.length;
256    this.streams.set(attemptId, s);
257    if (now - this.lastStats < 400) return;
258    const { tokens, seconds } = this.decode();
259    if (seconds < 0.5) return;
260    this.lastStats = now;
261    out.push({ type: 'stats', tokensOut: tokens, tps: Number((tokens / seconds).toFixed(1)), source: 'stream' });
262  }
263
264  decode() {
265    let tokens = 0, ms = 0;
266    for (const s of this.streams.values()) { tokens += s.chars / Math.max(1, s.chunks) < 8 ? s.chunks : Math.ceil(s.chars / 4); ms += s.last - s.first; }
267    return { tokens, seconds: ms / 1000 };
268  }
269
270  /** Process one `session/follow` item (event or assistant-stream). Returns frames. */
271  consume(item) {
272    const out = [];
273    if (item.type === 'assistant-stream') {
274      const f = item.frame;
275      if (f.type === 'chunk') {
276        const c = f.chunk;
277        if (c.type === 'text-delta' && c.text) {
278          this.firstTokenAt ??= Date.now();
279          this.#produced(f.attemptId, c.text, out);
280          this.emittedAny = true;
281          this.#status({ phase: 'answering', code: 'answering', text: 'Writing the answer…' });
282          this.emittedText.set(f.attemptId, (this.emittedText.get(f.attemptId) ?? 0) + c.text.length);
283          out.push({ type: 'delta', text: c.text });
284        } else if (c.type === 'reasoning-delta' && c.text) {
285          this.firstTokenAt ??= Date.now();
286          this.#produced(f.attemptId, c.text, out);
287          // The count is for the model's current thinking (each model request starts again from zero), not the whole turn.
288          if (this.reasoningAttempt !== f.attemptId) { this.reasoning = new TokenCount(); this.reasoningAttempt = f.attemptId; }
289          this.reasoning.add(c.text);
290          this.#status({ phase: 'thinking', code: 'thinking', text: `Thinking… ${fmtTokens(this.reasoning.tokens)} tokens`, key: 'Thinking… {0} tokens', values: [fmtTokens(this.reasoning.tokens)], tokens: this.reasoning.tokens, args: { tokens: this.reasoning.tokens } });
291          out.push({ type: 'reasoning', text: c.text });
292        } else if (c.type === 'tool-call-delta' && c.id) {
293          // The model is writing a tool call. For a big file this is the long silent part: nothing else arrives until it is finished.
294          const call = this.composing.get(c.id) ?? new ToolDraft(c.id, c.name ?? '');
295          if (c.name) call.name = c.name;
296          const piece = String(c.argumentsDelta ?? '');
297          // Writing a tool call (a whole file, say) is decoding too: its tokens are in the engine's output count, so its time belongs in the speed.
298          this.#produced(f.attemptId, piece, out);
299          call.add(piece);
300          this.composing.set(c.id, call);
301          if (call.name && !NO_CARD.has(call.name)) {
302            const target = call.target;
303            const args = target ? { file_path: target, url: target } : {};
304            this.#status(toolUpdate('preparing', 'preparing-tool', call.name, args, { bytes: call.bytes }, { args: { tool: call.name, verb: toolVerb(call.name, 'running'), target: target ?? '', bytes: call.bytes } }));
305            // The live data path of a file being written (AGENT-LOST): the name, a growing size and the tail of the text, at most five times a second.
306            const now = Date.now();
307            if (now - call.at >= 200) { call.at = now; out.push(call.frame({ scope: toolScope(call.name), verb: toolVerb(call.name, 'running') })); }
308          }
309        } else if (c.type === 'usage' && c.usage) {
310          this.usageSeen = true;
311          // The Harness counts input, cache reads and cache writes apart (a prompt the server's conversation cache already held is `cacheReadTokens`,
312          // not `inputTokens`): the prompt of a request is all three. Counting only `inputTokens` made a long agent chat look nearly empty (0%).
313          const prompt = (Number(c.usage.inputTokens) || 0) + (Number(c.usage.cacheReadTokens) || 0) + (Number(c.usage.cacheWriteTokens) || 0);
314          this.tokensIn += prompt;
315          this.tokensOut += Number(c.usage.outputTokens) || 0;
316          this.lastOutput = Number(c.usage.outputTokens) || 0;
317          this.contextTokens = prompt + (Number(c.usage.outputTokens) || 0);
318          out.push({ type: 'context', contextTokens: this.contextTokens, contextMax: this.window || undefined });
319        }
320      }
321      return out;
322    }
323    if (item.type !== 'event') return out;
324    const e = item.event;
325    const d = e.data ?? {};
326    switch (e.type) {
327      case 'assistant/message': {
328        // Reconcile a text the live frames did not fully carry (a socket gap), never duplicating it.
329        const live = [...this.emittedText.values()].pop() ?? 0;
330        const text = (d.message?.content ?? []).filter(p => p.type === 'text').map(p => p.text).join('');
331        if (text.length > live && live > 0) out.push({ type: 'delta', text: text.slice(live) });
332        this.emittedText.clear();
333        break;
334      }
335      case 'tool/call': {
336        if (NO_CARD.has(d.name)) break;
337        const args = parseArguments(d.arguments);
338        const card = { ...presentTool({ callId: d.callId, name: d.name, args }), state: 'running' };
339        this.tools.set(d.callId, { card, calledAt: e.time });
340        const draft = this.composing.get(d.callId);
341        this.composing.delete(d.callId);
342        if (draft && draft.bytes > 0 && !NO_CARD.has(d.name)) out.push(draft.frame({ done: true }));
343        this.running.push(d.callId);
344        this.#status(toolUpdate('tool', 'tool', d.name, args, {}, { args: { tool: d.name, verb: card.verb, target: card.target } }));
345        out.push({ type: 'agent-tool', tool: card });
346        break;
347      }
348      case 'approval/asked': {
349        if (!d.callId) break;
350        this.asked.set(d.id, d.callId);
351        if (this.policy === 'never') break;
352        const entry = this.tools.get(d.callId);
353        this.#status({ phase: 'approval', code: 'waiting-approval', text: 'Waiting for your answer…', args: { tool: entry?.card.name ?? '' } });
354        const patch = { state: 'proposed', effect: clip(d.reason ?? entry?.card.effect ?? 'Needs your approval.', 400) };
355        const frame = this.#card(d.callId, patch);
356        if (frame) out.push(frame);
357        break;
358      }
359      case 'approval/decided': {
360        const callId = this.asked.get(d.id);
361        if (callId && this.policy === 'never' && d.outcome !== 'allowed-once') {
362          this.byPolicy.add(callId); this.denied.add(callId);
363          const frame = this.#card(callId, { state: 'denied', result: NOT_IN_MODE });
364          if (frame) out.push(frame);
365          break;
366        }
367        this.#afterTool();
368        const frame = callId ? this.decide(callId, d.outcome) : null;
369        if (frame) out.push(frame);
370        break;
371      }
372      case 'tool/result': {
373        const callId = d.message?.toolCallId;
374        const entry = this.tools.get(callId);
375        if (!entry) break;
376        this.running = this.running.filter(id => id !== callId);
377        this.#afterTool();
378        const isError = d.message?.isError === true;
379        const denied = this.denied.has(callId);
380        const frame = this.#card(callId, {
381          state: denied ? 'denied' : isError ? 'error' : 'done',
382          // A card the person (or the mode) refused keeps its plain sentence; the model's own error text ("the user rejected ...") is not for them.
383          result: this.byPolicy.has(callId) ? NOT_IN_MODE : denied ? (entry.card.result ?? 'Denied. Nothing ran.') : isError ? withPlain(resultText(d.message)) : outcomeText(entry.card.name, resultText(d.message), entry.card.args),
384          durationMs: Math.max(0, (e.time ?? 0) - entry.calledAt),
385        });
386        if (frame) out.push(frame);
387        break;
388      }
389      case 'compaction/start':
390        // The Harness is summarising the older messages to make room: say so while it does, and again (once) when it is done.
391        this.summarizing = true;
392        this.#status({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] });
393        break;
394      case 'compaction/end':
395        if (!this.summarizing) break;
396        this.summarizing = false;
397        this.#afterTool();
398        if (!d.error) {
399          const before = this.window > 0 && this.contextTokens ? Math.min(100, Math.round(100 * this.contextTokens / this.window)) : null;
400          const text = before === null ? FIT_TEXT.summarizedShort : FIT_TEXT.summarizedWas;
401          const values = before === null ? [] : [before];
402          out.push({ type: 'delta', own: true, text: '\n\n' + fill(text, values), key: text, values, noteReason: 'compacted' });
403        }
404        break;
405      case 'turn/start':
406        // The parent woke up again (a helper finished and reported back): the message goes on, as a new paragraph.
407        this.ended = null;
408        if (this.emittedAny) out.push({ type: 'delta', text: '\n\n' });
409        break;
410      case 'turn/end':
411        this.ended = d.reason ?? { kind: 'completed' };
412        break;
413      default:
414        break;
415    }
416    return out;
417  }
418
419  /** An approval was decided. `outcome` is the Harness vocabulary. */
420  decide(callId, outcome) {
421    if (!this.tools.has(callId)) return null;
422    // `approved` is what lets the card say "Approved" (the user answered) rather than "Ran" (it never asked).
423    if (outcome === 'allowed-once') return this.#card(callId, { state: 'running', approved: true });
424    this.denied.add(callId);
425    return this.#card(callId, { state: 'denied', result: outcome === 'rejected' ? 'Denied. Nothing ran.' : outcome === 'cancelled' ? 'Cancelled. Nothing ran.' : 'No one could answer this request, so nothing ran.' });
426  }
427
428  /** A reply the model could not finish (the turn ended on the length limit): what it was writing, so nothing is lost without a word. */
429  cut() {
430    return { tokens: this.lastOutput, calls: cutCalls(this.composing.values()) };
431  }
432
433  /** The agent was asked to carry on: the calls it lost are not pending any more. */
434  clearCut() { const frames = this.#dropDrafts(); this.ended = null; return frames; }
435
436  /** Frames that take the writing cards of calls that will never be whole off the page (the reply was cut, or the turn ended). */
437  #dropDrafts() {
438    const frames = [...this.composing.values()].filter(d => d.bytes > 0 && !NO_CARD.has(d.name)).map(d => d.frame({ done: true, lost: true }));
439    this.composing.clear();
440    return frames;
441  }
442
443  /** The terminal frames for a finished turn. */
444  finish(options = {}) {
445    const cutInfo = this.ended?.kind === 'max-tokens' ? this.cut() : null;
446    const dropped = this.#dropDrafts();
447    return [...dropped, ...this.#finished(options, cutInfo)];
448  }
449
450  #finished({ model, contextMax, engine = null } = {}, cutInfo = null) {
451    const reason = this.ended ?? { kind: 'interrupted' };
452    const durationMs = Date.now() - this.startedAt;
453    const usage = this.usageSeen
454      ? { tokensIn: this.tokensIn, tokensOut: this.tokensOut, usageSource: 'reported' }
455      : { tokensIn: null, tokensOut: null, usageSource: 'unavailable' };
456    const decoded = this.decode();
457    const generated = this.usageSeen && this.tokensOut > 0 ? this.tokensOut : decoded.tokens;
458    // Answer speed, one definition everywhere: all the tokens the model produced over its decode time. The engine's own figures (the ones the
459    // Monitor shows) when the bridge could read them; otherwise the stream's own span. A very short reply has almost no span, so its decode time
460    // is then the time from its first chunk to the end of the turn (only when no tool ran, so no tool time is in it): the number is still shown.
461    let tps = null;
462    if (engine?.tps > 0) tps = engine.tps;
463    else if (generated > 0 && decoded.seconds >= 0.3) tps = Number((generated / decoded.seconds).toFixed(1));
464    else if (generated > 0 && this.tools.size === 0 && this.firstTokenAt && Date.now() - this.firstTokenAt >= 50) tps = Number((generated / ((Date.now() - this.firstTokenAt) / 1000)).toFixed(1));
465    const promptTps = engine?.promptTps > 0 ? engine.promptTps : null;
466    const base = { durationMs, ttftMs: this.firstTokenAt ? this.firstTokenAt - this.startedAt : null, model, contextMax, tps, ...(promptTps ? { promptTps } : {}), contextTokens: this.contextTokens };
467    switch (reason.kind) {
468      case 'completed':
469        return [{ type: 'done', ...base, ...usage, finishReason: 'stop' }];
470      case 'max-tokens':
471        return [{ type: 'done', ...base, ...usage, finishReason: 'length', cut: cutInfo }];
472      case 'aborted':
473        return [{ type: 'done', ...base, ...usage, finishReason: 'aborted', cancelled: true }];
474      case 'error':
475        return [{ type: 'error', message: friendlyFailure(reason.error), code: isContextFailure(reason.error) ? 'CONTEXT_WINDOW_EXCEEDED' : reason.error?.code ?? 'UNKNOWN', ...(isContextFailure(reason.error) ? { key: FIT_TEXT.full, details: String(reason.error?.message ?? '') } : {}) }];
476      case 'blocked':
477        return [{ type: 'error', message: 'The agent stopped because this turn was blocked by policy.', code: 'BLOCKED' }];
478      default:
479        return [{ type: 'error', message: 'The agent turn was interrupted before it finished.', code: 'INTERRUPTED' }];
480    }
481  }
482}
483
484/** Whether a failure is the model server saying the conversation does not fit its window (its code, or the engine's own words). */
485export function isContextFailure(failure) {
486  return isContextOverflow(failure) || /context window|too long for|exceeds the context/i.test(String(failure?.message ?? ''));
487}
488
489/** A model-route failure in words a user can act on. */
490export function friendlyFailure(failure) {
491  const message = String(failure?.message ?? 'The model request failed.');
492  if (isContextFailure(failure)) return FIT_TEXT.full;
493  if (/ECONNREFUSED|fetch failed|connect/i.test(message)) return `The model is not reachable. ${clip(message, 200)}`;
494  if (/401|403|credential|api key/i.test(message)) return 'The model rejected the credentials. Check the connection in Settings.';
495  return clip(message, 400);
496}