@cairnvibe/sdk 0.2.13 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,13 +29,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
29
29
  return (mod && mod.__esModule) ? mod : { "default": mod };
30
30
  };
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.formatRememberedFacts = exports.seedHistoryFromMemory = void 0;
32
33
  exports.createRealtimeServer = createRealtimeServer;
33
34
  exports.handleDeepgramMessage = handleDeepgramMessage;
34
35
  const node_http_1 = __importDefault(require("node:http"));
35
36
  const ws_1 = require("ws");
36
37
  const core_1 = require("@cairnvibe/core");
38
+ const agent_loop_1 = require("./agent-loop");
37
39
  const server_1 = require("./server");
38
40
  const tts_stream_1 = require("./tts-stream");
41
+ const memory_sqlite_1 = require("./memory-sqlite");
42
+ Object.defineProperty(exports, "formatRememberedFacts", { enumerable: true, get: function () { return memory_sqlite_1.formatRememberedFacts; } });
43
+ Object.defineProperty(exports, "seedHistoryFromMemory", { enumerable: true, get: function () { return memory_sqlite_1.seedHistoryFromMemory; } });
39
44
  const DEEPGRAM_LIVE_URL = "wss://api.deepgram.com/v1/listen";
40
45
  const DEFAULT_STT_MODEL = "nova-2";
41
46
  const DEFAULT_TTS_VOICE = "aura-2-thalia-en";
@@ -44,15 +49,67 @@ const DEFAULT_TTS_VOICE = "aura-2-thalia-en";
44
49
  // something within about a second instead of dead air while the real
45
50
  // multi-step work runs. A short rotating set, not one fixed line, so it
46
51
  // doesn't read as a canned bot phrase on every multi-step question.
47
- const ACK_PHRASES = ["Let me check that for you.", "One moment, let me look into that.", "Give me a second to check.", "Let me take a look."];
52
+ //
53
+ // Phase 2 step 3 — rewritten from the original set (kept below in spirit
54
+ // but not verbatim: "Let me check that for you." / "One moment, let me
55
+ // look into that." / "Give me a second to check." / "Let me take a
56
+ // look.") for two real, testable reasons, not a vibe change: (1) the
57
+ // plan's own bar is "feels like a person coordinating a team ('give me
58
+ // a sec, sorting that out'), never generic-corporate" — the original
59
+ // set's formal, service-desk phrasing ("One moment, let me look into
60
+ // that") is closer to a phone-tree script than a coworker; (2) "kept
61
+ // short on purpose (a long ack costs real latency budget)" — the
62
+ // original set averaged 6 words; this one averages under 4, a real,
63
+ // measurable reduction in synthesis time before the ack is even
64
+ // audible, on top of sounding more like a person. Graded on this now,
65
+ // not eyeballed — see judge.ts's new `persona` dimension and
66
+ // realtime-server.ts's own "ack" message, which exposes the actual
67
+ // spoken text to packages/evals' trace capture for the first time.
68
+ const ACK_PHRASES = ["Give me a sec.", "One sec, checking.", "Hang on, let me look.", "On it, one sec.", "Just a sec here.", "Let me check real quick."];
48
69
  // Not constrained by any telephony 8kHz requirement — this is just "what
49
70
  // quality does Deepgram render at" for browser playback, and the Web Audio
50
71
  // API resamples an AudioBuffer at any declared rate transparently.
51
72
  const TTS_SAMPLE_RATE = 24000;
