osborn 0.9.271 → 0.9.275

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.
Files changed (61) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +82 -30
  2. package/.claude/skills/browser-apply/candidate.example.env +16 -0
  3. package/.claude/skills/browser-apply/fill.mjs +294 -0
  4. package/Dockerfile +1 -1
  5. package/dist/claude-auth.d.ts +85 -6
  6. package/dist/claude-auth.js +202 -22
  7. package/dist/claude-llm.d.ts +13 -0
  8. package/dist/claude-llm.js +171 -25
  9. package/dist/compaction-log.d.ts +67 -0
  10. package/dist/compaction-log.js +195 -0
  11. package/dist/config.d.ts +18 -0
  12. package/dist/config.js +122 -65
  13. package/dist/content/transcript-sanitizer.d.ts +20 -6
  14. package/dist/content/transcript-sanitizer.js +66 -11
  15. package/dist/data-sender-auth.d.ts +90 -0
  16. package/dist/data-sender-auth.js +158 -0
  17. package/dist/duck.d.ts +8 -0
  18. package/dist/duck.js +59 -0
  19. package/dist/env-keys.js +11 -0
  20. package/dist/index.js +493 -97
  21. package/dist/lib/safe-artifact-path.d.ts +17 -0
  22. package/dist/lib/safe-artifact-path.js +129 -0
  23. package/dist/meeting-addressing.d.ts +176 -0
  24. package/dist/meeting-addressing.js +288 -0
  25. package/dist/pipeline-direct-llm.d.ts +52 -1
  26. package/dist/pipeline-direct-llm.js +206 -61
  27. package/dist/prompts/direct-mode-fallback.md +1 -1
  28. package/dist/prompts/direct-mode-research.md +2 -2
  29. package/dist/prompts.d.ts +1 -1
  30. package/dist/prompts.js +3 -3
  31. package/dist/pushover.d.ts +77 -0
  32. package/dist/pushover.js +276 -0
  33. package/dist/recall-client.js +21 -2
  34. package/dist/session-store.d.ts +15 -5
  35. package/dist/session-store.js +37 -10
  36. package/dist/transcript-wiring.d.ts +121 -0
  37. package/dist/transcript-wiring.js +252 -0
  38. package/dist/voice-io.d.ts +0 -9
  39. package/dist/voice-io.js +5 -19
  40. package/dist/watch-gateway.d.ts +38 -0
  41. package/dist/watch-gateway.js +205 -0
  42. package/package.json +1 -1
  43. package/scripts/review.ts +1 -1
  44. package/dist/bridge-llm.d.ts +0 -22
  45. package/dist/bridge-llm.js +0 -39
  46. package/dist/codex-handler.d.ts +0 -38
  47. package/dist/codex-handler.js +0 -83
  48. package/dist/codex-llm.d.ts +0 -40
  49. package/dist/codex-llm.js +0 -144
  50. package/dist/fast-brain.d.ts +0 -176
  51. package/dist/fast-brain.js +0 -1887
  52. package/dist/index-3-2-26-legacy.d.ts +0 -1
  53. package/dist/index-3-2-26-legacy.js +0 -2233
  54. package/dist/leagcyprompts2.d.ts +0 -0
  55. package/dist/leagcyprompts2.js +0 -573
  56. package/dist/prompts-2-25-26.d.ts +0 -0
  57. package/dist/prompts-2-25-26.js +0 -518
  58. package/dist/prompts-3-2-26.d.ts +0 -78
  59. package/dist/prompts-3-2-26.js +0 -1319
  60. package/dist/summary-index.d.ts +0 -90
  61. package/dist/summary-index.js +0 -585
@@ -9,8 +9,34 @@
9
9
  * Phase 2 (future): Gemini speaks first, Claude suppressed when Gemini has HIGH confidence
10
10
  */
11
11
  import { llm, type APIConnectOptions } from '@livekit/agents';
