okami.mom/strata

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

Niko1221Merge f-0213-guidata (final 1d5096beb) into f-0213-int85269ca15

main
97.6 KiB1509 linesraw
1/**
2 * The agent bridge: Strata chats as Harness sessions.
3 *
4 * What it owns
5 *   - the pinned Harness process (one, lazily started, restarted only when a route it needs changed);
6 *   - the stable Strata-chat -> Harness-session map, persisted next to the host's other state;
7 *   - one `session/follow` stream per live turn, projected into the NDJSON frames the chat UI renders;
8 *   - approvals: the Harness `approval/request` waterfall in, the user's Approve/Deny back out;
9 *   - Stop: `session/cancel` for exactly one session, resolved only once the turn has really ended.
10 *
11 * What it deliberately does not do
12 *   - it never falls back to another model: a chat picks a route (local instance or saved API
13 *     connection) and a missing route is a typed error;
14 *   - it never implements Stop by killing the Harness (that would cancel every other chat);
15 *   - it never holds a secret outside the environment of the agent process it starts.
16 */
17import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
18import { join, resolve } from 'node:path';
19import { homedir, tmpdir } from 'node:os';
20import { fileURLToPath } from 'node:url';
21import { randomUUID } from 'node:crypto';
22import { GatewayClient } from './gateway-client.mjs';
23import { HarnessProcess, resolveHarness, redact, stopStaleAgent } from './harness-runtime.mjs';
24import { StatusReporter } from './status.mjs';
25import { buildProfile, routeFor, MODE_PRESETS, modeOf, effortOf, localOutputBudget, compactionHeadroom } from './profile.mjs';
26import { TurnProjector, parseArguments as parseArgs } from './events.mjs';
27import { ChildProjector } from './children.mjs';
28import { nearestBudget } from './llm-shape.mjs';
29import { DeliverableTracker, ActivityGroups, FolderClaims } from './deliverables.mjs';
30import { SkillsUsed, skillInfoFrom } from './skills-used.mjs';
31import { turnEngineSpeed } from './engine-speed.mjs';
32import { TurnGuard, guardNote, GUARD_NOTES } from './turn-guard.mjs';
33import { cutNotice, cutNudge } from './reply-cut.mjs';
34
35/** How often one turn asks the agent to carry on after a reply the length limit cut (each time in smaller pieces). */
36export const MAX_CUT_RETRIES = 2;
37import { buildAnswer, parseQuestions } from './user-questions.mjs';
38import { BASE_TOKENS, COUNT_ABOVE_CHARS, FIT_TEXT, countTokens, decideFit, fill, grouped } from './context-fit.mjs';
39import { PlanStore, planPrompt, parsePlan, parsePoints, stepObjective, stepLine, firstSentence, stepSummary, planAsPrompt, editedSteps, planView, researchPrompt, researchWritePrompt, RESEARCH_NUDGE, parseSources } from './plan.mjs';
40
41/**
42 * A failure the person can read. `message` is a plain sentence with the next step; `details` keeps the technical
43 * text for the Details disclosure (experts), already free of secrets.
44 */
45export class AgentUnavailable extends Error {
46  constructor(message, code = 'agent-unavailable', details = null) { super(message); this.name = 'AgentUnavailable'; this.code = code; this.details = details; }
47}
48
49/** The plain sentence for a raw agent failure text, whatever produced it. */
50export function plainAgentFailure(raw) {
51  const text = String(raw ?? '');
52  if (/did not print its address|exited during start|could not start|ECONNREFUSED.*127\.0\.0\.1|refused the launch token|socket/i.test(text)) return 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.';
53  if (/process stopped|lost the session stream|stream did not open|session stream/i.test(text)) return 'The coding assistant stopped unexpectedly, so this answer is incomplete. Send your message again.';
54  if (/did not accept the message/i.test(text)) return 'The coding assistant did not take this message. Send it again in a moment.';
55  return text;
56}
57
58/**
59 * A failure thrown while a turn starts, as `{ message, details, code }` for the chat's error card. The agent's own errors read like
60 * `session/create: tool-bash (...): waiting for shell ...` (a plugin chain that never started): never shown raw. The plain sentence
61 * goes in `message`; the technical text goes in `details`, which the app shows only behind Details.
62 */
63export function plainTurnFailure(err) {
64  const raw = String(err?.message ?? err ?? '');
65  const details = typeof err?.details === 'string' && err.details ? err.details : raw;
66  if (err instanceof AgentUnavailable) return { message: err.message, details, code: err.code ?? 'AGENT_ERROR' };
67  if (err?.code === 'agent-preset/invalid' || /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)|failed to import|did not activate/i.test(raw)) {
68    return { message: 'The coding assistant is missing a part it needs, so it cannot work on files yet. Close and reopen Strata. If it keeps happening, reinstall Strata. Chatting without tools still works.', details, code: 'AGENT_INCOMPLETE' };
69  }
70  if (/^[a-z][a-z-]*\/[a-z][a-z-]*: /i.test(raw) || /^(gateway|rpc)/i.test(raw)) {
71    return { message: 'The coding assistant could not start this message. Try again. If it keeps happening, close and reopen Strata.', details, code: err?.code ?? 'AGENT_ERROR' };
72  }
73  return { message: plainAgentFailure(raw), details, code: err?.code ?? 'AGENT_ERROR' };
74}
75
76/** The Harness's plugins start one after another: until they are all up, session/create answers "<plugin>: waiting for <service>". */
77const STARTING_UP = /waiting for (shell|subprocess|ptcRuntime|workflowEngine|sandbox)/i;
78
79/**
80 * Create a Harness session, waiting for its plugins to finish starting. Right after the app opens (or the Harness restarts) the first
81 * message can arrive before they are up: that is retried every `retryMs` for up to `readyMs` (`onWait` tells the page "Starting the assistant…")
82 * instead of failing the first chat. Any other error is thrown at once; a start that never finishes is a plain AGENT_NOT_READY error
83 * with the Harness's text kept for Details. Returns null when `cancelled()` turns true while waiting.
84 */
85export async function createSessionWhenReady(create, { readyMs = 60_000, retryMs = 1_500, onWait = () => {}, cancelled = () => false, now = Date.now } = {}) {
86  const until = now() + readyMs;
87  for (;;) {
88    try { return await create(); } catch (e) {
89      const text = String(e?.message ?? e ?? '');
90      if (!STARTING_UP.test(text)) throw e;
91      if (now() >= until) throw new AgentUnavailable('The assistant could not start. Try again in a moment.', 'AGENT_NOT_READY', text);
92      onWait();
93      await new Promise(r => setTimeout(r, retryMs));
94      if (cancelled()) return null;
95    }
96  }
97}
98
99/** Attached pictures (data addresses) as the Harness's image prompt parts. */
100export function imageParts(images) {
101  return (Array.isArray(images) ? images : []).map(i => {
102    const m = /^data:(image\/(?:png|jpeg|webp));base64,(.+)$/.exec(String(i?.url ?? ''));
103    return m ? { type: 'image', mediaType: m[1], data: m[2], name: String(i.name ?? 'Picture').slice(0, 120) } : null;
104  }).filter(Boolean);
105}
106
107/** A timer that never keeps the process alive by itself. */
108const after = (ms, fn) => { const t = setTimeout(fn, ms); t.unref?.(); return t; };
109/** The app's own host folder: never a place an answer's files can be (this file lives in <host>/server/agent). */
110const HOST_DIR = fileURLToPath(new URL('../..', import.meta.url));
111
112const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; };
113
114/**
115 * @param {object} options
116 * @param {string} options.dataDir                      the host's data directory (agent state lives in `<dataDir>/agent`)
117 * @param {string|null} [options.componentsDir]         where installed components live
118 * @param {() => Array} options.localInstances          ready local instances (see profile.mjs)
119 * @param {() => Array} options.connections             saved API connections WITH their keys (host-internal)
120 * @param {() => (string|null)} [options.defaultLocalId]  the local instance the chat runs on: its tool servers are the agent's (T5)
121 * @param {NodeJS.ProcessEnv} [options.env]
122 * @param {string} [options.nodePath]                   the Node runtime that runs the Harness
123 * @param {(line:string)=>void} [options.log]
124 */
125export function createAgentBridge({ dataDir, componentsDir = null, bundledDir = null, gate = true, localInstances, connections, tools = () => undefined, defaultLocalId = () => null, skillsDir = () => null, onGoal = () => {}, onPlan = () => {}, onQueue = () => {}, proxyBase = null, searchMock = null, expertSampling = () => null, engineProgress = () => null, engineGraceMs = 30 * 60_000, stallMs = 4 * 60_000, stallToolMs = 20 * 60_000, env = process.env, nodePath = process.execPath, log = () => {}, startTimeoutMs = 120_000, sessionReadyMs = 60_000, sessionRetryMs = 1_500 }) {
126  const root = join(dataDir, 'agent');
127  const home = join(root, 'home');
128  const sessionsFile = join(root, 'sessions.json');
129  mkdirSync(root, { recursive: true });
130  /** Which chat's file tools wrote which file, for chats that share a folder (#5008). */
131  const folderClaims = new FolderClaims();
132
133  /**
134   * Where the turn's file tracker must never look (deliverables.mjs): the app, the engine and its components, Strata's own data, AppData
135   * and temp. `forbid` ones also switch tracking off when the chat's folder is one of them or inside one.
136   */
137  function trackerFolders() {
138    const user = env.USERPROFILE ?? env.HOME ?? homedir();
139    const forbid = [HOST_DIR, componentsDir, bundledDir].filter(Boolean);
140    const exclude = [dataDir, tmpdir(), env.LOCALAPPDATA, env.APPDATA, env.ProgramData, env.ProgramFiles, env['ProgramFiles(x86)'], env.TEMP, env.TMP,
141      join(user, 'AppData'), join(user, '.cache'), join(user, '.config'), join(user, '.local'), join(user, 'Library')].filter(Boolean);
142    return { forbid, exclude };
143  }
144
145  /** chatId -> { sessionId, cwd, createdAt } */
146  let sessionMap = {};
147  if (existsSync(sessionsFile)) {
148    try { sessionMap = JSON.parse(readFileSync(sessionsFile, 'utf8')) ?? {}; } catch { sessionMap = {}; }
149  }
150  const persist = () => {
151    const temp = `${sessionsFile}.${randomUUID()}.tmp`;
152    writeFileSync(temp, JSON.stringify(sessionMap, null, 2));
153    renameSync(temp, sessionsFile);
154  };
155
156  /** @type {{hp:HarnessProcess, gw:GatewayClient, profile:object, clientId:string|null, generation:number, events:object}|null} */
157  let rt = null;
158  let generation = 0;
159  let lastError = null;
160  let starting = null;
161  const chats = new Map();         // chatId -> { turn, route, routeGeneration }
162  const plans = new PlanStore(join(root, 'plans.json'));
163  /** chatId -> messages the person typed while a goal ran: [{ id, text, at, deliverAt }]; delivered between steps or when the goal ends */
164  const queues = new Map();
165  const queueView = chatId => (queues.get(chatId) ?? []).map(({ id, text, at, deliverAt }) => ({ id, text, at, deliverAt }));
166  const pending = new Map();       // `${sessionId}:${callId}` -> { eventId, sessionId, callId, at }
167  const questions = new Map();     // `${sessionId}:${callId}` -> the agent's own question waiting for the person: { eventId, sessionId, callId, items, at, clientId } (#4244)
168  const chatOfSession = sessionId => Object.keys(sessionMap).find(id => sessionMap[id]?.sessionId === sessionId) ?? null;
169  const idleWaiters = new Set();
170
171  const chat = id => { let c = chats.get(id); if (!c) { c = { id, turn: null, route: null, routeGeneration: -1 }; chats.set(id, c); } return c; };
172  const activeTurns = () => [...chats.values()].filter(c => c.turn).length;
173  const notifyIdle = () => { if (activeTurns() === 0) { for (const w of idleWaiters) w(); idleWaiters.clear(); } };
174  const waitIdle = (signal, ms) => new Promise((resolve, reject) => {
175    if (activeTurns() === 0) return resolve();
176    const timer = setTimeout(() => { idleWaiters.delete(done); reject(new AgentUnavailable('Another chat is still working and the list of models changed. Try again when it finishes.', 'agent-busy')); }, ms);
177    const done = () => { clearTimeout(timer); resolve(); };
178    idleWaiters.add(done);
179    signal?.addEventListener('abort', () => { clearTimeout(timer); idleWaiters.delete(done); reject(signal.reason ?? new Error('aborted')); }, { once: true });
180  });
181
182  /** The agent's profile now, plus where its shaped routes really lead (read by the forwarding endpoint). */
183  let shapeTargets = {};
184  function buildProfileNow() {
185    const profile = buildProfile({ local: localInstances(), connections: connections(), gate, tools: tools(), skillsDir: skillsDir(), proxyBase, searchMock, defaultLocalId: defaultLocalId() });
186    shapeTargets = profile.shapeTargets ?? {};
187    return profile;
188  }
189  const llmTarget = key => shapeTargets[key] ?? null;
190
191  function harnessInfo() { return resolveHarness({ env, componentsDir, bundledDir }); }
192  /** Where the agent component is (the browser tool server lives inside it), or null. */
193  const harnessDir = () => { const h = harnessInfo(); return h.ok ? h.dir : null; };
194
195  /** The capability state the app shows. Never carries a token or a key. */
196  function status() {
197    const h = harnessInfo();
198    if (!h.ok) return { state: 'unavailable', reason: 'The coding assistant isn’t installed on this computer yet. Chat works without it.', detail: h.reason, code: 'component-missing' };
199    const profile = buildProfileNow();
200    return {
201      state: rt?.hp.running ? 'ready' : starting ? 'starting' : lastError ? 'error' : 'idle',
202      reason: lastError ? plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again.' : plainAgentFailure(lastError) : null,
203      detail: lastError ?? null,
204      harness: { version: h.version },
205      runtime: rt?.hp.running ? { pid: rt.hp.pid, generation: rt.generation } : null,
206      routes: profile.routes.map(({ route, kind, modelId, name, contextWindow }) => ({ route, kind, modelId, name, contextWindow })),
207      // tool servers that could not be wired (a name the rule does not allow, no program or address): the chat says so
208      skippedServers: profile.mcpSkipped ?? [],
209      activeTurns: activeTurns(),
210      pendingApprovals: pending.size,
211    };
212  }
213
214  async function startRuntime(profile) {
215    const h = harnessInfo();
216    if (!h.ok) throw new AgentUnavailable('The coding assistant isn’t installed on this computer yet. Chat works without it.', 'component-missing', h.reason);
217    mkdirSync(home, { recursive: true });
218    const stale = stopStaleAgent(join(root, 'harness.pid'));
219    if (stale) log(`agent · stopped a leftover Harness process (pid ${stale}) from an earlier run`);
220    const patchFile = join(root, `profile-${profile.signature}.patch.yml`);
221    writeFileSync(patchFile, profile.patch);
222    const workdir = join(root, 'run');
223    const hp = new HarnessProcess({
224      harness: h, home, patchFile, cwd: workdir, env: profile.env, nodePath, logFile: join(root, 'harness.log'), pidFile: join(root, 'harness.pid'),
225      onExit: exit => {
226        log(`agent · the Harness process exited (code ${exit.code})`);
227        if (rt?.hp === hp) { lastError = 'The agent process stopped.'; rt = null; }
228        for (const c of chats.values()) c.turn?.abortFromRuntime('The agent process stopped before this turn finished.');
229      },
230    });
231    const info = await hp.start({ timeoutMs: startTimeoutMs });
232    const gw = new GatewayClient({ baseUrl: info.baseUrl, token: info.token });
233    await gw.connect();
234    const next = { hp, gw, profile, clientId: null, generation: ++generation, events: null };
235    next.events = gw.openStream('$events', {}, {
236      onItem: value => onHostEvent(next, value),
237      onError: e => log(`agent · event stream: ${redact(e.message, Object.values(profile.env))}`),
238    });
239    rt = next;
240    lastError = null;
241    log(`agent · Harness ${h.version ?? ''} ready (pid ${hp.pid}, ${profile.routes.length} route(s))`);
242    return next;
243  }
244
245  /** The local engine's own speed for this turn's requests (null when it cannot be read: the stream's estimate stays). */
246  async function engineSpeedOf(route, projector) {
247    const inst = localInstances().find(i => i.id === route.instanceId);
248    if (!inst) return null;
249    return turnEngineSpeed({ baseUrl: inst.baseUrl, key: inst.key, since: projector.startedAt, attempts: projector.streams.size, timeoutMs: 800 });
250  }
251
252  /** Make sure a runtime exists that knows the route this turn needs. */
253  async function ensureRuntime(choice, signal) {
254    for (;;) {
255      if (starting) { await starting.catch(() => {}); continue; }
256      const profile = buildProfileNow();
257      const route = routeFor(profile, choice);
258      if (!route) {
259        throw new AgentUnavailable(choice?.connectionId
260          ? 'This API model is no longer available. Choose another model in the chat picker.'
261          : 'No local model is ready for the agent. Load a model in Models, or choose an API model.', 'model-unavailable');
262      }
263      const known = rt?.hp.running && rt.profile.toolsSignature === profile.toolsSignature && rt.profile.routes.some(r => r.route === route.route && r.modelId === route.modelId && r.fp === route.fp);
264      if (known) return { rt, route };
265      starting = (async () => {
266        if (rt?.hp.running) {
267          await waitIdle(signal, 120_000);
268          const old = rt; rt = null;
269          old.events?.close(); old.gw.close(); await old.hp.stop();
270        }
271        try { return await startRuntime(profile); } catch (e) {
272          lastError = redact(String(e.message ?? e), Object.values(profile.env));
273          throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainAgentFailure(lastError) === lastError ? 'The coding assistant could not start. Try again. If it keeps happening, close and reopen Strata.' : plainAgentFailure(lastError), 'agent-start-failed', lastError);
274        }
275      })();
276      try { await starting; } finally { starting = null; }
277    }
278  }
279
280  function onHostEvent(runtime, value) {
281    if (value.type === 'ready') { runtime.clientId = value.clientId; return; }
282    if (value.type === 'waterfall' && value.event === 'approval/request') {
283      const r = value.request ?? {};
284      if (!r.callId) return;
285      pending.set(`${value.agentId}:${r.callId}`, { eventId: value.eventId, sessionId: value.agentId, callId: r.callId, tool: r.toolName, reason: r.reason ?? null, at: Date.now(), clientId: runtime.clientId });
286    } else if (value.type === 'waterfall' && value.event === 'user-questions/request') {
287      // The agent of a chat that is running in front of the person asks the person: the question goes to the page (the question card above the message box) and the
288      // Harness waits for the answer. Anything else (a helper's question, a chat that is stopping, a request with nothing to show) is declared
289      // unanswerable, which makes the tool return an error the model reads and carries on from, instead of a turn that waits forever.
290      const r = value.request ?? {};
291      const chatId = chatOfSession(value.agentId);
292      const turn = chatId ? chats.get(chatId)?.turn : null;
293      const items = parseQuestions(r.questions);
294      // A goal or a plan step runs without anyone there: a question would stall it, so it is declined at once (the model reads "could not be answered" and goes on).
295      if (!turn || turn.finished || turn.stopping || turn.goalRun || turn.plan || !turn.announceQuestion || !items.length) {
296        void runtime.gw.answerEvent({ clientId: runtime.clientId, eventId: value.eventId, outcome: 'next' }).catch(() => {});
297      } else {
298        const callId = String(r.wait?.callId ?? value.eventId);
299        questions.set(`${value.agentId}:${callId}`, { eventId: value.eventId, sessionId: value.agentId, callId, items, at: Date.now(), clientId: runtime.clientId });
300        turn.announceQuestion({ type: 'agent-question', callId, questions: items });
301      }
302    } else if (value.type === 'cancel') {
303      for (const [k, v] of questions) if (v.eventId === value.eventId) { questions.delete(k); chats.get(chatOfSession(v.sessionId))?.turn?.announceQuestion?.({ type: 'agent-question-end', callId: v.callId }); }
304      for (const [k, v] of pending) if (v.eventId === value.eventId) pending.delete(k);
305    }
306  }
307
308  async function sessionFor(c, cwd, runtime, { onWait = () => {} } = {}) {
309    let known = sessionMap[c.id];
310    // The chat's folder changed: the agent's working folder and sandbox are fixed when its session starts, so the chat gets a new session
311    // in the new folder (the earlier conversation is carried into its first message, as for any fresh session).
312    if (known && cwd && known.cwd && resolve(known.cwd) !== resolve(cwd)) { delete sessionMap[c.id]; persist(); known = null; }
313    if (known) return { sessionId: known.sessionId, fresh: false };
314    const created = await createSessionWhenReady(() => runtime.gw.rpc('session/create', { request: { cwd } }), { readyMs: sessionReadyMs, retryMs: sessionRetryMs, onWait, cancelled: () => c.cancelStart });
315    if (!created) return null;
316    sessionMap[c.id] = { sessionId: created.sessionId, cwd, createdAt: new Date().toISOString() };
317    persist();
318    return { sessionId: created.sessionId, fresh: true };
319  }
320
321  /**
322   * Put the session into the preset of the chat's mode, through the Harness's own `/permission` command, and
323   * check that it took. A turn never starts in a mode other than the one asked for: if the switch cannot be
324   * confirmed the turn fails closed with a typed error instead of running with unknown permissions.
325   */
326  async function applyMode(runtime, sessionId, mode) {
327    const want = MODE_PRESETS[mode].key;
328    const read = async () => {
329      const r = await runtime.gw.rpc('session/projections', { request: { sessionId, keys: ['permissions'] } });
330      return r?.values?.permissions?.currentValue ?? null;
331    };
332    try {
333      if (await read() !== want) {
334        const done = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: `/permission ${want}`, submittedAttachments: [] });
335        if (done?.result?.kind !== 'success') throw new Error(done?.result?.text ?? 'the agent did not recognise the command');
336        const now = await read();
337        if (now !== want) throw new Error(`the session reports "${now}" instead of "${want}"`);
338      }
339    } catch (e) {
340      throw new AgentUnavailable(`Strata could not set this chat to ${MODE_PRESETS[mode].name} mode, so nothing ran. Try again.`, 'mode-unavailable', e.message);
341    }
342    // Manual leaves the sandbox open and relies on the Strata gate to ask first. Without the gate it must not start.
343    if (mode === 'manual' && !runtime.gateChecked) {
344      try {
345        const probe = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-gate', submittedAttachments: [] });
346        if (probe?.result?.kind !== 'success' || !String(probe.result.text ?? '').includes('strata-gate active')) throw new Error('the approval gate is not loaded');
347        runtime.gateChecked = true;
348      } catch (e) {
349        throw new AgentUnavailable('Strata could not make sure the coding assistant asks before changing anything, so nothing ran. Close and reopen Strata, then try again.', 'mode-unavailable', e.message);
350      }
351    }
352  }
353
354  /**
355   * Run one agent turn for a Strata chat and stream it as frames.
356   * `signal` means the client went away: the turn keeps running (that is not Stop).
357   */
358  async function runTurn(options) {
359    const c = chat(options.chatId);
360    if (c.turn || c.starting) throw new AgentUnavailable('This chat is still working. Stop it or wait for it to finish.', 'turn-active');
361    // From here until the Harness has the prompt, Stop has no session to cancel; it cancels the start.
362    c.starting = true; c.cancelStart = false;
363    try { return await runTurnInner(c, options); } finally { c.starting = false; }
364  }
365
366  async function runTurnInner(c, { chatId, message, workspacePath, choice = null, mode = null, history = [], onFrame, requestId = `req-${randomUUID()}`, signal, goal = null, thinking = null, thinkingBudget = 0, images = [], planTask = null, planRun = null, researchTopic = null }) {
367    let send = onFrame; let attached = true;
368    // A research run gathers first; what the assistant writes while gathering is notes, not the answer, so it is not shown.
369    let hideDeltas = !!researchTopic;
370    signal?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true });
371    // 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.
372    const written = { all: '', step: '', reasoning: '' };
373    // The frame that closed the turn, kept with the turn's text for a page that comes back after it ended (attach).
374    let terminal = null;
375    // The turn guard (turn-guard.mjs): counts failing searches, searches, plan rewrites and a nearly full context. Set up once the route is known.
376    let guard = null;
377    const raw = frame => { if (frame.type === 'done' || frame.type === 'error') terminal = frame; try { send(frame); } catch { send = () => {}; attached = false; } };
378    // What the turn made (files) and compact activity lines (notes-split-agent8.md): derived from the cards the turn already sends.
379    const tracker = new DeliverableTracker(workspacePath, { ...trackerFolders(), claims: folderClaims, owner: chatId });
380    let toolsRan = false;   // a turn that ran no tool wrote nothing, so there is nothing to look for at its end
381    try { tracker.snapshot(); } catch { /* a folder that cannot be read has no deliverables */ }
382    const groups = new ActivityGroups({ emit: raw });
383    const skills = new SkillsUsed({ emit: raw, info: skillInfoFrom(skillsDir()) });
384    const emit = frame => {
385      if (frame.type === 'reasoning' && frame.text && written.reasoning.length < 2_000_000) written.reasoning += frame.text;
386      if (frame.type === 'delta' && !frame.own) { written.all += frame.text; written.step += frame.text; if (guard) trip(guard.text(frame.text)); if (hideDeltas) return; }
387      if (frame.own) { const { own, ...rest } = frame; frame = rest; }
388      if (frame.type === 'delta' && frame.text) groups.text();
389      if (frame.type === 'agent-tool' && frame.tool) {
390        if (['done', 'error'].includes(frame.tool.state) && !['read', 'read_image', 'glob', 'grep', 'web_fetch', 'web_search'].includes(frame.tool.name)) toolsRan = true;
391        let made = null;
392        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, { explicit: true }); } catch { made = null; } }
393        raw(frame);
394        if (made) raw(made);
395        if (guard) trip(guard.card(frame.tool));
396        groups.card(frame.tool, made);
397        skills.card(frame.tool);
398        return;
399      }
400      raw(frame);
401    };
402    // What the assistant is doing right now, one small frame (status.mjs). Cleared before the final frame of the turn.
403    const reporter = new StatusReporter({ emit });
404
405    emit({ type: 'queued', requestId });
406    reporter.set({ phase: 'starting', code: 'starting', text: 'Starting…' });
407    const { rt: runtime, route } = await ensureRuntime(choice, signal);
408    const made = await sessionFor(c, workspacePath, runtime, { onWait: () => reporter.set({ phase: 'starting', code: 'assistant-starting', text: 'Starting the assistant…' }) });
409    const { sessionId, fresh } = made ?? {};
410    const cancelled = () => { reporter.clear(); emit({ type: 'done', finishReason: 'aborted', cancelled: true, tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0, model: route.name, contextMax: route.contextWindow }); return { cancelled: true }; };
411    if (c.cancelStart || !made) return cancelled();
412
413    // The model and the chat's thinking level (the Reasoning menu) are sent to the Harness when either changed. A level the route does
414    // not have (an API model with its own vocabulary) is dropped and the model's own default stands: never an error for the person.
415    const level = effortOf(thinking ?? 'Medium');   // the menu's default is Medium
416    // Response settings the Harness cannot send itself (the thinking budget, the Expert sampling) go through this host's forwarding
417    // endpoint, on a copy of the route; with every setting at its default the route is used directly, as before.
418    const budget = level === 'off' ? 0 : nearestBudget(thinkingBudget);
419    const sampling = proxyBase && route.shaped ? expertSampling() : null;
420    const provider = route.shaped && (budget || sampling) ? route.shaped[budget] : route.route;
421    const wanted = `${provider}/${route.modelId}/${level ?? ''}`;
422    if (c.route !== wanted || c.routeGeneration !== runtime.generation) {
423      const select = effort => runtime.gw.rpc('session/selectModel', { request: { sessionId, provider, model: route.modelId, ...(effort ? { reasoningEffort: effort } : {}) } });
424      try {
425        try { await select(level); } catch (e) { if (!level || e.code === 'session/not-found') throw e; await select(null); }
426      } catch (e) {
427        if (e.code === 'session/not-found') { delete sessionMap[c.id]; persist(); }
428        throw new AgentUnavailable(`The coding assistant could not use ${route.name}. Pick the model again and retry.`, 'model-unavailable', e.message);
429      }
430      c.route = wanted; c.routeGeneration = runtime.generation;
431    }
432
433    // The chat's permission mode is read once, here, for this whole turn. A change the user makes while the
434    // turn runs applies to the next one, so a running turn never sees its permissions move under it.
435    const appliedMode = planTask ? 'plan' : modeOf(mode);
436    await applyMode(runtime, sessionId, appliedMode);
437
438    // Does the message fit the model's window? Asked before anything is sent, with the model server's own count (context-fit.mjs). A message
439    // that fits once the older messages are a summary is sent after a summary; one that can never fit is not sent, and the person is told
440    // plainly and offered the two ways out. Whatever cannot be counted goes through: the Harness recovers from a refusal by itself.
441    if (!goal && route.kind === 'local') {
442      const fit = await fitCheck({ runtime, route, sessionId, fresh, history, message }).catch(() => null);
443      if (fit?.action === 'too-large') {
444        reporter.clear();
445        const values = [grouped(fit.tokens), grouped(fit.window)];
446        const text = fill(FIT_TEXT.tooLarge, values);
447        emit({ type: 'error', message: text, key: FIT_TEXT.tooLarge, values, code: 'CONTEXT_MESSAGE_TOO_LARGE', tokens: fit.tokens, window: fit.window });
448        return { error: text };
449      }
450      if (fit?.action === 'summarize') {
451        reporter.set({ phase: 'compacting', code: 'compacting', text: FIT_TEXT.summarizing, key: FIT_TEXT.summarizing, values: [] });
452        const done = await compactChat(runtime, sessionId);
453        reporter.clear();
454        if (done.ok) emit(summarizedNote(done.before, done.after, fit.window));
455      }
456    }
457
458    const projector = new TurnProjector({ policy: MODE_PRESETS[appliedMode].approval, window: route.contextWindow });
459    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
460    projector.onStatus = update => { if (!turn?.parentOpen && turn?.children.size && [...turn.children.values()].some(h => !h.done) && update.phase === 'waiting') return; reporter.set(update); };
461    const turn = {
462      sessionId, projector, route, requestId, live: false, lastSeq: -1,
463      ended: deferred(), follow: null, snapshot: deferred(), finished: false, prompted: false, stopBeforePrompt: false,
464      abortFromRuntime: reason => finishTurn(reason), finish: failure => finishTurn(failure),
465      // Helper agents (subagents) the Harness started for this chat, and the state of the run around them.
466      children: new Map(), subagentCalls: new Map(), parentOpen: false, stopping: false, settleTimer: null, mode: appliedMode,
467      plan: null, advancing: false, goalRun: false, lastActivity: Date.now(), heard: Date.now(), engineMark: null, watchdog: null,
468      research: researchTopic ? { phase: 'gather', nudged: false, waitingStart: false } : null,
469    };
470    c.turn = turn;
471    if (workspacePath) folderClaims.begin(workspacePath, chatId);
472    /**
473     * A page that comes back (a reload, a new window) takes the running turn over again. Everything that was said while no page was there is
474     * sent as one catch-up: the start, the text and thinking so far (a `resync`), every tool card as it is now (the ones waiting for a yes
475     * included) and the questions waiting for an answer. After that the turn's frames flow to the new page as they did to the old one.
476     */
477    turn.reattach = ({ onFrame, signal: again }) => {
478      send = onFrame; attached = true;
479      again?.addEventListener('abort', () => { send = () => {}; attached = false; }, { once: true });
480      raw({ type: 'start', model: route.name, contextMax: route.contextWindow, demo: false, remoteModel: route.kind === 'api', agent: true, mode: appliedMode, sessionId, requestId, skills: [], resumed: true, ...(planTask ? { planning: true } : {}) });
481      raw({ type: 'resync', content: hideDeltas ? '' : written.all, reasoning: written.reasoning });
482      for (const t of projector.tools.values()) if (t.card) raw({ type: 'agent-tool', tool: t.card });
483      for (const q of questions.values()) if (q.sessionId === sessionId) raw({ type: 'agent-question', callId: q.callId, questions: q.items });
484    };
485    /**
486     * A turn must always end. If the Harness sends nothing at all for a while (a tool that never returns, a model server that went
487     * quiet, a lost event) the turn is stopped and ended with a plain message instead of showing "thinking" forever. A running tool gets
488     * a longer allowance than a quiet model (a build can be silent for minutes). Whatever the assistant finished is kept.
489     */
490    turn.watchdog = setInterval(() => {
491      if (turn.finished || turn.stopping) return;
492      const toolRunning = [...projector.tools.values()].some(x => x.card?.state === 'running' || x.card?.state === 'proposed') || pending.size > 0 && pendingFor(chatId).length > 0;
493      const limit = toolRunning ? stallToolMs : stallMs;
494      // A local engine reading a long prompt sends the Harness nothing for minutes (#3623). Its /metrics progress counts as activity,
495      // for at most engineGraceMs after the Harness last spoke: progress for another chat cannot keep a lost turn alive forever.
496      if (turn.route?.kind === 'local' && Date.now() - turn.heard < engineGraceMs) {
497        let mark = null;
498        try { mark = engineProgress(turn.route.instanceId); } catch { /* no progress known: the Harness alone decides */ }
499        if (mark != null && mark !== turn.engineMark) { turn.engineMark = mark; turn.lastActivity = Date.now(); return; }
500      }
501      if (Date.now() - turn.lastActivity < limit) return;
502      turn.stalledFor = Math.round((Date.now() - turn.lastActivity) / 1000);
503      turn.stopping = true;
504      void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {});
505      for (const h of turn.children.values()) if (!h.done) void runtime.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: sessionId, mode: 'continuable' }).catch(() => {});
506      const mins = Math.max(1, Math.round(turn.stalledFor / 60));
507      turn.finish(`The assistant stopped answering for ${mins > 1 ? mins + ' minutes' : 'a minute'}, so I ended this turn. Anything it already finished is kept. Send your message again to go on.`);
508    }, Math.min(15_000, Math.max(200, Math.floor(stallMs / 4))));
509    turn.watchdog.unref?.();
510    async function finishTurn(failure) {
511      if (turn.finished) return;
512      turn.finished = true;
513      for (const [k, v] of questions) if (v.sessionId === turn.sessionId) questions.delete(k);
514      clearTimeout(turn.settleTimer);
515      clearInterval(turn.watchdog);
516      turn.follow?.close();
517      for (const child of turn.children.values()) child.follow?.close();
518      if (turn.stopping && !failure) projector.ended = turn.guard ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'user' } };
519      reporter.clear();
520      const extra = [];
521      try { if (toolsRan) for (const d of tracker.sweep()) { emit(d); groups.addFile(d); } } catch { /* never blocks the end of a turn */ }
522      if (workspacePath) folderClaims.end(workspacePath, chatId);
523      groups.end();
524      if (researchTopic && !failure && !turn.stopping) { const sources = parseSources(written.all); if (sources.length) extra.push({ type: 'research', topic: researchTopic, sources }); }
525      try { extra.push(...settlePlan(failure)); } catch { /* a plan frame must never break the end of a turn */ }
526      // 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).
527      let noteReason = turn.guard ?? null;
528      // A reply the length limit cut ends with a sentence that says so (and what was lost), never with silence (AGENT-LOST).
529      const cutEnd = !failure && !turn.stopping && projector.ended?.kind === 'max-tokens';
530      if (cutEnd && !noteReason) {
531        const note = cutNotice({ ...projector.cut(), retrying: false });
532        extra.push({ type: 'delta', own: true, text: `
533
534${note.text}`, key: note.key, values: note.values, noteReason: 'cut' });
535      }
536      if (!noteReason && !cutEnd && guard && !failure && !turn.stopping && !turn.goalRun) {
537        noteReason = guard.silent({ ended: projector.ended, wrote: projector.emittedAny === true, acted: projector.tools.size > 0, contextTokens: projector.contextTokens });
538      }
539      if (noteReason && !extra.some(f => f.type === 'plan' && f.event === 'proposed')) { const note = guardNote(noteReason); if (note) extra.push(note); }
540      for (const f of extra) emit(f);
541      // The answer speed of a turn on this computer is the engine's own (tokens it produced over its decode time, as the Monitor shows it).
542      const engine = !failure && route.kind === 'local' ? await engineSpeedOf(route, projector) : null;
543      const frames = failure ? [{ type: 'error', message: plainAgentFailure(failure), details: failure, code: 'AGENT_STOPPED' }] : projector.finish({ model: route.name, contextMax: route.contextWindow, engine });
544      for (const f of frames.slice(0, -1)) emit(f);
545      // Messages typed while the goal ran and not delivered between steps go back to the page now, to be sent as ordinary messages.
546      if (turn.goalRun && attached) {
547        const left = queueView(chatId);
548        if (left.length) { queues.delete(chatId); onQueue(chatId, []); emit({ type: 'queued-release', messages: left.map(({ id, text }) => ({ id, text })) }); }
549      }
550      for (const f of frames.slice(-1)) emit(f);
551      c.turn = null;
552      // What a page that was away needs to show the end of this turn (attach, below).
553      c.last = { requestId, sessionId, mode: appliedMode, model: route.name, contextMax: route.contextWindow, remoteModel: route.kind === 'api', content: hideDeltas ? '' : written.all.slice(0, 4_000_000), reasoning: written.reasoning, cards: [...projector.tools.values()].filter(t => t.card).map(t => t.card), terminal };
554      turn.ended.resolve({ reason: projector.ended, failure: failure ?? null });
555      notifyIdle();
556      // 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.
557      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);
558    }
559
560    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 } : {}) });
561
562    turn.follow = runtime.gw.openStream('session/follow', { request: { address: { kind: 'session', sessionId }, assistantStream: true } }, {
563      onItem: item => {
564        if (item.type === 'snapshot') {
565          if (turn.lastSeq < 0) turn.lastSeq = item.cursor;
566          else for (const r of item.records ?? []) if (r.type === 'event' && r.event.seq > turn.lastSeq) handle({ type: 'event', event: r.event });
567          turn.snapshot.resolve();
568          return;
569        }
570        handle(item);
571      },
572      onError: e => finishTurn(`The agent lost the session stream: ${e.message}`),
573    });
574
575    /** The guard says stop: end the turn the way Stop does, but as a normal end with a plain message (finishTurn). */
576    function trip(reason) {
577      if (!reason || turn.guard || turn.finished || turn.stopping) return;
578      turn.guard = reason;
579      log(`agent · turn guard: ${reason} (searches ${guard?.searches ?? 0}, failed in a row ${guard?.failedInARow ?? 0}, plan rewrites ${guard?.rewrites ?? 0})`);
580      void stop(chatId).catch(() => {});
581    }
582
583    function handle(item) {
584      if (turn.finished) return;
585      turn.lastActivity = Date.now();
586      turn.heard = turn.lastActivity;
587      if (item.type === 'event') {
588        const e = item.event;
589        if (e.seq <= turn.lastSeq) return;
590        turn.lastSeq = e.seq;
591        // The turn is ours from the user message that carries our request id. Until then an older,
592        // detached turn on the same session may still be finishing; its events are not ours.
593        if (!turn.live) {
594          if (e.type === 'user/message' && e.data?.source?.rpcId === requestId) turn.live = true;
595          return;
596        }
597      } else if (!turn.live) return;
598      for (const f of projector.consume(item)) emit(f);
599      if (guard && projector.contextTokens != null) trip(guard.context(projector.contextTokens));
600      if (item.type === 'event') watchParent(item.event);
601    }
602
603    // -- helper agents ---------------------------------------------------------------------------------------
604
605    const rowFrame = child => ({ type: 'agent', agent: child.cp.agent() });
606    const emitRow = (child, force = false) => {
607      const now = Date.now();
608      if (!force && now - child.lastRow < 400) { child.rowPending = true; return; }
609      child.lastRow = now; child.rowPending = false;
610      emit(rowFrame(child));
611      const working = [...turn.children.values()].filter(h => !h.done).length;
612      if (working && !turn.parentOpen) reporter.set({ phase: 'helpers', code: 'helpers', text: `Helpers are working (${working})…`, key: 'Helpers are working ({0})…', values: [working], args: { n: working } });
613    };
614
615    function openChild(d) {
616      const id = d.childId;
617      if (!id || turn.children.has(id)) return;
618      const cp = new ChildProjector({ id, name: d.label || 'Helper' });
619      const child = { id, cp, follow: null, noticed: false, done: false, lastRow: 0, rowPending: false, endedAt: 0 };
620      turn.children.set(id, child);
621      emitRow(child, true);
622      const fold = item => {
623        if (turn.finished) return;
624        turn.lastActivity = turn.heard = Date.now();
625        // A helper that finishes before its throttled "working" row went out would show queued -> completed and never "working": send the held row first.
626        if (item.type === 'event' && item.event.type === 'turn/end' && child.rowPending) emitRow(child, true);
627        const { frames, row } = cp.consume(item);
628        for (const f of frames) emit(f);
629        if (item.type === 'event' && item.event.type === 'turn/end') { child.done = true; child.endedAt = Date.now(); emitRow(child, true); armSettle(); return; }
630        if (item.type === 'event' && child.done && cp.status === 'working') { child.done = false; }
631        if (row) emitRow(child);
632      };
633      child.follow = runtime.gw.openStream('session/follow', {
634        request: { address: { kind: 'subagent', parentSessionId: sessionId, childSessionId: id, mode: d.mode ?? 'unknown' }, assistantStream: true },
635      }, {
636        onItem: item => {
637          if (item.type === 'snapshot') { for (const r of item.records ?? []) if (r.type === 'event') fold({ type: 'event', event: r.event }); return; }
638          fold(item);
639        },
640        onError: e => {
641          log(`agent · helper stream ended: ${e.message}`);
642          if (!child.done) { child.done = true; child.endedAt = Date.now(); cp.status = 'failed'; cp.failure = 'Lost contact with this helper.'; cp.endedAt = Date.now(); emitRow(child, true); armSettle(); }
643        },
644      });
645      // A late reader still gets the final row: flush any row held back by the throttle.
646      child.flush = after(500, function tick() { if (!turn.finished && child.rowPending) emitRow(child, true); if (!turn.finished && !child.done) child.flush = after(500, tick); });
647    }
648
649    function watchParent(e) {
650      const d = e.data ?? {};
651      switch (e.type) {
652        case 'turn/start':
653          turn.parentOpen = true;
654          if (turn.research) turn.research.waitingStart = false;
655          turn.cutWaiting = false;
656          clearTimeout(turn.settleTimer);
657          // After Stop, a helper's report would start a new turn that nobody asked for.
658          if (turn.stopping) void runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {});
659          break;
660        case 'turn/end':
661          turn.parentOpen = false;
662          armSettle();
663          break;
664        // The first turn of a prompt may have started before this follow stream attached (no turn/start seen): any step of the parent is proof that it is
665        // still working. Without this a helper that finished while the parent was still answering ended the run early ("The agent turn was interrupted").
666        case 'step/start':
667          if (!turn.parentOpen) { turn.parentOpen = true; clearTimeout(turn.settleTimer); }
668          break;
669        case 'tool/call':
670          if (d.name === 'subagent' || d.name === 'subagent_fork') turn.subagentCalls.set(d.callId, parseArgs(d.arguments));
671          break;
672        case 'subagent/catalog':
673          openChild(d);
674          break;
675        case 'tool/result': {
676          const call = turn.subagentCalls.get(d.message?.toolCallId);
677          const text = (d.message?.content ?? []).map(p => p.text ?? '').join(' ');
678          const started = /started subagent ([0-9a-f-]{36})/i.exec(text);
679          const child = started ? turn.children.get(started[1]) : null;
680          if (call && child) { child.cp.task = String(call.prompt ?? call.description ?? '').replace(/\s+/g, ' ').trim().slice(0, 140); emitRow(child, true); }
681          break;
682        }
683        case 'user/message':
684          if (d.source?.kind === 'goal' && Number.isInteger(d.source.round)) { turn.goalRound = d.source.round; void announceGoal(); }
685        // falls through
686        case 'agent/inbox/spliced': {
687          const hit = JSON.stringify(d);
688          if (!/Background subagent/.test(hit)) break;
689          for (const child of turn.children.values()) if (hit.includes(child.id)) child.noticed = true;
690          break;
691        }
692        default:
693          break;
694      }
695    }
696
697    // -- plans and goal steps ----------------------------------------------------------------------------------
698
699    const planFrame = (event, plan, extra = {}) => ({ type: 'plan', event, plan: planView(plan), ...extra });
700    const publishPlan = (event, plan) => { onPlan(chatId, event, planView(plan)); return planFrame(event, plan); };
701    const stepFrame = (plan, index) => {
702      const st = plan.steps[index];
703      return { type: 'plan-step', planId: plan.id, stepId: st.id, index: index + 1, total: plan.steps.length, state: st.state, text: st.text, summary: st.summary ?? null, line: stepLine(index, plan.steps.length, st.text, st.state === 'running' ? 'started' : st.state) };
704    };
705    const currentStep = plan => plan.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped');
706
707    /** What the end of the turn means for the plan: a plan turn makes one; a step run records where it stopped. */
708    function settlePlan(failure) {
709      if (planTask) {
710        if (failure || (turn.stopping && !turn.guard)) return [];
711        const parsed = parsePlan(written.all, planTask);
712        if (!parsed) return [];
713        const plan = plans.create(chatId, { title: parsed.title, steps: parsed.steps, request: planTask, ...(turn.guard ? { caution: GUARD_NOTES[turn.guard] } : {}) });
714        return [publishPlan('proposed', plan)];
715      }
716      const run = turn.plan;
717      if (!run) return [];
718      const plan = plans.get(chatId);
719      if (!plan || plan.id !== run.id) return [];
720      if (plan.state !== 'running') return [];
721      const out = [];
722      const at = currentStep(plan);
723      plans.update(chatId, p => {
724        if (at < 0) { p.state = 'done'; return; }
725        // The step that was running goes back to waiting, so Resume runs it again.
726        p.steps[at].state = 'pending';
727        p.state = 'paused';
728      });
729      const updated = plans.get(chatId);
730      if (at >= 0) out.push(stepFrame(updated, at));
731      out.push(publishPlan(updated.state === 'done' ? 'done' : 'paused', updated));
732      return out;
733    }
734
735    /** The goal the Harness runs for the plan's next waiting step, and the frames that say so. */
736    async function startStep(plan, index) {
737      plans.update(chatId, p => { p.state = 'running'; p.goalStarted = true; p.steps[index].state = 'running'; });
738      const now = plans.get(chatId);
739      await runtime.gw.rpc('goals/create', { agentId: sessionId, request: { objective: stepObjective(now, index) } });
740      written.step = ''; written.stepAt = Date.now();
741      emit(stepFrame(now, index));
742      emit(publishPlan('step', now));
743      const st = now.steps[index];
744      reporter.set({ phase: 'goal', code: 'goal-step', text: stepLine(index, now.steps.length, st.text, 'started'), key: '{0}', values: [st.text], args: { step: index + 1, steps: now.steps.length } });
745    }
746
747    /** One goal step finished: say so, hand over queued messages, and begin the next step (or end the plan). */
748    async function advancePlan() {
749      const run = turn.plan;
750      const plan = plans.get(chatId);
751      if (!run || !plan || plan.id !== run.id) return false;
752      const at = currentStep(plan);
753      if (at < 0) return false;
754      const cards = [...projector.tools.values()].filter(x => x.calledAt >= (written.stepAt ?? 0) - 50 && x.card?.state === 'done').map(x => x.card);
755      const summary = stepSummary(cards, written.step.split(/\n\s*\n/).filter(Boolean).at(-1) ?? written.step);
756      plans.update(chatId, p => { p.steps[at].state = 'done'; p.steps[at].summary = summary; });
757      let now = plans.get(chatId);
758      emit(stepFrame(now, at));
759      emit({ type: 'delta', own: true, text: `\n\n${stepLine(at, now.steps.length, now.steps[at].text, 'done')}\n` });
760      const next = currentStep(now);
761      emit(publishPlan(next < 0 ? 'done' : 'step', next < 0 ? (plans.update(chatId, p => { p.state = 'done'; }), plans.get(chatId)) : now));
762      await deliverQueued(at + 1);
763      if (turn.stopping || turn.finished) return true;
764      if (next < 0) return false;
765      // One step per turn (Time-skip): the plan stays open for the next step, which starts in a session of its own so the conversation never grows across steps.
766      if (run.once) { plans.update(chatId, p => { p.state = 'approved'; }); emit(publishPlan('step', plans.get(chatId))); return false; }
767      await startStep(plans.get(chatId), next);
768      void announceGoal();
769      return true;
770    }
771
772    /** Hand the person's queued messages to the assistant, one at a time, each answered before the next. */
773    async function deliverQueued(afterStep) {
774      const list = queues.get(chatId) ?? [];
775      while (list.length && !turn.stopping && !turn.finished) {
776        const item = list.shift();
777        if (!list.length) queues.delete(chatId);
778        onQueue(chatId, queueView(chatId));
779        emit({ type: 'queued-message', state: 'delivered', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, afterStep, queue: queueView(chatId) });
780        try { await runtime.gw.rpc('session/prompt', { request: { requestId: `queued-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: item.text }] } }); }
781        catch { emit({ type: 'queued-release', messages: [{ id: item.id, text: item.text }] }); continue; }
782        // Wait for the answer: the parent opens a turn for it and closes it again.
783        const t0 = Date.now();
784        while (!turn.parentOpen && Date.now() - t0 < 4000 && !turn.finished) await new Promise(r => setTimeout(r, 50));
785        while (turn.parentOpen && !turn.finished && !turn.stopping) await new Promise(r => setTimeout(r, 100));
786      }
787    }
788
789    /**
790     * The run is over when the parent is idle and every helper has finished and reported back. A helper's report
791     * wakes the parent a moment after the helper ends, so a helper that ended but has not reported yet keeps the run
792     * open (for a few seconds at most); after Stop nobody waits for reports.
793     */
794    function armSettle() {
795      clearTimeout(turn.settleTimer);
796      if (turn.finished) return;
797      turn.settleTimer = after(turn.stopping ? 1200 : turn.children.size ? 600 : 0, async () => {
798        if (turn.finished || turn.parentOpen || turn.advancing) return;
799        const open = [...turn.children.values()];
800        if (open.some(c => !c.done)) return;
801        if (!turn.stopping) {
802          if (open.some(c => !c.noticed && Date.now() - c.endedAt < 8000)) { armSettle(); return; }
803          // An armed goal starts its next round as soon as the agent is idle: the run is not over until the goal stops.
804          const current = await goalGet();
805          if (turn.finished || turn.parentOpen) return;
806          if (current && current.phase === 'active' && current.activation === 'armed') { turn.settleTimer = after(700, armSettle); return; }
807          // A reply the length limit cut (AGENT-LOST): the agent lost what it was writing. Say so in the chat and ask it to carry on in smaller pieces, twice at most.
808          if (turn.cutWaiting) { turn.settleTimer = after(300, armSettle); return; }
809          if (projector.ended?.kind === 'max-tokens' && !turn.goalRun && !turn.stopping && (turn.cuts ?? 0) < MAX_CUT_RETRIES) {
810            const cut = projector.cut();
811            turn.cuts = (turn.cuts ?? 0) + 1;
812            const note = cutNotice({ ...cut, retrying: true });
813            emit({ type: 'delta', own: true, text: `
814
815${note.text}
816
817`, key: note.key, values: note.values, noteReason: 'cut' });
818            for (const f of projector.clearCut()) emit(f);
819            turn.cutWaiting = true;
820            try { await runtime.gw.rpc('session/prompt', { request: { requestId: `cut-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: cutNudge(cut) }] } }); }
821            catch { turn.cutWaiting = false; finishTurn(null); return; }
822            turn.settleTimer = after(500, armSettle);
823            return;
824          }
825          // Research: gather (search and read pages), then write the answer in the fixed shape. A step that did not open pages is sent back once.
826          if (turn.research && !turn.stopping) {
827            const r = turn.research;
828            if (r.waitingStart) { turn.settleTimer = after(300, armSettle); return; }
829            const opened = [...projector.tools.values()].filter(x => x.card?.name === 'web_fetch' && x.card.state === 'done').length;
830            const prompt = r.phase === 'write' ? null : (opened < 2 && !r.nudged) ? RESEARCH_NUDGE : researchWritePrompt(researchTopic);
831            if (prompt) {
832              if (prompt !== RESEARCH_NUDGE) { r.phase = 'write'; hideDeltas = false; written.all = ''; reporter.set({ phase: 'waiting', code: 'research-writing', text: 'Writing the answer…', key: 'Writing the answer…', values: [], args: {} }); } else r.nudged = true;
833              r.waitingStart = true;
834              try { await runtime.gw.rpc('session/prompt', { request: { requestId: `research-${randomUUID()}`, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }] } }); }
835              catch { r.waitingStart = false; hideDeltas = false; finishTurn(null); return; }
836              turn.settleTimer = after(500, armSettle);
837              return;
838            }
839          }
840          // A plan step's goal is complete: record it, deliver queued messages, start the next step.
841          if (turn.plan && current && current.phase === 'complete' && !turn.advancing) {
842            turn.advancing = true;
843            let more = false;
844            try { more = await advancePlan(); } catch (e) { emit({ type: 'delta', own: true, text: `\n\nThe plan stopped: ${plainGoalError(e)}\n` }); }
845            turn.advancing = false;
846            if (more && !turn.finished && !turn.stopping) { turn.settleTimer = after(700, armSettle); return; }
847          }
848
849          if (turn.goalRun && current) { const line = goalEnding(current); if (line) emit({ type: 'delta', text: line }); }
850          if (turn.goalRun) await announceGoal(true);
851        }
852        finishTurn(null);
853      });
854    }
855    const goalGet = () => runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined);
856    /** The goal's state to the page: a `goal` frame, the SSE event for the bar, and (while a round runs) the status line. */
857    async function announceGoal(final = false) {
858      const view = await goalGet();
859      if (turn.finished && !final) return;
860      const goal = goalObject(view, chatId);
861      emit({ type: 'goal', goal });
862      onGoal(chatId, goal);
863      if (!final && goal && goal.phase === 'active' && turn.goalRound) reporter.set({ phase: 'goal', code: 'goal-step', text: 'Working on the goal…', args: { round: turn.goalRound, max: goal.maxRounds } });
864    }
865    turn.announceGoal = announceGoal;
866    turn.announceQueue = frame => emit(frame);
867    turn.announceQuestion = frame => emit(frame);
868
869    const snapshotTimer = {};
870    await Promise.race([turn.snapshot.promise, new Promise((_, rej) => { snapshotTimer.t = after(20_000, () => rej(new Error('the session stream did not open'))); })])
871      .catch(e => { finishTurn(e.message); })
872      .finally(() => clearTimeout(snapshotTimer.t));
873    if (turn.finished) return { error: true };
874    if (turn.stopBeforePrompt || c.cancelStart) { projector.ended = { kind: 'aborted', reason: { kind: 'user' } }; finishTurn(null); return { cancelled: true }; }
875
876    if (goal) {
877      // A goal run has no prompt of its own: the Harness's goal driver starts the rounds. Everything from now on is ours.
878      turn.live = true; turn.goalRun = true;
879      try {
880        if (planRun) {
881          const plan = plans.get(chatId);
882          if (!plan || plan.id !== planRun.planId) throw new AgentUnavailable('That plan is no longer there. Ask for a new one with /plan.', 'plan-gone');
883          turn.plan = { id: plan.id, once: !!planRun.once };
884          const at = currentStep(plan);
885          if (at < 0) throw new AgentUnavailable('Every step of this plan is already done.', 'plan-done');
886          if (goal.action === 'resume' && plan.goalStarted) {
887            plans.update(chatId, p => { p.state = 'running'; p.steps[at].state = 'running'; });
888            await startGoal(runtime, sessionId, goal);
889            emit(publishPlan('step', plans.get(chatId)));
890          } else await startStep(plan, at);
891        } else {
892          await startGoal(runtime, sessionId, goal);
893        }
894      } catch (e) { finishTurn(e instanceof AgentUnavailable ? e.message : plainGoalError(e)); return { error: true }; }
895      reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' });
896      void announceGoal();
897    } else {
898      let prompt = message;
899      if (fresh && history.length) prompt = withEarlierConversation(history, message);
900      try {
901        await runtime.gw.rpc('session/prompt', { request: { requestId, sessionId, mode: 'queue', content: [{ type: 'text', text: prompt }, ...imageParts(images)] } });
902      } catch (e) {
903        finishTurn(`The agent did not accept the message: ${e.message}`);
904        return { error: true };
905      }
906    }
907    if (!goal) reporter.set({ phase: 'waiting', code: 'reading-prompt', text: 'Reading your message…' });
908    turn.prompted = true;
909    if (turn.stopBeforePrompt) {
910      // Stop landed in the instant between 'prompt sent' and 'prompt accepted'. A cancel before the turn
911      // starts arms nothing, so wait for the turn to be ours, then cancel it.
912      for (let i = 0; i < 100 && !turn.live && !turn.finished; i++) await new Promise(r => setTimeout(r, 50));
913      if (!turn.finished) await runtime.gw.rpc('session/cancel', { request: { sessionId } }).catch(() => {});
914    }
915
916    // Wait for the turn, or for the client to leave. Leaving does not stop the turn.
917    const gone = new Promise(r => signal?.addEventListener('abort', () => r('detached'), { once: true }));
918    const outcome = await Promise.race([turn.ended.promise, gone]);
919    if (outcome === 'detached') return { detached: true, sessionId, ended: turn.ended.promise.then(r => ({ ...r, tokensOut: projector.tokensOut })) };
920    return { sessionId, reason: outcome.reason, tokensIn: projector.tokensIn, tokensOut: projector.tokensOut };
921  }
922
923  // -- /goal -----------------------------------------------------------------------------------------------
924
925  /** Create or resume the chat's goal; the Harness's goal driver then runs the rounds by itself. */
926  async function startGoal(runtime, sessionId, goal) {
927    if (goal.action === 'create') {
928      const request = { objective: goal.objective, ...(goal.maxRounds ? { maxGoalRounds: goal.maxRounds } : {}) };
929      await runtime.gw.rpc('goals/create', { agentId: sessionId, request });
930      return;
931    }
932    const current = await runtime.gw.rpc('goals/get', { agentId: sessionId });
933    if (!current) throw new AgentUnavailable('There is no goal to continue. Start one with /goal followed by what you want done.', 'goal-none');
934    await runtime.gw.rpc('goals/resume', { agentId: sessionId, ref: { id: current.id, revision: current.revision } });
935  }
936
937  async function pauseGoal(runtime, sessionId, chatId = null) {
938    try {
939      const current = await runtime.gw.rpc('goals/get', { agentId: sessionId });
940      if (current && current.phase === 'active') {
941        await runtime.gw.rpc('goals/pause', { agentId: sessionId, ref: { id: current.id, revision: current.revision } });
942        if (chatId) onGoal(chatId, goalObject(await runtime.gw.rpc('goals/get', { agentId: sessionId }).catch(() => undefined)));
943      }
944    } catch { /* no goal service, or nothing to pause */ }
945  }
946
947  /** The goal as the page and the goal bar see it (notes-split-agent3.md), or null. */
948  function goalObject(view, chatId = null) {
949    if (!view) return null;
950    const phase = ['active', 'paused', 'complete', 'blocked'].includes(view.phase) ? view.phase : 'blocked';
951    // A goal that is running a plan (or the points of a goal) shows the plan's title and which step it is on.
952    const plan = chatId ? plans.get(chatId) : null;
953    const running = plan && plan.goalStarted && ['running', 'paused'].includes(plan.state) ? plan : null;
954    const at = running ? running.steps.findIndex(x => x.state !== 'done' && x.state !== 'skipped') : -1;
955    const step = running && at >= 0 ? { index: at + 1, total: running.steps.length, text: running.steps[at].text } : null;
956    return { objective: step ? running.title : String(view.objective ?? ''), ...(step ? { step } : {}), phase, round: view.roundsStarted ?? 0, maxRounds: view.maxGoalRounds ?? null, ...(phase === 'blocked' ? { blocked: plainBlocker(view.blockedReason) } : {}) };
957  }
958
959  /** The goal of a chat now, from the Harness (null: none, or the agent is not running). */
960  async function goalState(chatId) {
961    const known = sessionMap[chatId]?.sessionId;
962    if (!known || !rt?.hp.running) return null;
963    return goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId);
964  }
965
966  /** Pause, edit or remove the goal from the goal bar. Instant; resume runs rounds and goes through the chat stream. */
967  async function goalControl({ chatId, action, text }) {
968    const known = sessionMap[chatId]?.sessionId;
969    if (!known || !rt?.hp.running) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none');
970    const current = await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined);
971    if (!current) throw new AgentUnavailable('There is no goal in this chat yet.', 'goal-none');
972    const ref = { id: current.id, revision: current.revision };
973    try {
974      if (action === 'pause') { if (current.phase === 'active') await rt.gw.rpc('goals/pause', { agentId: known, ref }); }
975      else if (action === 'clear') await rt.gw.rpc('goals/clear', { agentId: known, ref });
976      else if (action === 'edit') {
977        const objective = String(text ?? '').trim().slice(0, 4000);
978        if (!objective) throw new AgentUnavailable('A goal needs a few words about what you want done.', 'goal-text');
979        await rt.gw.rpc('goals/edit', { agentId: known, ref, request: { objective } });
980      } else throw new AgentUnavailable('That goal action is not known.', 'goal-action');
981    } catch (e) { throw e instanceof AgentUnavailable ? e : new AgentUnavailable(plainGoalError(e), 'goal-failed', e.message); }
982    if (action === 'clear') { const plan = plans.get(chatId); if (plan && ['running', 'paused'].includes(plan.state)) { plans.update(chatId, p => { p.state = 'stopped'; for (const st of p.steps) if (st.state === 'running') st.state = 'pending'; }); onPlan(chatId, 'stopped', planView(plans.get(chatId))); } }
983    const goal = action === 'clear' ? null : goalObject(await rt.gw.rpc('goals/get', { agentId: known }).catch(() => undefined), chatId);
984    onGoal(chatId, goal);
985    return { goal };
986  }
987
988  /** The goal's state in plain words. */
989  function describeGoal(view) {
990    if (!view) return 'No goal is set. Start one with /goal followed by what you want done.';
991    const what = `"${view.objective}"`;
992    if (view.phase === 'active') return `Working on the goal ${what}.`;
993    if (view.phase === 'paused') return `The goal ${what} is paused. Type /goal resume to go on.`;
994    if (view.phase === 'complete') return `The goal ${what} is complete.`;
995    return `The goal ${what} stopped: ${plainBlocker(view.blockedReason)}`;
996  }
997
998  /**
999   * Handle a "/goal ..." line for a chat, as the Harness's own /goal command reads it: nothing = show the goal,
1000   * clear, pause, resume, edit <text>, or any other text = a new goal. Starting or resuming runs the rounds and
1001   * streams them like a chat turn (Stop pauses the goal); every other verb answers at once.
1002   */
1003  async function goalCommand(options) {
1004    const { chatId, line, onFrame } = options;
1005    const text = String(line ?? '').trim();
1006    const verb = text.split(/\s+/)[0]?.toLowerCase() ?? '';
1007    const rest = text.slice(verb.length).trim();
1008    const say = reply => {
1009      onFrame({ type: 'queued', requestId: `goal-${randomUUID()}` });
1010      onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] });
1011      onFrame({ type: 'delta', text: reply });
1012      onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 });
1013      return { goal: true };
1014    };
1015    if (tools()?.off?.has('goals')) return say('Goals are turned off. You can turn them back on in Settings, Tools.');
1016    const known = sessionMap[chatId]?.sessionId;
1017    const quick = ['', 'clear', 'pause', 'edit', 'complete'].includes(verb) || (verb === 'status');
1018    let runtime = rt;
1019    if (quick) {
1020      if (!known || !runtime?.hp.running) return say(verb === '' || verb === 'status' ? describeGoal(null) : 'There is no goal in this chat yet.');
1021      const current = await runtime.gw.rpc('goals/get', { agentId: known }).catch(() => undefined);
1022      const ref = current ? { id: current.id, revision: current.revision } : null;
1023      try {
1024        if (verb === '' || verb === 'status') return say(describeGoal(current));
1025        if (!ref) return say('There is no goal in this chat yet.');
1026        if (verb === 'clear') { await runtime.gw.rpc('goals/clear', { agentId: known, ref }); return say('The goal is cleared.'); }
1027        if (verb === 'pause') {
1028          if (current.phase === 'active') await runtime.gw.rpc('goals/pause', { agentId: known, ref });
1029          return say(describeGoal(await runtime.gw.rpc('goals/get', { agentId: known })));
1030        }
1031        if (verb === 'complete') { await runtime.gw.rpc('goals/complete', { agentId: known, ref }); return say('The goal is marked complete.'); }
1032        if (verb === 'edit') {
1033          if (!rest) return say('Type /goal edit followed by the new wording of the goal.');
1034          await runtime.gw.rpc('goals/edit', { agentId: known, ref, request: { objective: rest } });
1035          return say(`The goal now reads: "${rest}".`);
1036        }
1037      } catch (e) { return say(plainGoalError(e)); }
1038    }
1039    if (verb === 'resume') {
1040      const plan = plans.get(chatId);
1041      const goalPlan = plan && plan.goalStarted && plan.state === 'paused' ? { planId: plan.id } : null;
1042      return runTurn({ ...options, goal: { action: 'resume' }, ...(goalPlan ? { planRun: goalPlan } : {}) });
1043    }
1044    // A goal whose own words hold numbered points ("1. ... 2. ... 3. ...") runs point by point, each one reported.
1045    const points = parsePoints(text);
1046    if (points) {
1047      const plan = plans.create(chatId, { title: points.title, steps: points.steps, request: text, source: 'goal', state: 'approved' });
1048      onPlan(chatId, 'approved', planView(plan));
1049      return runTurn({ ...options, goal: { action: 'create', objective: text }, planRun: { planId: plan.id } });
1050    }
1051    // Any other text is a new goal. One unfinished goal at a time (the Harness's rule): say so in plain words.
1052    return runTurn({ ...options, goal: { action: 'create', objective: text } });
1053  }
1054
1055  // -- /plan -----------------------------------------------------------------------------------------------
1056
1057  /** A short answer in the chat that the page translates (the sentence is in the interface catalog, "values" fill its slots). */
1058  function sayKey(options, template, values = []) {
1059    const { onFrame } = options;
1060    onFrame({ type: 'queued', requestId: 'compact-' + randomUUID() });
1061    onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] });
1062    onFrame({ type: 'delta', text: fill(template, values), key: template, values });
1063    onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 });
1064    return { compact: true };
1065  }
1066
1067  /** A short answer in the chat (no model): the same frames a turn sends. */
1068  function sayOnce(options, reply) {
1069    const { onFrame } = options;
1070    onFrame({ type: 'queued', requestId: `plan-${randomUUID()}` });
1071    onFrame({ type: 'start', model: '', contextMax: 0, demo: false, remoteModel: false, agent: true, mode: modeOf(options.mode), skills: [] });
1072    onFrame({ type: 'delta', text: reply });
1073    onFrame({ type: 'done', finishReason: 'stop', tokensIn: null, tokensOut: null, usageSource: 'unavailable', durationMs: 0 });
1074    return { plan: true };
1075  }
1076
1077  /**
1078   * "/plan <what you want>": the assistant looks around (the chat is put in Plan mode for this turn, so nothing can change), writes the
1079   * plan, and the host sends it as a `plan` frame. Nothing runs until the person approves it.
1080   */
1081  async function planCommand(options) {
1082    const task = String(options.line ?? '').trim();
1083    if (!task) {
1084      const open = plans.get(options.chatId);
1085      return sayOnce(options, open && ['proposed', 'approved'].includes(open.state)
1086        ? 'A plan is waiting for you above. Approve it, edit it or reject it, or type /plan followed by something else to make a new one.'
1087        : 'Type /plan followed by what you want done, for example: /plan build a small pagoda page. I will look around and write a plan; nothing changes until you approve it.');
1088    }
1089    return runTurn({ ...options, message: planPrompt(task), planTask: task, mode: 'plan' });
1090  }
1091
1092  /**
1093   * "/research <topic>": the assistant searches the web, opens and reads pages, and writes a short structured answer (Summary, Key findings,
1094   * Sources). The host also sends the sources as a `research` frame before the end of the turn. Needs web search turned on.
1095   */
1096  async function researchCommand(options) {
1097    const topic = String(options.line ?? '').trim();
1098    if (!topic) return sayOnce(options, 'Type /research followed by what you want to know, for example: /research how do heat pumps compare with gas boilers. I will search the web, read the pages and answer with sources.');
1099    if (tools()?.off?.has('search')) return sayOnce(options, 'Research needs web search, which is turned off. Turn it on in Settings, Tools (DuckDuckGo needs no key), then try again.');
1100    return runTurn({ ...options, message: researchPrompt(topic), researchTopic: topic });
1101  }
1102
1103  const planGone = () => new AgentUnavailable('There is no plan waiting in this chat. Ask for one with /plan followed by what you want done.', 'plan-gone');
1104  function planOf(chatId, planId) {
1105    const plan = plans.get(chatId);
1106    if (!plan || (planId && plan.id !== planId)) throw planGone();
1107    return plan;
1108  }
1109  const mustBeOpen = plan => { if (plan.state !== 'proposed' && plan.state !== 'approved') throw new AgentUnavailable('This plan has already been used. Ask for a new one with /plan.', 'plan-used'); };
1110
1111  /** A short note added to every step of the chat's plan (the Time-skip B path: where its work comes from). */
1112  function setPlanBriefing(chatId, text) { plans.update(chatId, p => { p.briefing = String(text ?? '').slice(0, 600); }); }
1113
1114  /** The plan of a chat, or null. */
1115  const planState = chatId => planView(plans.get(chatId));
1116
1117  /** Approve, edit or reject the plan; instant. Approve also returns the message that carries the plan out as an ordinary turn. */
1118  function planControl({ chatId, planId, action, steps, title }) {
1119    const plan = planOf(chatId, planId);
1120    if (action === 'edit') {
1121      mustBeOpen(plan);
1122      const next = editedSteps(steps, plan.steps);
1123      const t = String(title ?? '').replace(/\s+/g, ' ').trim().slice(0, 80);
1124      plans.update(chatId, p => { p.steps = next; if (t) p.title = t; p.state = 'proposed'; });
1125      onPlan(chatId, 'edited', planView(plans.get(chatId)));
1126      return { plan: planView(plans.get(chatId)) };
1127    }
1128    if (action === 'approve') {
1129      mustBeOpen(plan);
1130      plans.update(chatId, p => { p.state = 'approved'; });
1131      const approved = plans.get(chatId);
1132      onPlan(chatId, 'approved', planView(approved));
1133      return { plan: planView(approved), prompt: planAsPrompt(approved) };
1134    }
1135    if (action === 'reject') {
1136      mustBeOpen(plan);
1137      plans.update(chatId, p => { p.state = 'rejected'; });
1138      onPlan(chatId, 'rejected', planView(plans.get(chatId)));
1139      return { plan: planView(plans.get(chatId)) };
1140    }
1141    throw new AgentUnavailable('That plan action is not known.', 'plan-action');
1142  }
1143
1144  /** "Start as goal": each step of the plan becomes a goal step, run one after another and reported. Streams like a chat turn. */
1145  async function planGoal(options) {
1146    const { chatId, planId } = options;
1147    let plan;
1148    try { plan = planOf(chatId, planId); } catch (e) { return sayOnce(options, e.message); }
1149    if (modeOf(options.mode) === 'plan') return sayOnce(options, 'Plan mode only looks, so it cannot carry out a plan. Switch this chat to Manual or Bypass, then start it again.');
1150    if (plan.state === 'paused' && plan.goalStarted) return goalCommand({ ...options, line: 'resume' });
1151    try { mustBeOpen(plan); } catch (e) { return sayOnce(options, e.message); }
1152    if (tools()?.off?.has('goals')) return sayOnce(options, 'Goals are turned off. You can turn them back on in Settings, Tools.');
1153    plans.update(chatId, p => { p.state = 'approved'; });
1154    onPlan(chatId, 'approved', planView(plans.get(chatId)));
1155    return runTurn({ ...options, goal: { action: 'create', objective: plan.title }, planRun: { planId: plan.id, once: options.once === true } });
1156  }
1157
1158  /** A paused plan becomes open again (a step that did not finish is tried again in a fresh session). */
1159  function reopenPlan(chatId) { const p = plans.get(chatId); if (p && p.state === 'paused') { plans.update(chatId, x => { x.state = 'approved'; }); onPlan(chatId, 'approved', planView(plans.get(chatId))); } }
1160
1161  /** Give up on one step with a plain note (a check that cannot be done here) so the rest of the plan can go on. */
1162  function skipStep(chatId, index, note) { plans.update(chatId, p => { const st = p.steps[index]; if (st) { st.state = 'skipped'; st.summary = String(note ?? 'Skipped.').slice(0, 140); } if (p.state === 'paused') p.state = 'approved'; }); onPlan(chatId, 'step', planView(plans.get(chatId))); }
1163
1164  /** Forget the chat's agent session (not its plan): the next turn starts a fresh one in the same folder. */
1165  function resetSession(chatId) {
1166    if (chats.get(chatId)?.turn || chats.get(chatId)?.starting) throw new AgentUnavailable('This chat is still working.', 'turn-active');
1167    delete sessionMap[chatId]; persist();
1168  }
1169
1170  // -- the agent's own questions ------------------------------------------------------------------------------
1171
1172  /**
1173   * The person's answer to a question the agent asked (#4244), or a skip. The answer is checked against the questions that were asked, then sent
1174   * to the Harness as the result of the waiting `user-questions/request`; a skip declares the question unanswerable, as before, and the model
1175   * carries on.
1176   */
1177  async function answerQuestion({ chatId, callId, answers, skip = false }) {
1178    const sessionId = sessionMap[chatId]?.sessionId;
1179    const key = `${sessionId}:${callId}`;
1180    const entry = questions.get(key);
1181    if (!entry || !rt?.hp.running) throw new AgentUnavailable('That question was already answered, or the assistant has gone on.', 'question-gone');
1182    const outcome = skip ? 'next' : buildAnswer(entry.items, answers);
1183    await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome });
1184    questions.delete(key);
1185    return { ok: true, skipped: !!skip };
1186  }
1187
1188  // -- a message for a helper ---------------------------------------------------------------------------------
1189
1190  /**
1191   * The person's own words for one helper (#4749), through the Harness's `subagents/prompt`: it delivers one browser-authored message to a
1192   * continuable child through its live parent. "steer" reaches a working helper at its next step; "queue" gives a helper that has finished
1193   * (or is between steps) a new turn. The Harness refuses a helper that cannot take messages (a one-shot one) and a parent that is not live;
1194   * either comes back as a plain sentence.
1195   */
1196  async function messageHelper({ chatId, helperId, text, delivery = 'queue' }) {
1197    const clean = String(text ?? '').trim().slice(0, 8000);
1198    if (!clean) throw new AgentUnavailable('Type a few words for the helper.', 'helper-empty');
1199    if (!/^[\w.:@-]{1,160}$/.test(String(helperId ?? ''))) throw new AgentUnavailable('That helper is not known.', 'helper-unknown');
1200    const parent = sessionMap[chatId]?.sessionId;
1201    if (!parent || !rt?.hp.running) throw new AgentUnavailable('The assistant is not running in this chat, so it cannot pass a message on. Send a message in the chat first.', 'helper-idle');
1202    try {
1203      const receipt = await rt.gw.rpc('subagents/prompt', { request: { requestId: `helper-${randomUUID()}`, parentSessionId: parent, childSessionId: String(helperId), mode: 'continuable', delivery: delivery === 'steer' ? 'steer' : 'queue', content: [{ type: 'text', text: clean }] } });
1204      return { ok: true, messageId: receipt?.messageId ?? null, delivery: delivery === 'steer' ? 'steer' : 'queue' };
1205    } catch (e) {
1206      log(`agent · message for a helper refused: ${String(e?.message ?? e).slice(0, 200)}`);
1207      throw new AgentUnavailable(/continuable|one-shot|not.*(found|live|open)|unavailable|closed|ended/i.test(String(e?.message ?? '')) ? 'This helper cannot take a message any more. Ask the assistant in the chat to start a new one.' : 'The message could not be delivered right now. Try again in a moment.', 'helper-refused');
1208    }
1209  }
1210
1211  // -- messages typed while a goal runs ----------------------------------------------------------------------
1212
1213  /** Queue a message for the running goal. It is delivered between steps, or handed back to the page when the goal ends or pauses. */
1214  function queueMessage({ chatId, text }) {
1215    const turn = chats.get(chatId)?.turn;
1216    if (!turn || !turn.goalRun || turn.stopping || turn.finished) throw new AgentUnavailable('No goal is running in this chat, so there is nothing to queue behind. Send the message as usual.', 'queue-idle');
1217    const clean = String(text ?? '').trim().slice(0, 8000);
1218    if (!clean) throw new AgentUnavailable('Type a few words to queue.', 'queue-empty');
1219    const list = queues.get(chatId) ?? [];
1220    if (list.length >= 20) throw new AgentUnavailable('Twenty messages are already waiting. Wait for some to be delivered.', 'queue-full');
1221    const item = { id: randomUUID(), text: clean, at: new Date().toISOString(), deliverAt: turn.plan ? 'step' : 'end' };
1222    list.push(item); queues.set(chatId, list);
1223    const message = { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt };
1224    onQueue(chatId, queueView(chatId));
1225    turn.announceQueue?.({ type: 'queued-message', state: 'queued', message, queue: queueView(chatId) });
1226    return { message, queue: queueView(chatId) };
1227  }
1228
1229  /** Take a queued message back (the x on it). A message already being delivered cannot be taken back. */
1230  function cancelQueued({ chatId, id }) {
1231    const list = queues.get(chatId) ?? [];
1232    const at = list.findIndex(m => m.id === id);
1233    if (at < 0) throw new AgentUnavailable('That message was already sent or removed.', 'queue-gone');
1234    const [item] = list.splice(at, 1);
1235    if (!list.length) queues.delete(chatId);
1236    onQueue(chatId, queueView(chatId));
1237    chats.get(chatId)?.turn?.announceQueue?.({ type: 'queued-message', state: 'cancelled', message: { id: item.id, text: item.text, at: item.at, deliverAt: item.deliverAt }, queue: queueView(chatId) });
1238    return { queue: queueView(chatId) };
1239  }
1240
1241  /** Messages waiting for a chat, and (after a goal ended while the page was away) the ones it should now send. */
1242  function takeQueue(chatId, { release = false } = {}) {
1243    const turn = chats.get(chatId)?.turn;
1244    const list = queueView(chatId);
1245    if (release && !turn && list.length) { queues.delete(chatId); onQueue(chatId, []); return { queue: [], released: list.map(({ id, text }) => ({ id, text })) }; }
1246    return { queue: list, released: [] };
1247  }
1248
1249  /**
1250   * The person changed the chat's mode while a turn (a goal and its helpers included) is running. The new preset
1251   * is put on the session at once, the running turn's own bookkeeping follows, and questions already waiting are
1252   * settled the way the new mode would have settled them: Bypass allows them, Plan rejects them.
1253   */
1254  async function setMode(chatId, mode) {
1255    const want = modeOf(mode);
1256    const c = chats.get(chatId);
1257    const sessionId = sessionMap[chatId]?.sessionId;
1258    if (!rt || !sessionId) return { applied: false, mode: want, reason: 'no session yet' };
1259    if (c?.turn && c.turn.mode === want) return { applied: true, mode: want, settled: 0 };
1260    await applyMode(rt, sessionId, want);
1261    let settled = 0;
1262    if (c?.turn) {
1263      c.turn.mode = want;
1264      c.turn.projector.policy = MODE_PRESETS[want].approval;
1265      if (want !== 'manual') {
1266        const helpers = c.turn.children;
1267        for (const [key, entry] of [...pending.entries()]) {
1268          if (entry.sessionId !== sessionId && !helpers?.has(entry.sessionId)) continue;
1269          pending.delete(key);
1270          try { await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: want === 'bypass' ? 'allowed-once' : 'rejected' }); settled++; } catch { /* already answered */ }
1271        }
1272      }
1273    }
1274    return { applied: true, mode: want, settled };
1275  }
1276
1277  /** Answer one pending approval. `decision` is `approve` or `deny`. */
1278  async function approve({ chatId, callId, decision }) {
1279    const sessionId = sessionMap[chatId]?.sessionId;
1280    // A helper agent's question carries the helper's session id in front of its call id. Only a helper that belongs to
1281    // THIS chat's run can be answered from this chat.
1282    const [maybeChild] = String(callId).split(':');
1283    const ownHelper = callId.includes(':') && chats.get(chatId)?.turn?.children.has(maybeChild);
1284    const key = ownHelper ? callId : `${sessionId}:${callId}`;
1285    // The durable `approval/asked` (which makes the card say "needs approval") and the waterfall frame
1286    // (which makes it answerable) travel on different streams; a fast click can beat the second one.
1287    let entry = sessionId ? pending.get(key) : null;
1288    for (let i = 0; !entry && sessionId && i < 40; i++) {
1289      await new Promise(r => setTimeout(r, 50));
1290      entry = pending.get(key);
1291    }
1292    if (!entry) throw new AgentUnavailable('That question is no longer waiting for an answer.', 'approval-gone');
1293    if (!rt?.hp.running) throw new AgentUnavailable('That question expired because the coding assistant restarted. Ask again.', 'approval-gone');
1294    pending.delete(key);
1295    try {
1296      await rt.gw.answerEvent({ clientId: entry.clientId ?? rt.clientId, eventId: entry.eventId, outcome: decision === 'approve' ? 'allowed-once' : 'rejected' });
1297    } catch (e) {
1298      throw new AgentUnavailable('Your answer could not be delivered. Ask again.', 'approval-gone', e.message);
1299    }
1300    return { ok: true };
1301  }
1302
1303  /**
1304   * Stop one chat's turn. Resolves only once the turn has ended (or the wait times out), because the
1305   * Harness acknowledges a cancel as admitted, not as done.
1306   */
1307  /** What the chat holds now and the model's window, as the context plugin measures them (null when it cannot be read). */
1308  async function contextOf(runtime, sessionId) {
1309    try {
1310      const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/strata-context', submittedAttachments: [] });
1311      if (r?.result?.kind !== 'success') return null;
1312      const v = JSON.parse(String(r.result.text));
1313      return Number.isFinite(v.tokens) ? { tokens: Math.round(v.tokens), window: Number(v.window) > 0 ? Math.round(v.window) : 0 } : null;
1314    } catch { return null; }
1315  }
1316
1317  /** The decision of context-fit.mjs for the message about to be sent, or null when the model server cannot count it. */
1318  async function fitCheck({ runtime, route, sessionId, fresh, history, message }) {
1319    const inst = localInstances().find(i => i.id === route.instanceId);
1320    if (!inst || !(route.contextWindow > 0)) return null;
1321    const carried = fresh && history.length ? withEarlierConversation(history, message) : message;
1322    if (carried.length < COUNT_ABOVE_CHARS) return null;
1323    const count = text => countTokens({ baseUrl: inst.baseUrl, key: inst.key, model: inst.modelId, text });
1324    let tokens = await count(carried);
1325    if (tokens == null) return null;
1326    const now = fresh ? null : await contextOf(runtime, sessionId);
1327    const window = now?.window || route.contextWindow;
1328    const pressure = now?.tokens ?? 0;
1329    // Where the Harness starts summarising by itself on this window (profile.mjs: the reply keeps its room, then the headroom).
1330    const reply = localOutputBudget(window);
1331    const threshold = Math.floor(Math.min(window * 0.8, window - reply - compactionHeadroom(window, reply)));
1332    let verdict = decideFit({ window, pressure, messageTokens: tokens, threshold });
1333    // The earlier conversation carried into a fresh session is what pushed it over: send the message alone instead.
1334    if (verdict.action === 'too-large' && carried !== message) {
1335      const alone = await count(message);
1336      if (alone != null) { tokens = alone; verdict = decideFit({ window, pressure, messageTokens: alone, threshold }); }
1337    }
1338    return { ...verdict, tokens, window, pressure };
1339  }
1340
1341  /**
1342   * Summarise the older part of a chat with the Harness's /compact and say what happened. Never throws.
1343   * ok:true carries the figures before and after; ok:false says why (nothing to summarise, busy, failed).
1344   */
1345  async function compactChat(runtime, sessionId) {
1346    const before = await contextOf(runtime, sessionId);
1347    let result;
1348    try { result = (await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] }))?.result; }
1349    catch (e) { return { ok: false, reason: /not.found|no such/i.test(String(e.message)) ? 'nothing' : 'failed', before, text: String(e.message ?? e) }; }
1350    const text = String(result?.text ?? '');
1351    log('agent · compact: ' + (result?.kind ?? 'none') + ' ' + text.slice(0, 140));
1352    if (result?.kind === 'success' && /^Compacted/i.test(text)) return { ok: true, before, after: await contextOf(runtime, sessionId) };
1353    if (result?.kind === 'success') return { ok: false, reason: 'nothing', before, text };
1354    if (/active compaction|not idle/i.test(text)) return { ok: false, reason: 'busy', before, text };
1355    // The Harness cannot make a summary smaller than what is left when the chat holds little beyond its first prompt: that is nothing to summarise, not a failure.
1356    const little = before && before.window > 0 && before.tokens - BASE_TOKENS < before.window * 0.25;
1357    return { ok: false, reason: little && /useful summary|not smaller/i.test(text) ? 'nothing' : 'failed', before, text };
1358  }
1359
1360  /** The line in the chat that explains why the context meter fell: how full it was and how full it is. */
1361  function summarizedNote(before, after, window) {
1362    const w = after?.window || before?.window || window || 0;
1363    const pct = v => Math.max(0, Math.min(100, Math.round(100 * v.tokens / w)));
1364    const known = w > 0 && before && after;
1365    const template = known ? FIT_TEXT.summarized : FIT_TEXT.summarizedShort;
1366    const values = known ? [pct(before), pct(after)] : [];
1367    return { type: 'delta', own: true, text: '\n\n' + fill(template, values), key: template, values, noteReason: 'compacted' };
1368  }
1369
1370  /** "/compact": summarise the older messages of this chat now, and say in plain words what happened. */
1371  async function compactCommand(options) {
1372    const { chatId, choice, signal } = options;
1373    const c = chat(chatId);
1374    const say = (template, values = []) => sayKey(options, template, values);
1375    if (c.turn || c.starting) return say(FIT_TEXT.compactBusy);
1376    const known = sessionMap[chatId]?.sessionId;
1377    if (!known) return say(FIT_TEXT.noChatYet);
1378    let runtime;
1379    try { ({ rt: runtime } = await ensureRuntime(choice, signal)); } catch { return say(FIT_TEXT.compactFailed); }
1380    const done = await compactChat(runtime, known);
1381    if (done.ok) {
1382      const note = summarizedNote(done.before, done.after, 0);
1383      return say(note.key, note.values);
1384    }
1385    if (done.reason === 'busy') return say(FIT_TEXT.compactBusy);
1386    if (done.reason === 'nothing') {
1387      const w = done.before?.window || 0;
1388      const pct = w > 0 && done.before ? Math.round(100 * done.before.tokens / w) : 0;
1389      return say(pct >= 60 ? FIT_TEXT.nothingFull : FIT_TEXT.nothingToSummarize, pct >= 60 ? [pct] : []);
1390    }
1391    return say(FIT_TEXT.compactFailed);
1392  }
1393
1394  /** 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. */
1395  async function compactSession(runtime, sessionId) {
1396    try {
1397      const r = await runtime.gw.rpc('commands/execute', { agentId: sessionId, line: '/compact', submittedAttachments: [] });
1398      log(`agent · compact after a stopped turn: ${r?.result?.kind ?? 'done'} ${String(r?.result?.text ?? '').slice(0, 120)}`);
1399    } catch (e) { log(`agent · compact after a stopped turn failed: ${e.message}`); }
1400  }
1401
1402  async function stop(chatId, { waitMs = 20_000 } = {}) {
1403    const c = chats.get(chatId);
1404    const turn = c?.turn;
1405    if (!turn && c?.starting) { c.cancelStart = true; return { stopped: true, ended: 'cancelled-before-start', ms: 0 }; }
1406    if (!turn || !rt) return { stopped: false, reason: 'no active turn' };
1407    const t0 = Date.now();
1408    if (!turn.prompted) {
1409      // The Harness has not been given the prompt yet, so there is nothing to cancel there.
1410      turn.stopBeforePrompt = true;
1411      const early = await Promise.race([turn.ended.promise, new Promise(r => setTimeout(() => r(null), 100))]);
1412      if (early) return { stopped: true, ended: early.reason?.kind ?? 'aborted', ms: Date.now() - t0 };
1413    }
1414    turn.stopping = true;
1415    await pauseGoal(rt, turn.sessionId, chatId);
1416    // Helpers first: a helper still working would otherwise report back and wake the parent again.
1417    await Promise.allSettled([...turn.children.values()].filter(h => !h.done).map(h => rt.gw.rpc('subagents/interruptByParent', { childSessionId: h.id, parentSessionId: turn.sessionId, mode: 'continuable' })));
1418    await rt.gw.rpc('session/cancel', { request: { sessionId: turn.sessionId } }).catch(e => { if (turn.parentOpen) throw e; });
1419    // Nothing is running in the parent (it was waiting for its helpers): the run ends once they are all down.
1420    if (!turn.parentOpen) { clearTimeout(turn.settleTimer); turn.settleTimer = after(300, () => { if (!turn.finished && !turn.parentOpen && [...turn.children.values()].every(h => h.done)) turn.finish(null); }); }
1421    let timer; const result = await Promise.race([turn.ended.promise, new Promise(r => { timer = after(waitMs, () => r(null)); })]);
1422    clearTimeout(timer);
1423    if (!result) return { stopped: false, pending: true, reason: 'the turn is still stopping' };
1424    return { stopped: true, ended: result.reason?.kind ?? 'unknown', ms: Date.now() - t0 };
1425  }
1426
1427  /** The turn running for a chat now, for a page that has just loaded; null when none. */
1428  function turnOf(chatId) {
1429    const t = chats.get(chatId)?.turn;
1430    if (!t || t.finished) return null;
1431    return { chatId, sessionId: t.sessionId, requestId: t.requestId, mode: t.mode, stopping: !!t.stopping, pending: pendingFor(chatId) };
1432  }
1433  /** Every chat with a turn running. */
1434  function runningTurns() { return [...chats.keys()].map(turnOf).filter(Boolean); }
1435  /**
1436   * Take a turn over from a new page. A running turn: the catch-up, then the live frames until it ends or the page leaves again. A turn that
1437   * ended while no page was there (`requestId` names it): its text, tool cards and closing frame once. null when there is nothing to take over.
1438   */
1439  function attach({ chatId, requestId = null, onFrame, signal }) {
1440    const c = chats.get(chatId);
1441    const turn = c?.turn;
1442    if (turn && !turn.finished && typeof turn.reattach === 'function') {
1443      if (requestId && turn.requestId !== requestId) return null;
1444      turn.reattach({ onFrame, signal });
1445      return { ended: turn.ended.promise.then(() => undefined), live: true };
1446    }
1447    const last = c?.last;
1448    if (!last || !requestId || last.requestId !== requestId) return null;
1449    onFrame({ type: 'start', model: last.model, contextMax: last.contextMax, demo: false, remoteModel: last.remoteModel, agent: true, mode: last.mode, sessionId: last.sessionId, requestId: last.requestId, skills: [], resumed: true });
1450    onFrame({ type: 'resync', content: last.content, reasoning: last.reasoning });
1451    for (const card of last.cards) onFrame({ type: 'agent-tool', tool: card });
1452    if (last.terminal) onFrame(last.terminal);
1453    return { ended: Promise.resolve(), live: false };
1454  }
1455  function pendingFor(chatId) {
1456    const sessionId = sessionMap[chatId]?.sessionId;
1457    const helpers = chats.get(chatId)?.turn?.children;
1458    return [...pending.values()].filter(p => p.sessionId === sessionId || helpers?.has(p.sessionId))
1459      .map(p => (p.sessionId === sessionId ? p : { ...p, callId: `${p.sessionId}:${p.callId}` })).map(({ callId, tool, reason, at }) => ({ callId, tool, reason, at }));
1460  }
1461
1462  /** Every chat that has an approval waiting, for the task board: the chat, its working folder and what is waiting (same items as pendingFor). */
1463  function pendingAll() {
1464    if (!pending.size) return [];
1465    return Object.keys(sessionMap).map(chatId => ({ chatId, folder: sessionMap[chatId]?.cwd ?? null, pending: pendingFor(chatId) })).filter(c => c.pending.length);
1466  }
1467
1468  async function close() {
1469    const r = rt; rt = null;
1470    if (r) { r.events?.close(); r.gw.close(); await r.hp.stop(); }
1471  }
1472
1473  /** Let go of a chat's Harness session mapping (a task starts every run in a session of its own). */
1474  function forget(chatId) { if (chats.get(chatId)?.turn) return; delete sessionMap[chatId]; chats.delete(chatId); persist(); }
1475
1476  return { compactCommand, messageHelper, answerQuestion, goalState, goalControl, harnessDir, status, turnOf, runningTurns, attach, runTurn, goalCommand, planCommand, researchCommand, llmTarget, setPlanBriefing, resetSession, reopenPlan, skipStep, planGoal, planControl, planState, queueMessage, cancelQueued, takeQueue, forget, approve, setMode, stop, pendingFor, pendingAll, close, sessionOf: chatId => sessionMap[chatId]?.sessionId ?? null, workingFolder: chatId => sessionMap[chatId]?.cwd ?? null, isRunning: chatId => !!chats.get(chatId)?.turn, _debug: () => ({ rt, sessionMap }) };
1477}
1478
1479/** A goal that stopped by itself, in words. */
1480export function plainBlocker(reason) {
1481  if (!reason) return 'it could not go on.';
1482  if (reason.code === 'round-limit') return 'it worked for the most steps it was allowed. Type /goal clear, then start a new goal to go on.';
1483  return String(reason.message ?? 'it could not go on.');
1484}
1485
1486/** What a goal run says when it ends. */
1487export function goalEnding(view) {
1488  if (view.phase === 'complete') return '\n\n*The goal is complete.*';
1489  if (view.phase === 'blocked') return `\n\n*The goal stopped: ${plainBlocker(view.blockedReason)}*`;
1490  if (view.phase === 'paused') return '\n\n*The goal is paused. Type /goal resume to go on.*';
1491  return '';
1492}
1493
1494/** A goal request the Harness refused, as a sentence. */
1495export function plainGoalError(e) {
1496  const message = String(e?.message ?? e);
1497  if (/already|unfinished|current goal/i.test(message)) return 'This chat already has a goal that is not finished. Type /goal edit to change it, /goal clear to remove it, or /goal to see it.';
1498  if (/GOAL_NONE|no goal/i.test(message) || e?.code === 'goal-none') return 'There is no goal to continue. Start one with /goal followed by what you want done.';
1499  if (/objective/i.test(message)) return 'A goal needs a few words about what you want done, for example: /goal make every test pass.';
1500  return 'The goal could not be changed right now. Try again in a moment.';
1501}
1502
1503/** The Harness session of a chat that existed before the agent did knows nothing; carry a bounded summary. */
1504export function withEarlierConversation(history, message) {
1505  const rows = history.filter(m => (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim()).slice(-12);
1506  if (!rows.length) return message;
1507  const text = rows.map(m => `${m.role}: ${m.content.length > 1500 ? `${m.content.slice(0, 1499)}…` : m.content}`).join('\n');
1508  return `Earlier in this conversation, before you were given tools:\n${text}\n\nCurrent message:\n${message}`;
1509}