73
+ /**
74
+ * Phase 5 step 2 — explicit fact-remembering (Track B's own "remember is
75
+ * an explicit act, never automatic" pattern — step 1 built the automatic
76
+ * turn-recording half; this is the deliberate half). Modeled as a
77
+ * SYNTHETIC WebMCP tool the model can call_tool, not a new verb — reuses
78
+ * the existing call_tool grammar/validation the model already knows
79
+ * ("a tool name from this turn's webMcpTools list") instead of inventing
80
+ * a new one. Handled entirely SERVER-SIDE (see executeStep below) —
81
+ * the client never learns this step happened at all (see onStep below
82
+ * for why that's not just an optimization: it's what keeps this safe).
83
+ */
84
+ const REMEMBER_FACT_TOOL_NAME = "remember_fact";
85
+ const REMEMBER_FACT_TOOL = {
86
+ name: REMEMBER_FACT_TOOL_NAME,
87
+ description: "Remember something worth recalling in a FUTURE conversation with this same user — a stated preference, a known pitfall, anything that would help next time. Not for facts only relevant to answering right now. Call this AT MOST ONCE per turn, for one real fact. Once it returns, the fact is already saved — immediately give your final spoken answer (e.g. explain) confirming that to the user; do not call this again in the same turn.",
88
+ inputSchema: {
89
+ type: "object",
90
+ properties: {
91
+ key: { type: "string", description: "A short, stable name for this fact, e.g. \"preferredUnits\" or \"flakySelectorNote\"." },
92
+ value: { type: "string", description: "The real fact to remember, in plain language." },
93
+ },
94
+ required: ["key", "value"],
95
+ },
96
+ };
97
+ async function handleRememberFactTool(memory, scopeId, args) {
98
+ const key = typeof args?.key === "string" ? args.key.trim() : "";
99
+ const value = typeof args?.value === "string" ? args.value.trim() : "";
100
+ if (!key || !value)
101
+ return "Could not remember that — a key and a value are both required.";
102
+ memory.rememberFact(scopeId, key, value);
103
+ return `Remembered: ${key} = ${value}`;
104
+ }
52
105
  function createRealtimeServer(options) {
53
106
  const registeredActions = options.registeredActions ?? [];
54
107
  const capability = options.capability ?? "act";
55
108
  const llm = (0, server_1.createVerbLLM)(options);
109
+ // Phase 3 steps 2-3 — real, separately-configured Planner/Critic LLMs.
110
+ // See finalizeTurn's own doc comment for how they're actually used.
111
+ const planLLM = (0, server_1.createPlanLLM)(options);
112
+ const criticLLM = (0, server_1.createCriticLLM)(options);
56
113
  // "text" is optional on highlight/open/navigate/do in the base prompt —
57
114
  // fine for the typed/HTTP path, which always has a visible answer area,
58
115
  // but silence reads as broken in a live voice conversation (the client
@@ -60,7 +117,8 @@ function createRealtimeServer(options) {
60
117
  // instruction asks for a confirmation grounded in what was actually
61
118
  // done, not filler — generic phrasing here is what made replies feel
62
119
  // "unrelated" to the question that was just asked.
63
- const systemPrompt = (0, server_1.buildSystemPrompt)(options.manifest, registeredActions, options.persona) +
120
+ const actionDescriptions = options.actionDescriptions ?? {};
121
+ const systemPrompt = (0, server_1.buildSystemPrompt)(options.manifest, registeredActions, options.persona, actionDescriptions) +
64
122
  `\n\nYou are in a live voice conversation right now — the user is speaking out loud and may not be looking at the screen. For highlight/open/navigate/do, include a short spoken "text" that names the specific thing you're pointing at or the specific place you're sending them (e.g. "Highlighting the New Invoice button" or "Taking you to Invoices"), not a generic filler phrase — so they hear a confirmation that's actually about their question.`;
65
123
  const sttModel = options.sttModel ?? process.env.DEEPGRAM_MODEL ?? DEFAULT_STT_MODEL;
66
124
  const ttsVoice = options.ttsVoice ?? process.env.DEEPGRAM_VOICE ?? DEFAULT_TTS_VOICE;
@@ -70,17 +128,50 @@ function createRealtimeServer(options) {
70
128
  res.end("cairn realtime relay\n");
71
129
  });
72
130
  const wss = new ws_1.WebSocketServer({ server: httpServer });
131
+ // Real, server-side visibility into how many browser tabs/connections
132
+ // are actually live at once — added specifically to answer, with real
133
+ // data instead of a guess, a live-raised concern: could a page reload
134
+ // (or several in quick succession) leave more than one realtime
135
+ // connection open at the same time, each independently running its own
136
+ // Deepgram STT/TTS and LLM calls for the same user? Every connection
137
+ // gets a short id, logged on open and close, alongside a live count —
138
+ // if that count is ever more than 1 during normal single-tab use, THAT
139
+ // is the real, direct evidence of a genuine duplicate-connection bug;
140
+ // if it always reads 1, duplication server-side is ruled out with real
141
+ // proof, not assumed away.
142
+ let nextConnectionId = 1;
143
+ let activeConnections = 0;
73
144
  wss.on("connection", (client) => {
74
- handleConnection(client, { deepgramApiKey, sttModel, ttsVoice, llm, systemPrompt, manifest: options.manifest, registeredActions, capability }).catch((err) => {
75
- console.error("[cairn realtime] connection error:", err);
145
+ const connectionId = nextConnectionId++;
146
+ activeConnections++;
147
+ console.log(`[cairn realtime] connection ${connectionId} opened — ${activeConnections} active`);
148
+ client.on("close", () => {
149
+ activeConnections--;
150
+ console.log(`[cairn realtime] connection ${connectionId} closed — ${activeConnections} active`);
151
+ });
152
+ handleConnection(client, {
153
+ deepgramApiKey,
154
+ sttModel,
155
+ ttsVoice,
156
+ llm,
157
+ planLLM,
158
+ criticLLM,
159
+ systemPrompt,
160
+ manifest: options.manifest,
161
+ registeredActions,
162
+ actionDescriptions,
163
+ capability,
164
+ memory: options.memory,
165
+ skills: options.skills,
166
+ skillsScopeId: options.skillsScopeId,
167
+ }).catch((err) => {
168
+ console.error(`[cairn realtime] connection ${connectionId} error:`, err);
76
169
  safeSend(client, { type: "error", message: "internal error" });
77
170
  client.close();
78
171
  });
79
172
  });
80
173
  return httpServer;
81
174
  }
82
- const MAX_HISTORY_TURNS = 8; // 4 exchanges — enough for "the first one"/"do that instead" without growing the prompt unbounded over a long call
83
- const MAX_LOOP_ITERATIONS = 6; // a hard cap on one turn's agent-loop steps, not a target — see finalizeTurn
84
175
  async function handleConnection(client, deps) {
85
176
  // liveElements/webMcpTools refresh on every "context" resend (the client
86
177
  // sends one on route changes and each time it's about to start listening
@@ -97,6 +188,22 @@ async function handleConnection(client, deps) {
97
188
  // one WebSocket per call — so this is accumulated here directly rather
98
189
  // than round-tripped through the client.
99
190
  const history = [];
191
+ // Phase 5 — real cross-session memory. `scopeId` is set from the FIRST
192
+ // "context" message that carries one (see the "context" handler below)
193
+ // and never changed again for the life of this connection — a real,
194
+ // deliberate v1 simplification (no attempt to handle a scopeId that
195
+ // legitimately changes mid-connection, e.g. a mid-session login) rather
196
+ // than guessed-at complexity. `historySeededFromMemory` guards the
197
+ // ONE-TIME load of this scope's prior turns into `history` — a later
198
+ // "context" resend (route changes send fresh ones routinely) must never
199
+ // re-seed and duplicate them.
200
+ let scopeId = null;
201
+ let historySeededFromMemory = false;
202
+ function recordMemoryTurn(role, text) {
203
+ if (!deps.memory || !scopeId)
204
+ return;
205
+ deps.memory.recordTurn(scopeId, role, text);
206
+ }
100
207
  // Resolves the agent loop's in-flight waitForToolResult() call once the
101
208
  // client reports back what a click/fill/read/call_tool step actually
102
209
  // did — same "a mutable pending-callback slot, resolved when the right
@@ -104,14 +211,70 @@ async function handleConnection(client, deps) {
104
211
  let pendingToolResultResolve = null;
105
212
  const dgUrl = `${DEEPGRAM_LIVE_URL}?model=${encodeURIComponent(deps.sttModel)}` +
106
213
  `&encoding=linear16&sample_rate=16000&channels=1&interim_results=true&endpointing=300&utterance_end_ms=1000`;
107
- const dg = new ws_1.WebSocket(dgUrl, { headers: { Authorization: `Token ${deps.deepgramApiKey}` } });
214
+ // Real, live-reported bug this closes: "status says Listening but nothing
215
+ // happens" — the client keeps looking and sounding fine (mic still
216
+ // capturing, WS still open, no error ever shown), because the REAL
217
+ // failure is silent and one layer deeper: Deepgram's own STT connection
218
+ // can close mid-session (an idle timeout, a network blip, Deepgram's own
219
+ // connection lifetime limit) and this code never noticed — there was no
220
+ // `dg.on("close", ...)` handler at all, `dgOpen` never got reset to
221
+ // false, and every subsequent mic frame kept calling `dg.send(buf)` on an
222
+ // already-CLOSED socket with no callback to catch the failure. The client
223
+ // never heard about any of this, because nothing here ever sent it an
224
+ // "error" message — from the outside it looks exactly like "listening,
225
+ // but the mic just isn't picking anything up."
226
+ //
227
+ // Fixed by making the STT connection self-healing instead of a single
228
+ // fire-and-forget WebSocket: `dg` is now reassignable, and a real close
229
+ // triggers a bounded number of automatic reconnects (fresh handshake,
230
+ // same handlers) before finally giving up and telling the client — so a
231
+ // transient Deepgram-side drop recovers on its own instead of silently
232
+ // bricking the rest of the call.
233
+ let dg;
108
234
  let dgOpen = false;
235
+ let dgReconnectAttempts = 0;
236
+ const MAX_DG_RECONNECT_ATTEMPTS = 3;
109
237
  const pendingAudio = [];
110
- dg.on("open", () => {
111
- dgOpen = true;
112
- for (const chunk of pendingAudio.splice(0))
113
- dg.send(chunk);
114
- });
238
+ // Accumulates Deepgram "Results" transcript segments across one utterance
239
+ // see handleDeepgramMessage for why this can't just react to every
240
+ // is_final. Declared before connectDeepgramStt so its own "message"
241
+ // handler closes over an already-initialized binding, not just a
242
+ // same-scope one that happens to be safe only because WS events are
243
+ // always async.
244
+ const turnState = { buffer: "" };
245
+ function connectDeepgramStt() {
246
+ const socket = new ws_1.WebSocket(dgUrl, { headers: { Authorization: `Token ${deps.deepgramApiKey}` } });
247
+ dg = socket;
248
+ socket.on("open", () => {
249
+ dgOpen = true;
250
+ dgReconnectAttempts = 0;
251
+ for (const chunk of pendingAudio.splice(0))
252
+ socket.send(chunk);
253
+ });
254
+ socket.on("message", (data) => {
255
+ void handleDeepgramMessage(data.toString(), client, deps, () => context, speakStreamed, history, turnState, () => generation, waitForToolResult, recordMemoryTurn, () => scopeId, () => {
256
+ generation++;
257
+ });
258
+ });
259
+ socket.on("error", (err) => {
260
+ console.error("[cairn realtime] Deepgram STT connection error:", err);
261
+ });
262
+ socket.on("close", (code, reason) => {
263
+ dgOpen = false;
264
+ console.log(`[cairn realtime] Deepgram STT connection closed (code ${code}${reason ? `, ${reason}` : ""})`);
265
+ if (client.readyState !== ws_1.WebSocket.OPEN)
266
+ return; // the whole call already ended — nothing to reconnect for
267
+ if (dgReconnectAttempts >= MAX_DG_RECONNECT_ATTEMPTS) {
268
+ console.error(`[cairn realtime] Deepgram STT gave up reconnecting after ${MAX_DG_RECONNECT_ATTEMPTS} attempts`);
269
+ safeSend(client, { type: "error", message: "Speech recognition connection was lost and couldn't be restored — try starting the call again." });
270
+ return;
271
+ }
272
+ dgReconnectAttempts++;
273
+ console.log(`[cairn realtime] reconnecting to Deepgram STT (attempt ${dgReconnectAttempts}/${MAX_DG_RECONNECT_ATTEMPTS})`);
274
+ connectDeepgramStt();
275
+ });
276
+ }
277
+ connectDeepgramStt();
115
278
  // ONE Speak connection reused for every turn in this session — a fresh
116
279
  // handshake per turn is a real, measurable chunk of the latency this
117
280
  // rewrite exists to remove. Recreated on demand if it ever drops.
@@ -141,10 +304,22 @@ async function handleConnection(client, deps) {
141
304
  }
142
305
  return { stream: speakStream, ready: speakStreamReady };
143
306
  }
144
- // Discards whatever the current turn is still synthesizing/sending, and
145
- // unsticks a pending speakStreamed() call if one is in flight — Deepgram's
146
- // "Clear" isn't guaranteed to itself trigger a "Flushed" confirmation, so
147
- // without this the interrupted call's promise would hang forever.
307
+ // A real, live-reported bug in what used to live here: a "confirm-or-
308
+ // reverse" grace window that, on ANY barge-in with no confirming STT
309
+ // transcript arriving within 600ms, concluded it was a false positive
310
+ // and RE-SPOKE THE SAME TEXT FROM THE TOP. Live symptom, reported
311
+ // directly: saying "stop" cut the agent off, paused for about a
312
+ // second, then the exact same answer started playing again from the
313
+ // beginning — because Deepgram's own transcript for "stop" routinely
314
+ // arrived a little later than the 600ms window, so every clean,
315
+ // deliberate interruption looked exactly like an unconfirmed false
316
+ // alarm and got "resumed." Direct user instruction: there should be no
317
+ // such system at all — a barge-in should behave like it does in any
318
+ // normal voice assistant, an immediate, permanent stop, never a guess
319
+ // at whether to talk over the user again. `triggerServerBargeIn` is
320
+ // now exactly that: bump generation (drops any audio/verb already in
321
+ // flight), clear the TTS stream, unstick a pending speakStreamed()
322
+ // call — and nothing else.
148
323
  function triggerServerBargeIn() {
149
324
  generation++;
150
325
  speakStream?.clear();
@@ -156,24 +331,24 @@ async function handleConnection(client, deps) {
156
331
  stream.setAudioHandler((chunk) => {
157
332
  if (myGeneration !== generation)
158
333
  return; // stale — dropped by barge-in
159
- safeSend(client, { type: "audio_chunk", audio: chunk.toString("base64"), sampleRate: TTS_SAMPLE_RATE });
334
+ safeSend(client, { type: "audio_chunk", audio: chunk.toString("base64"), sampleRate: TTS_SAMPLE_RATE, generation: myGeneration });
160
335
  });
161
336
  await ready;
162
337
  if (!speakStream || myGeneration !== generation) {
163
338
  // Reconnect failed, or barge-in happened before the stream connected —
164
339
  // either way, only degrade to turn_complete if this is still current.
165
340
  if (myGeneration === generation)
166
- safeSend(client, { type: "turn_complete" });
341
+ safeSend(client, { type: "turn_complete", generation: myGeneration });
167
342
  return;
168
343
  }
169
344
  await new Promise((resolve) => {
170
345
  onCurrentTurnFlushed = () => {
171
346
  onCurrentTurnFlushed = null;
172
347
  if (myGeneration === generation)
173
- safeSend(client, { type: "speaking_end" });
348
+ safeSend(client, { type: "speaking_end", generation: myGeneration });
174
349
  resolve();
175
350
  };
176
- safeSend(client, { type: "speaking_start" });
351
+ safeSend(client, { type: "speaking_start", generation: myGeneration });
177
352
  stream.sendText(text);
178
353
  stream.flush();
179
354
  });
@@ -197,21 +372,16 @@ async function handleConnection(client, deps) {
197
372
  }, 15000);
198
373
  });
199
374
  }
200
- // Accumulates Deepgram "Results" transcript segments across one utterance
201
- // — see handleDeepgramMessage for why this can't just react to every
202
- // is_final.
203
- const turnState = { buffer: "" };
204
- dg.on("message", (data) => {
205
- void handleDeepgramMessage(data.toString(), client, deps, () => context, speakStreamed, history, turnState, () => generation, waitForToolResult);
206
- });
207
- dg.on("error", (err) => {
208
- console.error("[cairn realtime] Deepgram STT connection error:", err);
209
- safeSend(client, { type: "error", message: "speech recognition unavailable" });
210
- });
211
375
  client.on("message", (data, isBinary) => {
212
376
  if (isBinary) {
213
377
  const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
214
- if (dgOpen)
378
+ // The readyState check (not just dgOpen) is real, defensive belt-and-
379
+ // suspenders: dgOpen is reset to false the instant "close" fires, but
380
+ // a mic frame arriving in the same tick as a not-yet-processed close
381
+ // event should never risk calling .send() on a socket that's already
382
+ // gone — that used to be exactly how a dead connection kept silently
383
+ // swallowing audio with no error ever surfacing.
384
+ if (dgOpen && dg.readyState === ws_1.WebSocket.OPEN)
215
385
  dg.send(buf);
216
386
  else
217
387
  pendingAudio.push(buf);
@@ -226,6 +396,32 @@ async function handleConnection(client, deps) {
226
396
  liveElements: parseLiveElements(msg.liveElements),
227
397
  webMcpTools: parseWebMcpTools(msg.webMcpTools),
228
398
  };
399
+ // Phase 5 — `scopeId` is whatever opaque id the CUSTOMER's own
400
+ // client code chooses to send (their own end-user id if they have
401
+ // login, anything else stable otherwise) — this SDK never invents
402
+ // one. Only the first real scopeId this connection ever sees is
403
+ // used; a later "context" resend's scopeId (route changes send
404
+ // these routinely) is ignored, and the one-time prior-turn load
405
+ // below never repeats.
406
+ if (!scopeId && typeof msg.scopeId === "string" && msg.scopeId) {
407
+ const newScopeId = msg.scopeId;
408
+ scopeId = newScopeId;
409
+ if (deps.memory && !historySeededFromMemory) {
410
+ historySeededFromMemory = true;
411
+ const priorTurns = deps.memory.recentTurns(newScopeId);
412
+ const seeded = (0, memory_sqlite_1.seedHistoryFromMemory)(history, priorTurns, agent_loop_1.MAX_HISTORY_TURNS);
413
+ history.length = 0;
414
+ history.push(...seeded);
415
+ // Prepended AFTER the cap above, deliberately exempt from
416
+ // it — a remembered fact ("prefers metric units") should
417
+ // stay in context for the WHOLE connection, not age out the
418
+ // same way an ordinary conversation turn does once enough
419
+ // new turns accumulate.
420
+ const factsSummary = (0, memory_sqlite_1.formatRememberedFacts)(deps.memory.recallFacts(newScopeId));
421
+ if (factsSummary)
422
+ history.unshift({ role: "assistant", text: factsSummary });
423
+ }
424
+ }
229
425
  }
230
426
  else if (msg.type === "tool_result" && typeof msg.observation === "string") {
231
427
  // The client finished executing a click/fill/read/call_tool step
@@ -277,7 +473,37 @@ async function handleConnection(client, deps) {
277
473
  speakStream?.close();
278
474
  });
279
475
  }
280
- async function handleDeepgramMessage(raw, client, deps, getContext, speakStreamed, history, turnState, getGeneration, waitForToolResult) {
476
+ async function handleDeepgramMessage(raw, client, deps, getContext, speakStreamed, history, turnState, getGeneration, waitForToolResult,
477
+ /** Phase 5 — called with each real (role, text) turn as it's finalized,
478
+ * right alongside the same-shaped `history.push`. Optional and a no-op
479
+ * by default so every existing call site keeps working unchanged. The
480
+ * realtime connection's own recordMemoryTurn writes it to durable
481
+ * storage when memory + a scopeId are both configured for this
482
+ * connection — see ConnectionDeps.memory's own doc comment. */
483
+ recordMemoryTurn,
484
+ /** Phase 5 step 2 — see finalizeTurn's own doc comment. Threaded
485
+ * through here purely to reach finalizeTurn's two call sites below. */
486
+ getScopeId,
487
+ /** Real, live-found gap this closes: `generation` (getGeneration/
488
+ * triggerServerBargeIn) previously only ever bumped on an EXPLICIT
489
+ * barge-in — two ordinary, sequential turns with no interruption
490
+ * between them shared the exact same generation number. That was
491
+ * fine for what `generation` was originally built for (dropping
492
+ * audio/verbs abandoned mid-turn by a real interruption), but it
493
+ * left the CLIENT's own generation-based staleness check (added for
494
+ * that same reason, in index.tsx) with no way to tell a merely SLOW
495
+ * turn's late-arriving reply apart from the current one — nothing
496
+ * had bumped, so the late reply's generation still matched. Found
497
+ * live: a "hello" reply that took long enough to arrive AFTER the
498
+ * next question's own "final" had already fired, landing on the
499
+ * wrong caption because both were tagged the same generation.
500
+ * Called once per genuinely NEW turn (both call sites below), so
501
+ * every real "final" gets its own fresh generation — a turn is now
502
+ * "superseded" the instant a newer one starts, not only when an
503
+ * explicit interruption says so. Optional and a no-op by default so
504
+ * every existing call site (own or a test's) that doesn't pass this
505
+ * keeps behaving exactly as before. */
506
+ bumpGeneration) {
281
507
  let msg;
282
508
  try {
283
509
  msg = JSON.parse(raw);
@@ -290,8 +516,10 @@ async function handleDeepgramMessage(raw, client, deps, getContext, speakStreame
290
516
  // after utterance_end_ms of silence — a safety net for the rare case a
291
517
  // Results message never carries speech_final:true, so a turn can't get
292
518
  // permanently stuck with real transcript sitting in the buffer forever.
293
- if (turnState.buffer)
294
- await finalizeTurn(turnState, client, deps, getContext, speakStreamed, history, getGeneration, waitForToolResult);
519
+ if (turnState.buffer) {
520
+ bumpGeneration?.();
521
+ await finalizeTurn(turnState, client, deps, getContext, speakStreamed, history, getGeneration, waitForToolResult, recordMemoryTurn, getScopeId);
522
+ }
295
523
  return;
296
524
  }
297
525
  if (msg.type !== "Results")
@@ -318,7 +546,8 @@ async function handleDeepgramMessage(raw, client, deps, getContext, speakStreame
318
546
  safeSend(client, { type: "interim", text: turnState.buffer });
319
547
  return;
320
548
  }
321
- await finalizeTurn(turnState, client, deps, getContext, speakStreamed, history, getGeneration, waitForToolResult);
549
+ bumpGeneration?.();
550
+ await finalizeTurn(turnState, client, deps, getContext, speakStreamed, history, getGeneration, waitForToolResult, recordMemoryTurn, getScopeId);
322
551
  }
323
552
  /**
324
553
  * Everything from here on (the LLM call, TTS streaming) can fail in ways
@@ -341,47 +570,159 @@ async function handleDeepgramMessage(raw, client, deps, getContext, speakStreame
341
570
  * ones aren't) doesn't end the turn here: the server can't execute a DOM
342
571
  * action itself, so it sends the step to the client, awaits its real
343
572
  * result over waitForToolResult(), folds that into a *local* working copy
344
- * of history, and calls resolveVerb again — repeat up to
345
- * MAX_LOOP_ITERATIONS. The connection's real `history` only gets the
346
- * user's real question plus the turn's final answer, committed once at
347
- * the end a turn that hits the cap mid-loop doesn't leave partial tool
348
- * noise in the conversation's real memory, same discipline the HTTP
349
- * path's runTypedAgentLoop (index.tsx) follows.
573
+ * of history, and calls resolveVerb again — repeat up to the iteration cap
574
+ * (driveAgentLoop's default of 6, in agent-loop.ts — the shared skeleton
575
+ * this function and the HTTP path's runTypedAgentLoop (index.tsx) both
576
+ * drive). The connection's real `history` only gets the user's real
577
+ * question plus the turn's final answer, committed once at the end here —
578
+ * a turn that hits the cap mid-loop doesn't leave partial tool noise in
579
+ * the conversation's real memory.
350
580
  */
351
- async function finalizeTurn(turnState, client, deps, getContext, speakStreamed, history, getGeneration, waitForToolResult) {
581
+ async function finalizeTurn(turnState, client, deps, getContext, speakStreamed, history, getGeneration, waitForToolResult, recordMemoryTurn,
582
+ /** Phase 5 step 2 — this connection's real scopeId, if it has one yet
583
+ * (see the "context" message handler). A getter, same pattern as
584
+ * getContext/getGeneration, since it can be set AFTER this turn
585
+ * already started (a scopeId only ever arrives via a "context"
586
+ * message, and a turn can begin before one has). Optional; absent or
587
+ * returning null both mean "no memory-backed tools offered." */
588
+ getScopeId) {
352
589
  const transcript = turnState.buffer;
353
590
  turnState.buffer = "";
354
591
  const myGeneration = getGeneration();
355
- safeSend(client, { type: "final", text: transcript });
356
- let loopHistory = history;
592
+ safeSend(client, { type: "final", text: transcript, generation: myGeneration });
357
593
  // The Talker: set once, the first time a turn turns out to need more
358
- // than one step (see the loop below) — a real, in-flight speakStreamed()
594
+ // than one step (see onStep below) — a real, in-flight speakStreamed()
359
595
  // call, never awaited until we're actually ready to speak the real
360
596
  // answer. Deliberately not re-triggered per step: the Speak connection
361
597
  // (speakStreamed) only ever handles one utterance at a time, so a second
362
598
  // ack mid-loop would race the first one's own audio_chunk/Flushed
363
599
  // handling instead of queuing cleanly.
364
600
  let ackPromise = null;
601
+ // Phase 3 step 5 — the Talker's real event stream ("Revisable by
602
+ // Design"'s pattern): a pure, fire-and-forget consumer, never awaited
603
+ // by driveAgentLoop, never able to affect its control flow. This
604
+ // realtime transport's own Talker projection is intentionally small —
605
+ // the only event type it currently DOES anything with is "inj" (the
606
+ // ack phrase), which it turns into the same real speakStreamed() call
607
+ // as before, just reached through a real event instead of an inline
608
+ // side effect inside onStep. "act"/"obs"/"thk" events flow through the
609
+ // same stream (driveAgentLoop already emits act/obs on its own; the
610
+ // Critic below emits a real "thk" with its own reasoning) but aren't
611
+ // consumed for anything yet — logged, not narrated, a real seam for a
612
+ // future richer Talker to attach to without touching the loop again.
613
+ function emitEvent(event) {
614
+ switch (event.type) {
615
+ case "inj":
616
+ // Phase 2 step 3 — the ack phrase's audio was already the only
617
+ // thing the user hears; this text-bearing sibling message makes
618
+ // WHAT was said visible in the wire protocol too — today the
619
+ // only way to know (packages/evals' voiceFrames capture full
620
+ // frames, but an "inj" event never otherwise reaches the client
621
+ // as readable text, only as synthesized audio). Purely
622
+ // informational — a client that ignores unknown message types
623
+ // loses nothing.
624
+ safeSend(client, { type: "ack", text: event.text });
625
+ ackPromise = speakStreamed(event.text);
626
+ return;
627
+ case "act":
628
+ console.log("[cairn talker] act:", (0, agent_loop_1.summarizeVerbForHistory)(event.verb));
629
+ return;
630
+ case "obs":
631
+ console.log("[cairn talker] obs:", event.observation);
632
+ return;
633
+ case "thk":
634
+ console.log("[cairn talker] thk:", event.text);
635
+ return;
636
+ }
637
+ }
638
+ // Architecture Pillar 4 — real Plan/Progress state the Critic (below)
639
+ // actually acts on, not just observability. Started EAGERLY, before the
640
+ // first real step even runs, when looksMultiStep(transcript) already
641
+ // flags this as a probable compound goal — replacing the old lazy gate
642
+ // (kicked off only once a turn had already revealed a non-terminal
643
+ // first step, one full model round trip later than it needed to be).
644
+ // A false-negative heuristic miss still falls back to that same lazy
645
+ // path below (`if (planLLM && !planPromise)`), so nothing regresses —
646
+ // this only ever makes planning START EARLIER, never skips it. Only
647
+ // the realtime transport had this Plan/Progress wiring until now — see
648
+ // index.tsx's runTypedAgentLoop for the typed/HTTP transport's own
649
+ // version, added in the same pass.
650
+ let planPromise = null;
651
+ let plan = null;
652
+ let progress = null;
653
+ const STALL_THRESHOLD = 3; // Magentic-One-sized bounded budget before the harness itself escalates to give_up, rather than trusting the Critic alone to notice it's stalling
654
+ // Architecture Pillar 3 (Skill half) — real, per-deployment Skills
655
+ // (skill-store.ts), a DIFFERENT scope axis than `memory` (per-user).
656
+ // Computed once, up front, since both the Planner (retrieval) and the
657
+ // Critic (accumulating what gets saved after this turn) need it.
658
+ const skillsScopeId = deps.skillsScopeId ?? "default";
659
+ const skillSummaries = deps.skills ? deps.skills.listSkillSummaries(skillsScopeId) : [];
660
+ const matchedSkillSummary = skillSummaries.length ? (0, server_1.matchSkillByGoal)(skillSummaries, transcript) : null;
661
+ const skillsPayload = skillSummaries.length
662
+ ? {
663
+ summariesText: (0, server_1.renderSkillSummaries)(skillSummaries) || undefined,
664
+ suggestedInstructions: matchedSkillSummary ? (deps.skills.getSkill(skillsScopeId, matchedSkillSummary.id)?.instructions ?? undefined) : undefined,
665
+ }
666
+ : undefined;
667
+ // Every real, Critic-verified learnedFact from this turn's steps — the
668
+ // Formulator (compileSkill) compiles whatever's here into a real Skill
669
+ // once the turn concludes, below. Empty is the common case, not a gap.
670
+ const learnedFacts = [];
671
+ // Architecture Pillar 5 — the Archive tier, checked once per turn
672
+ // (never always-injected the way Core facts are — those are seeded
673
+ // once per CONNECTION, in the "context" message handler above). Added
674
+ // only to THIS turn's own ephemeral working history, never persisted
675
+ // into the connection's real `history` array below — a fact resurfaced
676
+ // because it happened to relate to this one question shouldn't linger
677
+ // in context for the rest of the conversation the way a Core fact
678
+ // deliberately does.
679
+ const archiveScopeId = getScopeId?.() ?? null;
680
+ const archivedSummary = deps.memory && archiveScopeId ? (0, memory_sqlite_1.formatArchivedFacts)(deps.memory.recallArchivedFacts(archiveScopeId, transcript)) : null;
681
+ const historyForThisTurn = archivedSummary ? [...history, { role: "assistant", text: archivedSummary }] : history;
365
682
  try {
366
- for (let i = 0; i < MAX_LOOP_ITERATIONS; i++) {
367
- const { route, visible, liveElements, webMcpTools } = getContext();
368
- const verb = await (0, server_1.resolveVerb)(deps.llm, deps.systemPrompt, deps.manifest, deps.registeredActions, deps.capability, {
369
- route,
370
- question: transcript,
371
- visible,
372
- liveElements,
373
- webMcpTools,
374
- history: loopHistory,
375
- });
376
- if (myGeneration !== getGeneration())
377
- return; // superseded by a barge-in while this turn was resolving
378
- // Sent immediately before speech synthesis even starts — so
379
- // highlight/navigate/do execute in the browser right away instead of
380
- // waiting on audio. The agent visibly acts while it's still about to
381
- // speak, not after.
382
- safeSend(client, { type: "verb", verb });
383
- if (!core_1.TERMINAL_VERBS.has(verb.verb)) {
384
- if (i === 0) {
683
+ const planLLM = deps.planLLM;
684
+ const criticLLM = deps.criticLLM;
685
+ if (planLLM && (0, agent_loop_1.looksMultiStep)(transcript)) {
686
+ planPromise = (0, server_1.resolvePlan)(planLLM, transcript, 1, deps.manifest, (0, server_1.renderRegisteredActions)(deps.registeredActions, deps.actionDescriptions), skillsPayload);
687
+ }
688
+ const result = await (0, agent_loop_1.driveAgentLoop)(historyForThisTurn, {
689
+ async getNextStep(loopHistory) {
690
+ const { route, visible, liveElements, webMcpTools } = getContext();
691
+ // Phase 5 step 2 — offered only when there's somewhere real to
692
+ // write it (memory configured AND this connection has a real
693
+ // scopeId) never a tool the model can call into a void.
694
+ const availableTools = deps.memory && getScopeId?.() ? [...webMcpTools, REMEMBER_FACT_TOOL] : webMcpTools;
695
+ return (0, server_1.resolveVerb)(deps.llm, deps.systemPrompt, deps.manifest, deps.registeredActions, deps.capability, {
696
+ route,
697
+ question: transcript,
698
+ visible,
699
+ liveElements,
700
+ webMcpTools: availableTools,
701
+ history: loopHistory,
702
+ });
703
+ },
704
+ onStep({ verb, iteration, terminal }) {
705
+ if (myGeneration !== getGeneration())
706
+ return true; // superseded by a barge-in while this turn was resolving
707
+ // Phase 5 step 2 — a remember_fact call is handled entirely
708
+ // server-side (see executeStep below) and must NEVER be sent to
709
+ // the client: the client would try to look it up in its own
710
+ // real WebMCP tool registry, fail to find it (it's synthetic,
711
+ // server-only), and report an error tool_result back — landing
712
+ // on whatever's THEN occupying the single-slot
713
+ // pendingToolResultResolve, which by then could easily belong
714
+ // to a genuinely later, unrelated step. Suppressing this send
715
+ // is not an optimization, it's what keeps that real race from
716
+ // ever being possible.
717
+ const isRememberFactCall = verb.verb === "call_tool" && verb.name === REMEMBER_FACT_TOOL_NAME;
718
+ if (!isRememberFactCall) {
719
+ // Sent immediately — before speech synthesis even starts — so
720
+ // highlight/navigate/do execute in the browser right away instead
721
+ // of waiting on audio. The agent visibly acts while it's still
722
+ // about to speak, not after.
723
+ safeSend(client, { type: "verb", verb, generation: myGeneration });
724
+ }
725
+ if (!terminal && iteration === 0) {
385
726
  // This turn just revealed it needs more than one step — speak a
386
727
  // quick, cheap acknowledgment *now*, in parallel with the rest
387
728
  // of the loop's own real work below (not awaited here), so the
@@ -389,22 +730,132 @@ async function finalizeTurn(turnState, client, deps, getContext, speakStreamed,
389
730
  // air for however long the real multi-step answer takes.
390
731
  // Single-step turns (the common case) never reach this branch
391
732
  // at all, so they keep today's latency exactly as it is.
392
- ackPromise = speakStreamed(ACK_PHRASES[Math.floor(Math.random() * ACK_PHRASES.length)]);
733
+ // Emitted as a real "inj" event now (step 5), consumed by
734
+ // emitEvent above — same real speakStreamed() call, reached
735
+ // through the event stream instead of an inline side effect.
736
+ emitEvent({ type: "inj", text: ACK_PHRASES[Math.floor(Math.random() * ACK_PHRASES.length)], at: Date.now() });
737
+ // The lazy fallback — only fires when looksMultiStep missed
738
+ // (planPromise is still null): a real Plan is still guaranteed
739
+ // before the Critic needs one, just one round trip later than
740
+ // the eager path above.
741
+ if (planLLM && !planPromise)
742
+ planPromise = (0, server_1.resolvePlan)(planLLM, transcript, 1, deps.manifest, (0, server_1.renderRegisteredActions)(deps.registeredActions, deps.actionDescriptions), skillsPayload);
393
743
  }
394
- // A continuing step itself stays silent (keeps the loop fast; the
395
- // client still shows it visually) — wait for its real result and
396
- // go around again instead of ending the turn.
397
- const observation = await waitForToolResult();
398
- if (myGeneration !== getGeneration())
399
- return;
400
- loopHistory = [
401
- ...loopHistory,
402
- { role: "assistant", text: `${summarizeVerbForHistory(verb)}. Result: ${observation}` },
403
- ].slice(-MAX_HISTORY_TURNS);
404
- continue;
405
- }
406
- history.push({ role: "user", text: transcript }, { role: "assistant", text: summarizeVerbForHistory(verb) });
407
- history.splice(0, Math.max(0, history.length - MAX_HISTORY_TURNS));
744
+ return false;
745
+ },
746
+ // A continuing step itself stays silent (keeps the loop fast; the
747
+ // client still shows it visually) — wait for its real result and go
748
+ // around again instead of ending the turn.
749
+ executeStep: (verb) => {
750
+ // Phase 5 step 2 — resolved entirely in-process, never routed
751
+ // through the client's real tool-execution round trip (see
752
+ // onStep's own doc comment for why the client is never even
753
+ // told this step happened).
754
+ const currentScopeId = getScopeId?.() ?? null;
755
+ if (verb.verb === "call_tool" && verb.name === REMEMBER_FACT_TOOL_NAME && deps.memory && currentScopeId) {
756
+ return handleRememberFactTool(deps.memory, currentScopeId, verb.args);
757
+ }
758
+ return waitForToolResult();
759
+ },
760
+ onStepResult: () => myGeneration !== getGeneration(),
761
+ onEvent: emitEvent,
762
+ runCritic: planLLM && criticLLM
763
+ ? async ({ verb, observation }) => {
764
+ // Real state, not the Executor's self-report — see
765
+ // resolveCritic's own doc comment for why this is a
766
+ // genuinely separate pass, mirroring judge.ts's own
767
+ // precedent. Awaited here (not just logged) on its FIRST
768
+ // use — by now at least one real tool round trip has
769
+ // already happened, so the Planner call kicked off above
770
+ // has likely already resolved in parallel; this is not a
771
+ // NEW blocking wait so much as picking up work already in
772
+ // flight.
773
+ if (!plan) {
774
+ plan = planPromise ? await planPromise : (0, server_1.fallbackPlan)(transcript, 1);
775
+ progress = { planVersion: plan.version, currentTaskIndex: 0, stallCount: 0 };
776
+ }
777
+ const currentProgress = progress;
778
+ const currentTask = plan.tasks[currentProgress.currentTaskIndex];
779
+ const verdict = await (0, server_1.resolveCritic)(criticLLM, currentTask, transcript, verb, observation);
780
+ // A real "thk" event — the Critic's own reasoning, narrated
781
+ // onto the same event stream the ack/act/obs events already
782
+ // flow through (not spoken today, just carried — see
783
+ // emitEvent's own doc comment on why that's a deliberate,
784
+ // small v1 scope).
785
+ emitEvent({ type: "thk", text: verdict.reasoning, at: Date.now() });
786
+ // Architecture Pillar 3 (Skill half) — accumulate whatever
787
+ // this step's real, Critic-verified fact was; the
788
+ // Formulator compiles whatever's here into a real Skill
789
+ // once the turn concludes, below. The common case adds
790
+ // nothing here at all.
791
+ if (verdict.learnedFact)
792
+ learnedFacts.push(verdict.learnedFact);
793
+ if (verdict.verdict === "task_complete") {
794
+ currentTask.status = "done";
795
+ if (currentProgress.currentTaskIndex < plan.tasks.length - 1) {
796
+ // More tasks remain — advance and keep looping instead
797
+ // of ending the turn here.
798
+ currentProgress.currentTaskIndex++;
799
+ plan.tasks[currentProgress.currentTaskIndex].status = "in_progress";
800
+ currentProgress.stallCount = 0;
801
+ return { ...verdict, verdict: "continue" };
802
+ }
803
+ // The real bug fix: the LAST task is genuinely done —
804
+ // end the loop right here instead of asking the model
805
+ // again and hoping it notices its own success.
806
+ return verdict;
807
+ }
808
+ if (verdict.verdict === "replan") {
809
+ // A fresh Planner call, a real new version — never a
810
+ // silent patch to the existing plan.
811
+ plan = await (0, server_1.resolvePlan)(planLLM, transcript, plan.version + 1, deps.manifest, (0, server_1.renderRegisteredActions)(deps.registeredActions, deps.actionDescriptions), skillsPayload);
812
+ progress = { planVersion: plan.version, currentTaskIndex: 0, stallCount: 0 };
813
+ return { ...verdict, verdict: "continue" };
814
+ }
815
+ if (verdict.verdict === "give_up")
816
+ return verdict;
817
+ // "continue" — a harness-enforced fail-safe on top of the
818
+ // Critic's own judgment: crossing a bounded stall budget
819
+ // escalates to give_up itself, rather than trusting the
820
+ // Critic alone to eventually notice it's stuck (Magentic-One's
821
+ // own two-tier tolerance pattern).
822
+ currentProgress.stallCount++;
823
+ if (currentProgress.stallCount >= STALL_THRESHOLD) {
824
+ return {
825
+ verdict: "give_up",
826
+ reasoning: `Stuck after ${currentProgress.stallCount} steps with no confirmed progress on "${currentTask.description}" — ${verdict.reasoning}`,
827
+ };
828
+ }
829
+ return verdict;
830
+ }
831
+ : undefined,
832
+ });
833
+ if (result.outcome === "aborted")
834
+ return;
835
+ // Architecture Pillar 3 (Skill half) — the Formulator, run once per
836
+ // turn (not per-step — cheap on purpose). Saves nothing when nothing
837
+ // was learned (the common case) or no SkillStore is configured (zero
838
+ // overhead, today's exact behavior). Classified from whatever this
839
+ // exact moment's live context reports — a best-effort snapshot, not
840
+ // necessarily the exact page a given fact was learned on, which is
841
+ // an acceptable trade for a Skill meant to be a general per-platform
842
+ // note rather than a per-page one.
843
+ if (deps.skills && learnedFacts.length > 0) {
844
+ const patternMatches = (0, core_1.classifyUiPattern)((0, core_1.deriveStructureSignals)(getContext().liveElements));
845
+ const skill = (0, server_1.compileSkill)(transcript, learnedFacts, patternMatches[0]?.pattern);
846
+ if (skill)
847
+ deps.skills.saveSkill(skillsScopeId, skill);
848
+ }
849
+ if (result.outcome === "terminal" || result.outcome === "unparseable" || result.outcome === "critic-complete") {
850
+ const verb = result.outcome === "terminal"
851
+ ? result.finalVerb
852
+ : result.outcome === "critic-complete"
853
+ ? { verb: "explain", text: result.verdict.reasoning }
854
+ : { verb: "explain", text: "I'm not sure how to help with that." };
855
+ history.push({ role: "user", text: transcript }, { role: "assistant", text: (0, agent_loop_1.summarizeVerbForHistory)(verb) });
856
+ history.splice(0, Math.max(0, history.length - agent_loop_1.MAX_HISTORY_TURNS));
857
+ recordMemoryTurn?.("user", transcript);
858
+ recordMemoryTurn?.("assistant", (0, agent_loop_1.summarizeVerbForHistory)(verb));
408
859
  if (ackPromise) {
409
860
  // Never start a second speakStreamed call before the first (the
410
861
  // ack) has actually finished — same single Speak connection, one
@@ -419,31 +870,39 @@ async function finalizeTurn(turnState, client, deps, getContext, speakStreamed,
419
870
  // A verb with no spoken text (highlight/navigate/do often have none)
420
871
  // still needs to unstick the client's "thinking" state and let the mic
421
872
  // resume — turn_complete covers that with no audio path involved.
422
- if ("text" in verb && verb.text) {
423
- await speakStreamed(verb.text);
873
+ const textToSpeak = "text" in verb ? (verb.text ?? undefined) : undefined;
874
+ if (textToSpeak) {
875
+ await speakStreamed(textToSpeak);
424
876
  }
425
877
  else {
426
- safeSend(client, { type: "turn_complete" });
878
+ safeSend(client, { type: "turn_complete", generation: myGeneration });
427
879
  }
428
880
  return;
429
881
  }
430
- // Iteration cap hit with no terminal verb degrade honestly instead
431
- // of leaving the client waiting forever.
432
- history.push({ role: "user", text: transcript }, { role: "assistant", text: "(gave up after too many steps)" });
433
- history.splice(0, Math.max(0, history.length - MAX_HISTORY_TURNS));
434
- safeSend(client, { type: "verb", verb: { verb: "explain", text: "I wasn't able to finish that try asking again or breaking it into smaller steps." } });
882
+ // Iteration cap hit with no terminal verb, OR the Critic/stall
883
+ // fail-safe gave up — degrade honestly instead of leaving the client
884
+ // waiting forever. A real Critic give-up carries its own specific
885
+ // reasoning, which is a genuinely better message than the generic
886
+ // fallback belowuse it when there is one.
887
+ const giveUpText = result.outcome === "critic-give-up" ? result.verdict.reasoning : "I wasn't able to finish that — try asking again or breaking it into smaller steps.";
888
+ const gaveUpSummary = result.outcome === "critic-give-up" ? giveUpText : "(gave up after too many steps)";
889
+ history.push({ role: "user", text: transcript }, { role: "assistant", text: gaveUpSummary });
890
+ history.splice(0, Math.max(0, history.length - agent_loop_1.MAX_HISTORY_TURNS));
891
+ recordMemoryTurn?.("user", transcript);
892
+ recordMemoryTurn?.("assistant", gaveUpSummary);
893
+ safeSend(client, { type: "verb", verb: { verb: "explain", text: giveUpText }, generation: myGeneration });
435
894
  if (ackPromise) {
436
895
  await ackPromise;
437
896
  if (myGeneration !== getGeneration())
438
897
  return;
439
898
  }
440
- await speakStreamed("I wasn't able to finish that — try asking again or breaking it into smaller steps.");
899
+ await speakStreamed(giveUpText);
441
900
  }
442
901
  catch (err) {
443
902
  console.error("[cairn realtime] failed to resolve/speak this turn:", err);
444
903
  if (myGeneration === getGeneration()) {
445
904
  safeSend(client, { type: "error", message: "Something went wrong answering that — try again." });
446
- safeSend(client, { type: "turn_complete" });
905
+ safeSend(client, { type: "turn_complete", generation: myGeneration });
447
906
  }
448
907
  }
449
908
  }
@@ -488,33 +947,3 @@ function parseWebMcpTools(raw) {
488
947
  }
489
948
  return tools;
490
949
  }
491
- /** A short text form of any verb for the history log — not shown to the
492
- * user, just fed back to the model on later turns so it knows what it
493
- * already did/said. */
494
- function summarizeVerbForHistory(verb) {
495
- if ("text" in verb && verb.text)
496
- return verb.text;
497
- switch (verb.verb) {
498
- case "highlight":
499
- case "open":
500
- return `(highlighted ${verb.target})`;
501
- case "navigate":
502
- return `(navigated to ${verb.route})`;
503
- case "do":
504
- return `(ran ${verb.action}${verb.target ? ` on ${verb.target}` : ""})`;
505
- case "tour":
506
- return verb.steps.map((s) => s.text).join(" ");
507
- case "click":
508
- return `(clicked ${verb.target})`;
509
- case "fill":
510
- return `(typed "${verb.value}" into ${verb.target})`;
511
- case "read":
512
- return `(read ${verb.target})`;
513
- case "call_tool":
514
- return `(called ${verb.name})`;
515
- case "batch":
516
- return `(${verb.actions.length} steps: ${verb.actions.map((a) => a.verb).join(", ")})`;
517
- default:
518
- return "(no response)";
519
- }
520
- }