12
- import { type ClaudeLLMOptions } from './claude-llm.js';
12
+ import { ClaudeLLM, type ClaudeLLMOptions } from './claude-llm.js';
13
+ import { type AgentControlCallbacks } from './pipeline-fastbrain.js';
13
14
  import { EventEmitter } from 'events';
15
+ export declare const SESSION_TAIL_DEFAULT_ROWS = 200;
16
+ export declare const SESSION_TAIL_DEFAULT_MAX_CHARS = 16000;
17
+ export declare function buildSessionTail(sessionId: string | null, workingDir: string, opts?: {
18
+ maxRows?: number;
19
+ maxChars?: number;
20
+ }): string;
21
+ /**
22
+ * Return a SHALLOW COPY of `chatCtx` whose last user message is a clone carrying
23
+ * `text`. The original context, its items array and every item object stay
24
+ * untouched — the LiveKit session echoes the ORIGINAL user item to the frontend
25
+ * (conversation_item_added → user_transcript), so mutating it leaked the
26
+ * [INTERRUPTED]/[CONTEXT]/<session_tail> enrichment into chat (UI#16). Earlier
27
+ * items are shared by reference; the clone keeps the item's id/role/prototype.
28
+ * Synchronous by design (chat() must stay sync). Returns the original when there
29
+ * is no user message.
30
+ */
31
+ export declare function withLastUserContent(chatCtx: llm.ChatContext, text: string): llm.ChatContext;
32
+ /**
33
+ * Return a SHALLOW COPY of `chatCtx` whose last user message is a clone with
34
+ * `note` prepended to its FIRST text part; every other part (images, etc.) is
35
+ * kept in place. With no text part the note becomes a new leading part. Same
36
+ * no-mutation guarantee as withLastUserContent. Returns the original when there
37
+ * is no user message.
38
+ */
39
+ export declare function withNotePrepended(chatCtx: llm.ChatContext, note: string): llm.ChatContext;
14
40
  export interface InterruptionContext {
15
41
  spokenText: string;
16
42
  recentMessages: string;
@@ -33,6 +59,8 @@ export interface PipelineDirectOptions extends ClaudeLLMOptions {
33
59
  getResearchContext?: () => string | undefined;
34
60
  /** Returns pending interruption context and clears it (consumed once). null = no pending interruption. */
35
61
  getAndConsumeInterruptionContext?: () => InterruptionContext | null;
62
+ /** Returns pending client notices as a hidden-context block and clears them ('' = none). */
63
+ getAndConsumeClientNotes?: () => string;
36
64
  }
37
65
  export interface FastBrainPanelResult {
38
66
  question: string;
@@ -51,6 +79,13 @@ export declare class PipelineDirectLLM extends llm.LLM {
51
79
  get model(): string;
52
80
  get isResumingSession(): boolean;
53
81
  label(): string;
82
+ get inner(): ClaudeLLM;
83
+ swapInner(newInner: ClaudeLLM): ClaudeLLM;
84
+ setWorkingContext({ workingDirectory, sessionBaseDir }: {
85
+ workingDirectory: string;
86
+ sessionBaseDir?: string;
87
+ }): void;
88
+ hasSession(): boolean;
54
89
  setResumeSessionId(id: string | null): void;
55
90
  setContinueSession(e: boolean): void;
56
91
  resetForSessionSwitch(): void;
@@ -93,4 +128,20 @@ export declare class PipelineDirectLLM extends llm.LLM {
93
128
  abortController?: AbortController;
94
129
  }): llm.LLMStream;
95
130
  }
131
+ /**
132
+ * Fast-brain agentControl bound to the inner ClaudeLLM a turn started on. Every
133
+ * callback is a no-op once the wrapper's current inner is no longer `inner` (after
134
+ * swapInner), so an emergency_stop from a pre-swap turn can't interrupt/re-prompt the
135
+ * promoted session. Deliberately NOT gated on the turn's abort signal: a newer user
136
+ * turn aborts it, and a "stop" followed quickly by more speech must still let the
137
+ * earlier turn's emergency_stop act on the same session (pre-swap behavior).
138
+ */
139
+ export declare function buildGuardedAgentControl(args: {
140
+ inner: ClaudeLLM;
141
+ getCurrentInner: () => ClaudeLLM;
142
+ getChatHistory: () => {
143
+ role: string;
144
+ content: string;
145
+ }[];
146
+ }): AgentControlCallbacks;
96
147
  export declare function createPipelineDirectLLM(opts: PipelineDirectOptions): PipelineDirectLLM;
@@ -14,47 +14,78 @@ import { askPipelineFastBrain } from './pipeline-fastbrain.js';
14
14
  import { storeExists, openStore, recentRows } from './session-store.js';
15
15
  import { statusManager } from './status-manager.js';
16
16
  import { noiseGate, GATE_CONTEXT_TURNS } from './noise-gate.js';
17
+ import { cleanTurnText, redactSecrets } from './content/transcript-sanitizer.js';
17
18
  // Bypass marker for gate-approved contexts: the deferred gate stream re-enters
18
19
  // chat() with the SAME chatCtx after a forward verdict; the marker makes the
19
20
  // second pass skip the gate and run the normal (enrichment + Claude) path.
20
21
  const gateApproved = new WeakSet();
21
22
  // ============================================================
22
- // SESSION TAIL — compact recent-conversation block prepended to every user turn
23
- // so the orchestrator never loses the thread across context compaction.
23
+ // SESSION TAIL — compact recent-conversation block prepended to the first real
24
+ // user turn after a compaction so the orchestrator never loses the thread.
24
25
  // Controlled by:
25
- // OSBORN_SESSION_TAIL — set to "0" to disable (default ON)
26
- // OSBORN_SESSION_TAIL_COUNT — max user+assistant lines to keep (default 200)
26
+ // OSBORN_SESSION_TAIL — set to "0" to disable (default ON)
27
+ // OSBORN_SESSION_TAIL_COUNT — max user+assistant lines to keep (default 200)
28
+ // OSBORN_SESSION_TAIL_MAX_CHARS — hard cap on the whole block, tags included
29
+ // (default 16000)
30
+ // Source rules (UI#16): the CURRENT session's store only, its main JSONL only
31
+ // (no sub-agent rows), newest by timestamp; every line goes through the shared
32
+ // sanitizer (wrappers, earlier tails, notices dropped; secrets redacted) BEFORE
33
+ // it is truncated to 150 chars.
27
34
  // ============================================================
28
- function buildSessionTail(sessionId, workingDir) {
35
+ export const SESSION_TAIL_DEFAULT_ROWS = 200;
36
+ export const SESSION_TAIL_DEFAULT_MAX_CHARS = 16000;
37
+ const SESSION_TAIL_LINE_CHARS = 150;
38
+ function envInt(name, fallback) {
39
+ const n = parseInt(process.env[name] || '', 10);
40
+ return Number.isFinite(n) && n > 0 ? n : fallback;
41
+ }
42
+ export function buildSessionTail(sessionId, workingDir, opts) {
29
43
  if (process.env.OSBORN_SESSION_TAIL === '0')
30
44
  return '';
31
45
  if (!sessionId)
32
46
  return '';
33
- const maxLines = parseInt(process.env.OSBORN_SESSION_TAIL_COUNT || '3000', 10);
47
+ const maxRows = opts?.maxRows ?? envInt('OSBORN_SESSION_TAIL_COUNT', SESSION_TAIL_DEFAULT_ROWS);
48
+ const maxChars = opts?.maxChars ?? envInt('OSBORN_SESSION_TAIL_MAX_CHARS', SESSION_TAIL_DEFAULT_MAX_CHARS);
49
+ const OPEN = '<session_tail>';
50
+ const CLOSE = '</session_tail>';
34
51
  try {
52
+ // Store resolved by THIS session's id → only this conversation's rows.
35
53
  const dbPath = storeExists(sessionId, workingDir);
36
54
  if (!dbPath)
37
55
  return ''; // no store → prior empty-index behavior
38
56
  const db = openStore(dbPath, { readonly: true });
39
57
  try {
40
- // Pull the most recent user+assistant rows (filtered in SQL, so we only
41
- // decompress rows we keep), newest-first, then reverse to chronological.
42
- const rows = recentRows(db, maxLines, ['user', 'assistant']);
43
- const convLines = [];
58
+ // Over-fetch: sanitizing drops notice/wrapper-only rows, so the limit
59
+ // should count kept lines, not raw rows.
60
+ const rows = recentRows(db, maxRows * 2, ['user', 'assistant'], { sources: ['main'] });
61
+ const kept = []; // newest-first while filling
62
+ let used = OPEN.length + CLOSE.length + 2; // tags + their newlines
44
63
  for (const row of rows) {
64
+ if (kept.length >= maxRows)
65
+ break;
45
66
  if (row.msgType !== 'user' && row.msgType !== 'assistant')
46
67
  continue;
68
+ const clean = cleanTurnText(row.text, row.msgType === 'user' ? 'user' : 'assistant');
69
+ if (!clean)
70
+ continue;
71
+ const summary = redactSecrets(clean
72
+ .replace(/<\/?session_tail>/g, '') // an inner tag would close the block early
73
+ .replace(/[\n\r\t]+/g, ' ').replace(/\s+/g, ' ').trim()
74
+ .substring(0, SESSION_TAIL_LINE_CHARS));
75
+ if (!summary)
76
+ continue;
47
77
  const timestamp = (row.ts || '').substring(0, 19);
48
78
  const speaker = row.msgType === 'user' ? 'User' : 'Assistant';
49
- const summary = row.text.replace(/[\n\r\t]+/g, ' ').replace(/\s+/g, ' ').trim().substring(0, 150);
50
- convLines.push(`${timestamp} ${speaker}: ${summary}`);
79
+ const line = `${timestamp} ${speaker}: ${summary}`;
80
+ if (used + line.length + 1 > maxChars)
81
+ break;
82
+ used += line.length + 1;
83
+ kept.push(line);
51
84
  }
52
- // recentRows is newest-first — reverse to chronological, then keep the tail.
53
- convLines.reverse();
54
- const kept = convLines.slice(-maxLines);
55
85
  if (kept.length === 0)
56
86
  return '';
57
- return ['<session_tail>', ...kept, '</session_tail>'].join('\n');
87
+ kept.reverse(); // chronological
88
+ return [OPEN, ...kept, CLOSE].join('\n');
58
89
  }
59
90
  finally {
60
91
  db.close();
@@ -64,6 +95,55 @@ function buildSessionTail(sessionId, workingDir) {
64
95
  return '';
65
96
  }
66
97
  }
98
+ /**
99
+ * Return a SHALLOW COPY of `chatCtx` whose last user message is a clone carrying
100
+ * `text`. The original context, its items array and every item object stay
101
+ * untouched — the LiveKit session echoes the ORIGINAL user item to the frontend
102
+ * (conversation_item_added → user_transcript), so mutating it leaked the
103
+ * [INTERRUPTED]/[CONTEXT]/<session_tail> enrichment into chat (UI#16). Earlier
104
+ * items are shared by reference; the clone keeps the item's id/role/prototype.
105
+ * Synchronous by design (chat() must stay sync). Returns the original when there
106
+ * is no user message.
107
+ */
108
+ export function withLastUserContent(chatCtx, text) {
109
+ const items = chatCtx.items.slice();
110
+ for (let i = items.length - 1; i >= 0; i--) {
111
+ const item = items[i];
112
+ if (item.type === 'message' && item.role === 'user') {
113
+ const clone = Object.assign(Object.create(Object.getPrototypeOf(item)), item);
114
+ clone.content = [text];
115
+ items[i] = clone;
116
+ return new llm.ChatContext(items);
117
+ }
118
+ }
119
+ return chatCtx;
120
+ }
121
+ /**
122
+ * Return a SHALLOW COPY of `chatCtx` whose last user message is a clone with
123
+ * `note` prepended to its FIRST text part; every other part (images, etc.) is
124
+ * kept in place. With no text part the note becomes a new leading part. Same
125
+ * no-mutation guarantee as withLastUserContent. Returns the original when there
126
+ * is no user message.
127
+ */
128
+ export function withNotePrepended(chatCtx, note) {
129
+ const items = chatCtx.items.slice();
130
+ for (let i = items.length - 1; i >= 0; i--) {
131
+ const item = items[i];
132
+ if (item.type === 'message' && item.role === 'user') {
133
+ const parts = Array.isArray(item.content) ? item.content.slice() : [];
134
+ const t = parts.findIndex((c) => typeof c === 'string');
135
+ if (t >= 0)
136
+ parts[t] = `${note}\n\n${parts[t]}`;
137
+ else
138
+ parts.unshift(note);
139
+ const clone = Object.assign(Object.create(Object.getPrototypeOf(item)), item);
140
+ clone.content = parts;
141
+ items[i] = clone;
142
+ return new llm.ChatContext(items);
143
+ }
144
+ }
145
+ return chatCtx;
146
+ }
67
147
  export class PipelineDirectLLM extends llm.LLM {
68
148
  #claudeLLM;
69
149
  #opts;
@@ -99,6 +179,34 @@ export class PipelineDirectLLM extends llm.LLM {
99
179
  get model() { return this.#claudeLLM.model; }
100
180
  get isResumingSession() { return this.#claudeLLM.isResumingSession; }
101
181
  label() { return 'pipeline-direct'; }
182
+ // ── Instance swap (foreground ⇄ background handoff) ──────────────────────────
183
+ // The voice AgentSession binds THIS wrapper for the whole session; chat() routes
184
+ // to #claudeLLM. swapInner() hot-swaps the inner ClaudeLLM so the voice can move
185
+ // to an already-running subprocess without tearing down the AgentSession. The
186
+ // caller owns moving voice event listeners between the old and new inner's emitter.
187
+ // Not wired by any caller yet (swap port step 1: guards + surface only).
188
+ get inner() { return this.#claudeLLM; }
189
+ swapInner(newInner) {
190
+ const prev = this.#claudeLLM;
191
+ // Cancel any in-flight fast-brain turn bound to the OLD inner so its agentControl
192
+ // closures can't fire interrupt/sendPrompt into the newly promoted session.
193
+ // Clear per-turn flags so the new inner starts clean.
194
+ try {
195
+ this.#turnAbort?.abort();
196
+ }
197
+ catch { }
198
+ this.#turnAbort = null;
199
+ this.#postCompactionTailPending = false;
200
+ this.#claudeLLM = newInner;
201
+ console.log('🔁 [pipeline] swapped inner ClaudeLLM (voice handoff)');
202
+ return prev;
203
+ }
204
+ // After a swap, point the dir-derived work (fast brain, session-tail) at the promoted
205
+ // session's working dir; otherwise #opts stays bound to the pre-swap session.
206
+ setWorkingContext({ workingDirectory, sessionBaseDir }) {
207
+ this.#opts = { ...this.#opts, workingDirectory, sessionBaseDir: sessionBaseDir ?? workingDirectory };
208
+ }
209
+ hasSession() { return this.#claudeLLM.hasSession(); }
102
210
  // Proxy all methods
103
211
  setResumeSessionId(id) { this.#claudeLLM.setResumeSessionId(id); }
104
212
  setContinueSession(e) { this.#claudeLLM.setContinueSession(e); }
@@ -220,6 +328,9 @@ export class PipelineDirectLLM extends llm.LLM {
220
328
  // interruptQuery() for a transcript chunk, aborting working turns nonstop.
221
329
  // Leave the pending context for the next REAL user message.
222
330
  const isMeetingChunkEarly = userText.startsWith('[MEETING');
331
+ // What the inner ClaudeLLM receives: the original chatCtx, or an enriched
332
+ // shallow copy of it (see withLastUserContent).
333
+ let ctxForClaude = chatCtx;
223
334
  const interruptCtx = isMeetingChunkEarly ? null : this.#opts.getAndConsumeInterruptionContext?.();
224
335
  if (interruptCtx && userText.trim()) {
225
336
  const hasInterrupt = !!interruptCtx.spokenText;
@@ -314,30 +425,26 @@ export class PipelineDirectLLM extends llm.LLM {
314
425
  // when text is non-empty.
315
426
  enrichedMessage = userText;
316
427
  }
317
- // Modify the last user message in chatCtx
428
+ // Enrich a SHALLOW COPY — never the original item (the session echoes it).
429
+ // Built here, after the noise-gate block, so gateApproved stays keyed on
430
+ // the ORIGINAL chatCtx (the gate re-enters chat() with that object).
318
431
  const finalMessage = sessionTailBlock
319
432
  ? sessionTailBlock + '\n\n' + enrichedMessage
320
433
  : enrichedMessage;
321
- for (let i = chatCtx.items.length - 1; i >= 0; i--) {
322
- const item = chatCtx.items[i];
323
- if (item.type === 'message' && item.role === 'user') {
324
- item.content = [finalMessage];
325
- break;
326
- }
327
- }
434
+ if (finalMessage !== userText)
435
+ ctxForClaude = withLastUserContent(chatCtx, finalMessage);
328
436
  }
329
437
  else if (sessionTailBlock && userText.trim()) {
330
- // No interrupt context — inject post-compaction session tail into the user message
331
- for (let i = chatCtx.items.length - 1; i >= 0; i--) {
332
- const item = chatCtx.items[i];
333
- if (item.type === 'message' && item.role === 'user') {
334
- const original = Array.isArray(item.content)
335
- ? item.content.filter((c) => typeof c === 'string').join('\n')
336
- : String(item.content ?? '');
337
- item.content = [sessionTailBlock + '\n\n' + original];
338
- break;
339
- }
340
- }
438
+ // No interrupt context — post-compaction session tail on a shallow copy.
439
+ ctxForClaude = withLastUserContent(chatCtx, sessionTailBlock + '\n\n' + userText);
440
+ }
441
+ // Client notices (favorite_changed, L2b): UI actions that are context, not a
442
+ // user turn. They ride the next real user turn as a leading
443
+ // <system-reminder> block on the same shallow copy (the sanitizer strips
444
+ // that block from history and titles). Never on meeting chunks.
445
+ const clientNotes = (!isMeetingChunkEarly && userText.trim()) ? this.#opts.getAndConsumeClientNotes?.() : '';
446
+ if (clientNotes) {
447
+ ctxForClaude = withNotePrepended(ctxForClaude, clientNotes);
341
448
  }
342
449
  // Meeting chunks ([MEETING —]) are the silent-observer / addressed-response
343
450
  // path. They must NOT drive the browser voice session: (a) no session.say()
@@ -356,8 +463,9 @@ export class PipelineDirectLLM extends llm.LLM {
356
463
  noiseGate.setEnabled(true, 'meeting');
357
464
  noiseGate.noteActivity();
358
465
  }
359
- // Fire Claude
360
- const claudeStream = this.#claudeLLM.chat({ chatCtx, toolCtx, connOptions, abortController });
466
+ // Fire Claude with the (possibly enriched) copy; the original stays as the
467
+ // user said it.
468
+ const claudeStream = this.#claudeLLM.chat({ chatCtx: ctxForClaude, toolCtx, connOptions, abortController });
361
469
  // Fire pipeline fast brain in background — no await, no blocking. Skip for
362
470
  // meeting chunks (silent observer / meeting-response path, not a user turn).
363
471
  if (userText.trim() && !isMeetingChunk) {
@@ -371,21 +479,24 @@ export class PipelineDirectLLM extends llm.LLM {
371
479
  this.#turnAbort.abort();
372
480
  this.#turnAbort = new AbortController();
373
481
  const signal = this.#turnAbort.signal;
482
+ // Bind this turn to the inner it started on. After swapInner() the closures
483
+ // below must not reach the newly promoted session (see buildGuardedAgentControl).
484
+ const inner = this.#claudeLLM;
374
485
  const startMs = Date.now();
375
486
  // Wait for SDK to assign session ID — listen for event instead of polling
376
487
  // Large sessions (22MB+) can take 10-15s for SDK to replay JSONL
377
- let sessionId = this.#claudeLLM.sessionId;
488
+ let sessionId = inner.sessionId;
378
489
  if (!sessionId) {
379
490
  sessionId = await new Promise((resolve) => {
380
491
  // Listen for the session_id event from SDK
381
492
  const onSessionId = (data) => {
382
493
  resolve(data.sessionId);
383
494
  };
384
- this.#claudeLLM.events.once('session_id', onSessionId);
495
+ inner.events.once('session_id', onSessionId);
385
496
  // Safety timeout — don't wait forever
386
497
  setTimeout(() => {
387
- this.#claudeLLM.events.removeListener('session_id', onSessionId);
388
- resolve(this.#claudeLLM.sessionId || 'pending');
498
+ inner.events.removeListener('session_id', onSessionId);
499
+ resolve(inner.sessionId || 'pending');
389
500
  }, 15000);
390
501
  });
391
502
  }
@@ -401,26 +512,11 @@ export class PipelineDirectLLM extends llm.LLM {
401
512
  chatHistory: this.#opts.getChatHistory?.() || [],
402
513
  researchContext: this.#opts.getResearchContext?.(),
403
514
  sessionBaseDir,
404
- agentControl: {
405
- interrupt: () => this.#claudeLLM.interruptQuery(),
406
- abort: () => this.#claudeLLM.abortQuery(),
407
- hasActiveAgent: () => this.#claudeLLM.hasActiveQuery(),
408
- getRecentUserMessages: (count) => {
409
- const history = this.#opts.getChatHistory?.() || [];
410
- return history
411
- .filter(t => t.role === 'user')
412
- .slice(-count)
413
- .map(t => t.content);
414
- },
415
- sendPrompt: (prompt) => {
416
- // Direct call to ClaudeLLM.chat() — event listeners (tts_say, tool_use, etc.) still attached
417
- // skipTTSQueue mode: tts_say events → index.ts → session.say() — works independently
418
- console.log(`🧠⚡ [control] Sending new prompt to Claude (${prompt.length} chars)`);
419
- const chatCtx = new llm.ChatContext();
420
- chatCtx.addMessage({ role: 'user', content: prompt });
421
- this.#claudeLLM.chat({ chatCtx });
422
- },
423
- },
515
+ agentControl: buildGuardedAgentControl({
516
+ inner,
517
+ getCurrentInner: () => this.#claudeLLM,
518
+ getChatHistory: () => this.#opts.getChatHistory?.() || [],
519
+ }),
424
520
  });
425
521
  if (signal.aborted)
426
522
  return;
@@ -446,6 +542,55 @@ export class PipelineDirectLLM extends llm.LLM {
446
542
  }
447
543
  }
448
544
  }
545
+ /**
546
+ * Fast-brain agentControl bound to the inner ClaudeLLM a turn started on. Every
547
+ * callback is a no-op once the wrapper's current inner is no longer `inner` (after
548
+ * swapInner), so an emergency_stop from a pre-swap turn can't interrupt/re-prompt the
549
+ * promoted session. Deliberately NOT gated on the turn's abort signal: a newer user
550
+ * turn aborts it, and a "stop" followed quickly by more speech must still let the
551
+ * earlier turn's emergency_stop act on the same session (pre-swap behavior).
552
+ */
553
+ export function buildGuardedAgentControl(args) {
554
+ const { inner, getCurrentInner, getChatHistory } = args;
555
+ const stale = () => inner !== getCurrentInner();
556
+ return {
557
+ interrupt: async () => {
558
+ if (stale())
559
+ return false;
560
+ return inner.interruptQuery();
561
+ },
562
+ abort: () => {
563
+ if (stale())
564
+ return;
565
+ inner.abortQuery();
566
+ },
567
+ hasActiveAgent: () => {
568
+ if (stale())
569
+ return false;
570
+ return inner.hasActiveQuery();
571
+ },
572
+ getRecentUserMessages: (count) => {
573
+ if (stale())
574
+ return [];
575
+ return getChatHistory()
576
+ .filter(t => t.role === 'user')
577
+ .slice(-count)
578
+ .map(t => t.content);
579
+ },
580
+ sendPrompt: (prompt) => {
581
+ if (stale()) {
582
+ console.log('🧠⚡ [control] Dropped stale sendPrompt (inner swapped)');
583
+ return;
584
+ }
585
+ // Direct call to ClaudeLLM.chat() — event listeners (tts_say, tool_use, etc.) still attached
586
+ // skipTTSQueue mode: tts_say events → index.ts → session.say() — works independently
587
+ console.log(`🧠⚡ [control] Sending new prompt to Claude (${prompt.length} chars)`);
588
+ const chatCtx = new llm.ChatContext();
589
+ chatCtx.addMessage({ role: 'user', content: prompt });
590
+ inner.chat({ chatCtx });
591
+ },
592
+ };
593
+ }
449
594
  // Deferred stream returned while the noise gate triages an utterance. Satisfies
450
595
  // the synchronous chat() → llm.LLMStream contract (LiveKit); run() resolves the
451
596
  // verdict and either drops (tombstoned by the gate) or re-enters chat() with the
@@ -1,7 +1,7 @@
1
1
  You are thinking with this person, not for them. You are a peer, not a service. Surface assumptions before acting. If you think they are asking the wrong question, say so.
2
2
 
3
3
  <context>
4
- You are Osborn, a voice AI thinking partner in direct mode. Your text is read aloud by TTS.
4
+ You are Osborn, a voice AI engineer and thinking partner in direct mode. Your text is read aloud by TTS.
5
5
  SESSION WORKSPACE: Not yet initialized.
6
6
  </context>
7
7
 
@@ -1,7 +1,7 @@
1
1
  <context>
2
- You are Osborn, a voice AI thinking partner. Your text output is read aloud by a TTS engine — every word you write is spoken to a user listening through speakers or headphones. You also have a session workspace where you can write detailed reference files that the user sees in a side panel.
2
+ You are Osborn, a voice AI engineer and thinking partner. Your text output is read aloud by a TTS engine — every word you write is spoken to a user listening through speakers or headphones. You also have a session workspace where you can write detailed reference files that the user sees in a side panel.
3
3
 
4
- You are NOT a research assistant who receives questions and delivers findings. You are a peer on a voice call who thinks out loud with the user, grounds yourself with cheap reads, proposes specific approaches before acting, and uses every moment of long-running work as an opportunity to gather steering signal that makes the eventual output better than autonomous execution would produce.
4
+ You are a peer on a voice call who thinks out loud with the user, grounds yourself with cheap reads, proposes specific approaches before acting, and uses every moment of long-running work as an opportunity to gather steering signal that makes the eventual output better than autonomous execution would produce.
5
5
 
6
6
  The conversation IS the work. Your dialogue with the user is what makes Osborn's output more useful than pure autonomous execution. Without the conversation, you are just a vending machine.
7
7