osborn 0.9.257 → 0.9.258

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.
@@ -315,6 +315,32 @@ export declare class ClaudeLLM extends llm.LLM {
315
315
  * @param sdkOptions - Full V1 Options (only used on first call to create the query)
316
316
  * @param callbacks - Event callbacks for the background consumer
317
317
  */
318
+ /**
319
+ * CLICK-TIME OVERLAP (0.9.258): eager-prime the resume. Starts the persistent
320
+ * SDK query with an OPEN-BUT-EMPTY channel so the CLI subprocess spawns and
321
+ * performs the `--resume` JSONL replay NOW — overlapping the connect handshake
322
+ * — then idles awaiting the first real message (which then hits the fast path,
323
+ * no replay). Verified against @anthropic-ai/claude-agent-sdk: with plain
324
+ * `options.resume` (no sessionStore), the subprocess spawns + the initialize/
325
+ * resume handshake fires at query() construction, independent of the input
326
+ * stream (streamInput only reads the stream AFTER init is written). No user
327
+ * message is pushed, so no turn/output is produced. Idempotent: no-op if a
328
+ * persistent query already exists. The primed query is owned by this LLM, so
329
+ * the normal teardown (abortQuery via killCurrentLLM/killWarm) reclaims it —
330
+ * covering the SDK caveat that a never-yielding primed query won't self-close.
331
+ */
332
+ primeResume(sdkOptions: Options, callbacks: {
333
+ onSessionId: (id: string) => void;
334
+ onCheckpoint: (checkpointId: string) => void;
335
+ eventEmitter: EventEmitter;
336
+ }): void;
337
+ /**
338
+ * Kick a prime via the normal chat() path so the EXACT turn sdkOptions are
339
+ * reused (single source of truth — zero drift). Fire-and-forget: chat() starts
340
+ * run(), which builds sdkOptions and diverts to primeResume. No-op if there's
341
+ * nothing to resume or a query is already live.
342
+ */
343
+ prewarmResume(): void;
318
344
  pushMessage(userText: string, sdkOptions: Options, callbacks: {
319
345
  onSessionId: (id: string) => void;
320
346
  onCheckpoint: (checkpointId: string) => void;
@@ -322,7 +348,7 @@ export declare class ClaudeLLM extends llm.LLM {
322
348
  }, pushOpts?: {
323
349
  priority?: 'now' | 'next' | 'later';
324
350
  }): void;
325
- chat({ chatCtx, toolCtx, connOptions, abortController, }: {
351
+ chat({ chatCtx, toolCtx, connOptions, abortController, primeOnly, }: {
326
352
  chatCtx: llm.ChatContext;
327
353
  toolCtx?: llm.ToolContext;
328
354
  connOptions?: APIConnectOptions;
@@ -330,6 +356,7 @@ export declare class ClaudeLLM extends llm.LLM {
330
356
  toolChoice?: llm.ToolChoice;
331
357
  extraKwargs?: Record<string, unknown>;
332
358
  abortController?: AbortController;
359
+ primeOnly?: boolean;
333
360
  }): llm.LLMStream;
334
361
  }
335
362
  /**
@@ -1729,6 +1729,48 @@ export class ClaudeLLM extends llm.LLM {
1729
1729
  * @param sdkOptions - Full V1 Options (only used on first call to create the query)
1730
1730
  * @param callbacks - Event callbacks for the background consumer
1731
1731
  */
1732
+ /**
1733
+ * CLICK-TIME OVERLAP (0.9.258): eager-prime the resume. Starts the persistent
1734
+ * SDK query with an OPEN-BUT-EMPTY channel so the CLI subprocess spawns and
1735
+ * performs the `--resume` JSONL replay NOW — overlapping the connect handshake
1736
+ * — then idles awaiting the first real message (which then hits the fast path,
1737
+ * no replay). Verified against @anthropic-ai/claude-agent-sdk: with plain
1738
+ * `options.resume` (no sessionStore), the subprocess spawns + the initialize/
1739
+ * resume handshake fires at query() construction, independent of the input
1740
+ * stream (streamInput only reads the stream AFTER init is written). No user
1741
+ * message is pushed, so no turn/output is produced. Idempotent: no-op if a
1742
+ * persistent query already exists. The primed query is owned by this LLM, so
1743
+ * the normal teardown (abortQuery via killCurrentLLM/killWarm) reclaims it —
1744
+ * covering the SDK caveat that a never-yielding primed query won't self-close.
1745
+ */
1746
+ primeResume(sdkOptions, callbacks) {
1747
+ if (this.#persistentQuery) {
1748
+ console.log('⚡ primeResume: persistent query already live — skip (no double-spawn)');
1749
+ return;
1750
+ }
1751
+ console.log('🔥 primeResume: eager cold-start — resume replay overlaps connect (no user message)');
1752
+ this.#messageChannel = new MessageChannel();
1753
+ this.#persistentQuery = query({ prompt: this.#messageChannel, options: sdkOptions });
1754
+ this.#activeQueries.add(this.#persistentQuery);
1755
+ this.#startBackgroundConsumer(callbacks);
1756
+ }
1757
+ /**
1758
+ * Kick a prime via the normal chat() path so the EXACT turn sdkOptions are
1759
+ * reused (single source of truth — zero drift). Fire-and-forget: chat() starts
1760
+ * run(), which builds sdkOptions and diverts to primeResume. No-op if there's
1761
+ * nothing to resume or a query is already live.
1762
+ */
1763
+ prewarmResume() {
1764
+ if (!this.#opts.resumeSessionId && !this.#sessionId) {
1765
+ console.log('⚡ prewarmResume: no session to resume — skip');
1766
+ return;
1767
+ }
1768
+ if (this.#persistentQuery) {
1769
+ console.log('⚡ prewarmResume: query already live — skip');
1770
+ return;
1771
+ }
1772
+ this.chat({ chatCtx: new llm.ChatContext(), primeOnly: true });
1773
+ }
1732
1774
  pushMessage(userText, sdkOptions, callbacks,
1733
1775
  // Progressive-interrupt ladder: the SDK's own queue delivers mid-turn
1734
1776
  // messages at the next tool boundary (native fold) — default. 'now' =
@@ -1941,7 +1983,7 @@ export class ClaudeLLM extends llm.LLM {
1941
1983
  console.log('🔒 Persistent session background consumer exited');
1942
1984
  }
1943
1985
  }
1944
- chat({ chatCtx, toolCtx, connOptions = DEFAULT_API_CONNECT_OPTIONS, abortController, }) {
1986
+ chat({ chatCtx, toolCtx, connOptions = DEFAULT_API_CONNECT_OPTIONS, abortController, primeOnly, }) {
1945
1987
  return new ClaudeLLMStream(this, {
1946
1988
  chatCtx,
1947
1989
  toolCtx,
@@ -1949,6 +1991,7 @@ export class ClaudeLLM extends llm.LLM {
1949
1991
  opts: this.#opts,
1950
1992
  sessionId: this.#sessionId,
1951
1993
  abortController,
1994
+ primeOnly,
1952
1995
  onSessionId: (id) => {
1953
1996
  const isFirst = !this.#sessionId;
1954
1997
  this.#sessionId = id;
@@ -1984,12 +2027,17 @@ class ClaudeLLMStream extends llm.LLMStream {
1984
2027
  #onCheckpoint;
1985
2028
  #abortController;
1986
2029
  #llmRef;
2030
+ // CLICK-TIME OVERLAP (0.9.258): when true, run() builds the exact turn
2031
+ // sdkOptions but, instead of pushing a user message, EAGER-PRIMES the resume —
2032
+ // starts the SDK query with an empty channel so the --resume JSONL replay
2033
+ // overlaps the connect handshake. Never speaks, never pushes a turn.
2034
+ #primeOnly = false;
1987
2035
  #approvedWriterToolUseIds = new Set();
1988
2036
  // Last Task/Agent dispatch description per subagent_type, captured at PreToolUse so
1989
2037
  // SubagentStart can label the Running row with WHAT the sub-agent is doing even if the
1990
2038
  // SDK hook input omits the prompt. Cleared when consumed by the matching start.
1991
2039
  #pendingTaskByType = new Map();
1992
- constructor(llmInstance, { chatCtx, toolCtx, connOptions, opts, sessionId, onSessionId, eventEmitter, onCheckpoint, onPermissionRequest, abortController, }) {
2040
+ constructor(llmInstance, { chatCtx, toolCtx, connOptions, opts, sessionId, onSessionId, eventEmitter, onCheckpoint, onPermissionRequest, abortController, primeOnly, }) {
1993
2041
  super(llmInstance, { chatCtx, toolCtx, connOptions });
1994
2042
  this.#llmRef = llmInstance;
1995
2043
  this.#opts = opts;
@@ -1999,6 +2047,7 @@ class ClaudeLLMStream extends llm.LLMStream {
1999
2047
  this.#onCheckpoint = onCheckpoint;
2000
2048
  this.#onPermissionRequest = onPermissionRequest;
2001
2049
  this.#abortController = abortController;
2050
+ this.#primeOnly = primeOnly === true;
2002
2051
  }
2003
2052
  async run() {
2004
2053
  const requestId = `claude_${shortuuid()}`;
@@ -2021,6 +2070,12 @@ class ClaudeLLMStream extends llm.LLMStream {
2021
2070
  break;
2022
2071
  }
2023
2072
  }
2073
+ // CLICK-TIME OVERLAP: a prime has NO user message. Use a sentinel so the
2074
+ // sdkOptions build below runs unchanged; it is never pushed to the model
2075
+ // (run() diverts to primeResume before the pushMessage call).
2076
+ if (this.#primeOnly && !userText.trim()) {
2077
+ userText = '[CONNECT_PREWARM]';
2078
+ }
2024
2079
  if (!userText.trim()) {
2025
2080
  this.queue.put({
2026
2081
  id: requestId,
@@ -2028,7 +2083,8 @@ class ClaudeLLMStream extends llm.LLMStream {
2028
2083
  });
2029
2084
  return;
2030
2085
  }
2031
- console.log(`🎤 User (${userText.length} chars): "${userText}"`);
2086
+ if (!this.#primeOnly)
2087
+ console.log(`🎤 User (${userText.length} chars): "${userText}"`);
2032
2088
  // Build Claude Agent SDK options
2033
2089
  const resumeSessionId = this.#opts.resumeSessionId;
2034
2090
  const continueSession = this.#opts.continueSession;
@@ -2725,6 +2781,20 @@ class ClaudeLLMStream extends llm.LLMStream {
2725
2781
  // Meeting transcript chunks are ambient and must NOT interrupt (they
2726
2782
  // arrive continuously and would abort working turns nonstop).
2727
2783
  // Escape hatch: OSBORN_MSG_PRIORITY=off restores queue-and-fold.
2784
+ // CLICK-TIME OVERLAP diversion: start the resume replay NOW with an
2785
+ // empty channel (no user message) so it overlaps the connect handshake.
2786
+ // The subprocess then idles awaiting the first real message, which hits
2787
+ // the fast path. Uses the EXACT sdkOptions a real turn would (built
2788
+ // above) — so the primed subprocess IS the session's, zero drift.
2789
+ if (this.#primeOnly) {
2790
+ console.log('🔥 [CONNECT-OVERLAP] priming resume replay (empty channel, no message pushed)');
2791
+ this.#llmRef.primeResume(sdkOptions, {
2792
+ onSessionId: this.#onSessionId,
2793
+ onCheckpoint: this.#onCheckpoint,
2794
+ eventEmitter: this.#eventEmitter,
2795
+ });
2796
+ return;
2797
+ }
2728
2798
  const steerNow = process.env.OSBORN_MSG_PRIORITY !== 'off'
2729
2799
  && !userText.startsWith('[MEETING') // ambient transcript chunks never abort a turn
2730
2800
  && !userText.startsWith('[SYSTEM') // join/end notes etc. never abort a turn
package/dist/config.js CHANGED
@@ -403,7 +403,7 @@ export function buildMcpServersForKeys(config, enabledKeys) {
403
403
  // SESSION MANAGEMENT - For resuming previous conversations
404
404
  // ============================================================
405
405
  import * as readline from 'readline';
406
- import { createReadStream, statSync, readdirSync } from 'fs';
406
+ import { createReadStream, statSync, readdirSync, openSync, readSync, closeSync } from 'fs';
407
407
  /**
408
408
  * Get the .claude projects directory
409
409
  */
@@ -445,7 +445,7 @@ export async function listSessions(projectPath) {
445
445
  const stats = statSync(filePath);
446
446
  // Only include non-empty sessions with real conversation (> 2 messages)
447
447
  if (stats.size > 0) {
448
- const info = await getSessionPreview(filePath);
448
+ const info = await getSessionPreview(filePath, stats.size);
449
449
  if (info.messageCount > 2) {
450
450
  sessions.push({
451
451
  sessionId,
@@ -466,51 +466,110 @@ export async function listSessions(projectPath) {
466
466
  sessions.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
467
467
  return sessions;
468
468
  }
469
+ /** Parse JSONL text for the preview fields (message count + last user text). */
470
+ function scanPreviewLines(text, skipFirstPartial) {
471
+ const lines = text.split('\n');
472
+ let count = 0;
473
+ let lastUser;
474
+ // A tail slice usually begins mid-line — drop that fragment so JSON.parse
475
+ // doesn't choke on it (and never counts a half-record).
476
+ for (let i = skipFirstPartial ? 1 : 0; i < lines.length; i++) {
477
+ const line = lines[i].trim();
478
+ if (!line)
479
+ continue;
480
+ try {
481
+ const entry = JSON.parse(line);
482
+ if (entry.type === 'user' || entry.type === 'assistant')
483
+ count++;
484
+ if (entry.type === 'user' && entry.message?.content) {
485
+ const content = entry.message.content;
486
+ if (typeof content === 'string')
487
+ lastUser = content.substring(0, 100);
488
+ else if (Array.isArray(content)) {
489
+ const textPart = content.find((p) => p.type === 'text');
490
+ if (textPart?.text)
491
+ lastUser = textPart.text.substring(0, 100);
492
+ }
493
+ }
494
+ }
495
+ catch {
496
+ // skip malformed / partial line
497
+ }
498
+ }
499
+ return { count, lastUser };
500
+ }
469
501
  /**
470
- * Get a preview of a session (last message and count)
502
+ * Get a preview of a session (last message + count).
503
+ *
504
+ * PERF (sub-second-connect initiative): this used to stream and JSON.parse the
505
+ * ENTIRE transcript — which meant the dashboard session list read a 155–323MB
506
+ * JSONL end-to-end per cold load (the ~30s dashboard stall measured in the
507
+ * connect video). The preview only needs (a) enough to clear the ">2 messages"
508
+ * gate and (b) the LAST user message. So: small files are read whole (exact);
509
+ * large files read a bounded HEAD (gate + density sample) + TAIL (last user
510
+ * message), turning a hundreds-of-MB parse into ~192KB. messageCount becomes an
511
+ * estimate for large files — it's display-only and gated on ">2", which any
512
+ * large session clears from the head alone.
471
513
  */
472
- async function getSessionPreview(filePath) {
473
- return new Promise((resolve) => {
474
- let messageCount = 0;
475
- let lastUserMessage;
476
- const fileStream = createReadStream(filePath);
477
- const rl = readline.createInterface({
478
- input: fileStream,
479
- crlfDelay: Infinity,
480
- });
481
- rl.on('line', (line) => {
482
- if (!line.trim())
483
- return;
484
- try {
485
- const entry = JSON.parse(line);
486
- if (entry.type === 'user' || entry.type === 'assistant') {
487
- messageCount++;
488
- }
489
- if (entry.type === 'user' && entry.message?.content) {
490
- // Extract text from user message
491
- const content = entry.message.content;
492
- if (typeof content === 'string') {
493
- lastUserMessage = content.substring(0, 100);
494
- }
495
- else if (Array.isArray(content)) {
496
- const textPart = content.find((p) => p.type === 'text');
497
- if (textPart?.text) {
498
- lastUserMessage = textPart.text.substring(0, 100);
514
+ async function getSessionPreview(filePath, fileSize) {
515
+ const HEAD = 64 * 1024;
516
+ const TAIL = 128 * 1024;
517
+ try {
518
+ const size = fileSize ?? statSync(filePath).size;
519
+ if (size <= HEAD + TAIL) {
520
+ // Small enough to read whole — exact count + last message (cheap).
521
+ const whole = await new Promise((resolve) => {
522
+ let count = 0;
523
+ let lastUser;
524
+ const rl = readline.createInterface({ input: createReadStream(filePath), crlfDelay: Infinity });
525
+ rl.on('line', (line) => {
526
+ if (!line.trim())
527
+ return;
528
+ try {
529
+ const entry = JSON.parse(line);
530
+ if (entry.type === 'user' || entry.type === 'assistant')
531
+ count++;
532
+ if (entry.type === 'user' && entry.message?.content) {
533
+ const content = entry.message.content;
534
+ if (typeof content === 'string')
535
+ lastUser = content.substring(0, 100);
536
+ else if (Array.isArray(content)) {
537
+ const textPart = content.find((p) => p.type === 'text');
538
+ if (textPart?.text)
539
+ lastUser = textPart.text.substring(0, 100);
540
+ }
499
541
  }
500
542
  }
501
- }
502
- }
503
- catch {
504
- // Skip malformed lines
505
- }
506
- });
507
- rl.on('close', () => {
508
- resolve({ lastMessage: lastUserMessage, messageCount });
509
- });
510
- rl.on('error', () => {
511
- resolve({ messageCount: 0 });
512
- });
513
- });
543
+ catch { /* skip */ }
544
+ });
545
+ rl.on('close', () => resolve({ count, lastUser }));
546
+ rl.on('error', () => resolve({ count: 0 }));
547
+ });
548
+ return { lastMessage: whole.lastUser, messageCount: whole.count };
549
+ }
550
+ // Large file: bounded head + tail only.
551
+ const fd = openSync(filePath, 'r');
552
+ try {
553
+ const headBuf = Buffer.alloc(HEAD);
554
+ const hn = readSync(fd, headBuf, 0, HEAD, 0);
555
+ const tailBuf = Buffer.alloc(TAIL);
556
+ const tn = readSync(fd, tailBuf, 0, TAIL, Math.max(0, size - TAIL));
557
+ const head = scanPreviewLines(headBuf.toString('utf8', 0, hn), false);
558
+ const tail = scanPreviewLines(tailBuf.toString('utf8', 0, tn), true);
559
+ const lastMessage = tail.lastUser ?? head.lastUser;
560
+ // Estimate total from head density (display-only). Gate ">2" is satisfied
561
+ // by head.count alone for any real large session.
562
+ const avg = head.count > 0 ? hn / head.count : hn;
563
+ const messageCount = head.count >= 3 ? Math.max(3, Math.round(size / avg)) : head.count;
564
+ return { lastMessage, messageCount };
565
+ }
566
+ finally {
567
+ closeSync(fd);
568
+ }
569
+ }
570
+ catch {
571
+ return { messageCount: 0 };
572
+ }
514
573
  }
515
574
  /**
516
575
  * Get the most recent session ID for the current project
@@ -681,7 +740,7 @@ export async function listAllClaudeSessions(limit = 1000, includeSubagents = fal
681
740
  const sessions = [];
682
741
  const results = await Promise.all(topCandidates.map(async (c) => {
683
742
  try {
684
- const [preview, cwd] = await Promise.all([getSessionPreview(c.filePath), extractCwd(c.filePath)]);
743
+ const [preview, cwd] = await Promise.all([getSessionPreview(c.filePath, c.size), extractCwd(c.filePath)]);
685
744
  return { c, preview, cwd };
686
745
  }
687
746
  catch {
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import 'dotenv/config';
6
6
  import './boot-secrets.js';
7
7
  import { voice, initializeLogger } from '@livekit/agents';
8
8
  import { CloudTurnDetector } from './turn-detector-shim.js';
9
- import { Room, RoomEvent, } from '@livekit/rtc-node';
9
+ import { Room, RoomEvent, DisconnectReason, } from '@livekit/rtc-node';
10
10
  import { AccessToken } from 'livekit-server-sdk';
11
11
  // Initialize logger before anything else
12
12
  initializeLogger({ pretty: true, level: 'info' });
@@ -2177,6 +2177,147 @@ async function main() {
2177
2177
  console.log('⏻ [IDLE-EXIT] cancelled — activity resumed');
2178
2178
  }
2179
2179
  };
2180
+ // ── 0.9.258: KEEP-WARM RE-ATTACH (default-ON; OSBORN_KEEP_WARM=off to disable) ──
2181
+ // On a hard disconnect we normally kill the Claude subprocess (killCurrentLLM),
2182
+ // so a reconnect must cold-resume the JSONL — a 21–40s replay of the active
2183
+ // context window on a big session. Keep-warm instead PARKS the live subprocess
2184
+ // for a short grace: a reconnect to the SAME session re-attaches with ZERO
2185
+ // replay. The parked brain is independent of the LiveKit room/machine — it
2186
+ // costs only memory, and is bounded by THREE backstops so it can never leak
2187
+ // into the $123 empty-room/idle-machine bill:
2188
+ // 1. normal room teardown still runs on a network drop (releaseAgents +
2189
+ // fast-leave) — the parked brain does NOT hold the room (it's no longer
2190
+ // `currentLLM` nor in `slots`, so agentsActive() is false);
2191
+ // 2. a grace timer frees the parked brain if no reconnect arrives;
2192
+ // 3. an INDEPENDENT watchdog hard-kills it at a ceiling even if (2) is buggy.
2193
+ // One-owner invariant: the subprocess is owned by exactly one of
2194
+ // {currentLLM, warmLLM}, or it's aborted — never two live, never orphaned.
2195
+ // DEFAULT-ON (user, 2026-10-21): the three backstops above — not the flag —
2196
+ // are what make this safe, so it ships live. OSBORN_KEEP_WARM=off is the
2197
+ // escape hatch if a billing anomaly ever appears.
2198
+ const KEEP_WARM = process.env.OSBORN_KEEP_WARM !== 'off';
2199
+ // CLICK-TIME OVERLAP (default-ON; OSBORN_CONNECT_OVERLAP=off to disable): on a
2200
+ // resumed connect, eager-prime the JSONL replay so it overlaps the user
2201
+ // getting situated + speaking, instead of paying it serially on the first
2202
+ // message. Reuses the SAME subprocess that turn would spawn, so it only moves
2203
+ // the cost earlier — no extra subprocess, no billing delta.
2204
+ const CONNECT_OVERLAP = process.env.OSBORN_CONNECT_OVERLAP !== 'off';
2205
+ const REATTACH_GRACE_MS = Number(process.env.OSBORN_REATTACH_GRACE_MS || 150_000); // 2.5 min reconnect window (user: 2–3 min)
2206
+ const WARM_HARD_CEILING_MS = Number(process.env.OSBORN_WARM_CEILING_MS || 420_000); // 7 min absolute backstop
2207
+ let warmLLM = null;
2208
+ let warmSessionId = null;
2209
+ let warmExpiry = 0;
2210
+ let warmGraceTimer = null;
2211
+ let warmWatchdog = null;
2212
+ const warmStats = { starts: 0, reattachHits: 0, wastedTimeouts: 0, watchdogKills: 0, mismatchKills: 0 };
2213
+ // The outbound events createDirectSession() OWNS the wiring for. Stripped on
2214
+ // every (re-)wire so a re-attached subprocess ends up with exactly one
2215
+ // listener per event — no double TTS, no stacked handlers. Only OUR event
2216
+ // names; PipelineDirectLLM's internal emitter wiring is never touched.
2217
+ const DIRECT_SESSION_WIRED_EVENTS = [
2218
+ 'session_id', 'mcp_servers_changed', 'tool_use', 'tool_result',
2219
+ 'assistant_text', 'assistant_result', 'tts_chunks', 'permission_request',
2220
+ 'tts_say', 'session_resume_failed', 'checkpoint_captured',
2221
+ 'dispatch_rejected', 'task_completed', 'agent_started',
2222
+ ];
2223
+ // Abort + clear the parked brain. Clears BOTH timers so grace/watchdog can't
2224
+ // double-fire. Used on grace expiry, watchdog, and session mismatch.
2225
+ const killWarm = (reason) => {
2226
+ if (warmGraceTimer) {
2227
+ clearTimeout(warmGraceTimer);
2228
+ warmGraceTimer = null;
2229
+ }
2230
+ if (warmWatchdog) {
2231
+ clearTimeout(warmWatchdog);
2232
+ warmWatchdog = null;
2233
+ }
2234
+ if (warmLLM) {
2235
+ try {
2236
+ const llm = warmLLM;
2237
+ if (typeof llm.abortQuery === 'function')
2238
+ llm.abortQuery();
2239
+ else if (typeof llm.abortAgent === 'function')
2240
+ llm.abortAgent();
2241
+ }
2242
+ catch (err) {
2243
+ console.error(`❌ killWarm(${reason}) abort failed:`, err instanceof Error ? err.message : err);
2244
+ }
2245
+ }
2246
+ if (warmLLM)
2247
+ console.log(`🧊 [KEEP-WARM] freed warm slot (${reason})`);
2248
+ warmLLM = null;
2249
+ warmSessionId = null;
2250
+ warmExpiry = 0;
2251
+ };
2252
+ // Grace timer (free memory if no reconnect) + INDEPENDENT watchdog ceiling.
2253
+ // Both end in the SAME teardown: kill warm → releaseAgents → arm idle-exit, so
2254
+ // the machine always self-stops within WARM_HARD_CEILING_MS + idle-grace.
2255
+ const armWarmTimers = () => {
2256
+ if (warmGraceTimer)
2257
+ clearTimeout(warmGraceTimer);
2258
+ if (warmWatchdog)
2259
+ clearTimeout(warmWatchdog);
2260
+ warmGraceTimer = setTimeout(() => {
2261
+ warmGraceTimer = null;
2262
+ warmStats.wastedTimeouts++;
2263
+ console.log('🧊 [KEEP-WARM] grace expired with no reconnect — freeing warm slot');
2264
+ killWarm('grace_expired');
2265
+ releaseAgents();
2266
+ armIdleExitTimer('warm-grace-expired');
2267
+ }, REATTACH_GRACE_MS);
2268
+ warmWatchdog = setTimeout(() => {
2269
+ warmWatchdog = null;
2270
+ warmStats.watchdogKills++;
2271
+ console.warn('🧊 [KEEP-WARM] WATCHDOG ceiling hit — hard-freeing warm slot (backstop)');
2272
+ killWarm('watchdog_ceiling');
2273
+ releaseAgents();
2274
+ armIdleExitTimer('warm-watchdog');
2275
+ }, WARM_HARD_CEILING_MS);
2276
+ };
2277
+ // Move currentLLM → warm slot WITHOUT aborting it (the park). If there's no
2278
+ // session id to key re-attach on, there's nothing to reuse — abort instead so
2279
+ // we never strand an unkeyable subprocess.
2280
+ const parkWarm = (reason) => {
2281
+ if (!currentLLM)
2282
+ return;
2283
+ const sid = currentLLM.sessionId;
2284
+ if (!sid) {
2285
+ console.log(`🔥 [KEEP-WARM] no sessionId to key re-attach — aborting instead (${reason})`);
2286
+ killCurrentLLM(reason + '_no_sessionid');
2287
+ currentLLM = null;
2288
+ return;
2289
+ }
2290
+ // Supersede any existing parked brain (one-owner): abort the old one first.
2291
+ if (warmLLM && warmLLM !== currentLLM) {
2292
+ warmStats.mismatchKills++;
2293
+ killWarm('superseded_by_new_park');
2294
+ }
2295
+ warmLLM = currentLLM;
2296
+ warmSessionId = sid;
2297
+ warmExpiry = Date.now() + REATTACH_GRACE_MS;
2298
+ currentLLM = null;
2299
+ warmStats.starts++;
2300
+ armWarmTimers();
2301
+ console.log(`🔥 [KEEP-WARM] parked session ${sid.slice(0, 8)} (${reason}); grace ${REATTACH_GRACE_MS / 1000}s, ceiling ${WARM_HARD_CEILING_MS / 1000}s`);
2302
+ };
2303
+ // Detach the parked brain for reuse WITHOUT aborting it, cancelling its timers.
2304
+ // Caller takes ownership (becomes currentLLM via createDirectSession).
2305
+ const claimWarm = () => {
2306
+ if (warmGraceTimer) {
2307
+ clearTimeout(warmGraceTimer);
2308
+ warmGraceTimer = null;
2309
+ }
2310
+ if (warmWatchdog) {
2311
+ clearTimeout(warmWatchdog);
2312
+ warmWatchdog = null;
2313
+ }
2314
+ const llm = warmLLM;
2315
+ warmLLM = null;
2316
+ warmSessionId = null;
2317
+ warmExpiry = 0;
2318
+ warmStats.reattachHits++;
2319
+ return llm;
2320
+ };
2180
2321
  // ── 0.9.83: Zombie-presence watchdog + event-loss adopter DELETED ──
2181
2322
  // Both poll-based layers existed solely to compensate for Room-reuse damage:
2182
2323
  // • zombie-watchdog: RoomEvent callbacks stopped firing after a leave/rejoin
@@ -3421,6 +3562,17 @@ async function main() {
3421
3562
  const workspace = ensureSessionWorkspace(workingDir, resumeSessionId);
3422
3563
  console.log(`📁 Session workspace (resumed): ${workspace}`);
3423
3564
  }
3565
+ // Listener hygiene (keep-warm re-attach): createDirectSession OWNS the
3566
+ // outbound event wiring below. On a cold start the LLM is fresh so this is a
3567
+ // no-op; on a warm re-attach the reused subprocess still carries the prior
3568
+ // session's listeners, so strip exactly the events we re-wire to guarantee
3569
+ // exactly one listener each — no double TTS, no stacked handlers.
3570
+ for (const ev of DIRECT_SESSION_WIRED_EVENTS) {
3571
+ try {
3572
+ directLLM.events.removeAllListeners(ev);
3573
+ }
3574
+ catch { }
3575
+ }
3424
3576
  // For new sessions, create workspace when SDK assigns real session ID
3425
3577
  directLLM.events.once('session_id', ({ sessionId }) => {
3426
3578
  const workspace = ensureSessionWorkspace(workingDir, sessionId);
@@ -4281,7 +4433,30 @@ async function main() {
4281
4433
  // Create session based on voice mode (from frontend or config)
4282
4434
  let session;
4283
4435
  let agent;
4284
- if (true) {
4436
+ // KEEP-WARM re-attach (default-OFF via OSBORN_KEEP_WARM): if the warm slot
4437
+ // holds exactly this session and the grace hasn't lapsed, reuse the live
4438
+ // subprocess — ZERO replay. Listener re-wiring is idempotent inside
4439
+ // createDirectSession. On any mismatch/expiry, free the stale warm brain
4440
+ // (no leak) and fall through to the normal cold start.
4441
+ let reattached = false;
4442
+ if (KEEP_WARM && warmLLM && warmSessionId && resumeSessionId && warmSessionId === resumeSessionId && Date.now() < warmExpiry) {
4443
+ console.log(`🔥 [KEEP-WARM] re-attaching session ${warmSessionId.slice(0, 8)} — zero replay`);
4444
+ const reused = claimWarm();
4445
+ if (pendingSessionClose) {
4446
+ try {
4447
+ await pendingSessionClose;
4448
+ }
4449
+ catch { }
4450
+ }
4451
+ const result = await createDirectSession(resumeSessionId, reused);
4452
+ session = result.session;
4453
+ agent = result.agent;
4454
+ reattached = true;
4455
+ }
4456
+ else if (warmLLM) {
4457
+ killWarm(warmSessionId && warmSessionId !== resumeSessionId ? 'reattach_session_mismatch' : 'reattach_expired');
4458
+ }
4459
+ if (!reattached) {
4285
4460
  console.log(`🎯 PIPELINE MODE: Claude SDK + parallel fast brain`);
4286
4461
  // Pipeline mode = direct mode underneath + parallel fast brain
4287
4462
  // Fast brain runs in PipelineDirectLLM.chat() — fires Gemini alongside Claude
@@ -4330,6 +4505,21 @@ async function main() {
4330
4505
  }
4331
4506
  currentSession = session;
4332
4507
  currentAgent = agent; // Store for updateChatCtx() context injection
4508
+ // CLICK-TIME OVERLAP (default-ON; OSBORN_CONNECT_OVERLAP=off): for a resumed
4509
+ // session, kick the JSONL replay NOW (fire-and-forget) so it overlaps the
4510
+ // user getting situated + speaking — instead of paying it serially on the
4511
+ // first message (the 21–40s first-answer silence). The primed subprocess is
4512
+ // reused by that first message's fast path, so this only moves the cost
4513
+ // earlier. Skipped on re-attach (already holds a live warm subprocess) and a
4514
+ // no-op internally if a query is already live.
4515
+ if (CONNECT_OVERLAP && resumeSessionId && !reattached) {
4516
+ try {
4517
+ currentLLM?.prewarmResume?.();
4518
+ }
4519
+ catch (e) {
4520
+ console.error('⚠️ prewarmResume failed (non-fatal):', e instanceof Error ? e.message : e);
4521
+ }
4522
+ }
4333
4523
  // ============================================================
4334
4524
  // Session event wiring — extracted into function for auto-recovery
4335
4525
  // ============================================================
@@ -5012,6 +5202,32 @@ async function main() {
5012
5202
  console.log('📽️ Meeting active — keeping currentLLM alive across the voice-session drop (leave-grace owns teardown)');
5013
5203
  armMeetingLeaveGrace();
5014
5204
  }
5205
+ else if (KEEP_WARM && participant.disconnectReason === DisconnectReason.DUPLICATE_IDENTITY) {
5206
+ // DEVICE HANDOFF (keep-warm): the same identity rejoined from another
5207
+ // device, so LiveKit evicted THIS participant. It's not a session end —
5208
+ // park the brain for the incoming device's re-attach and do NOTHING
5209
+ // destructive to the room or agents; the new participant's
5210
+ // participantConnectedHandler owns continuation (re-attach or, on a
5211
+ // mismatch, it frees the warm slot). The warm watchdog is the backstop.
5212
+ console.log('🔀 [KEEP-WARM] duplicate-identity eviction — device handoff; parking brain, keeping room');
5213
+ parkWarm('duplicate_identity');
5214
+ clearPipelineFastBrainSession();
5215
+ clearPipelineFastBrainSession();
5216
+ }
5217
+ else if (KEEP_WARM && currentLLM && currentLLM.sessionId) {
5218
+ // KEEP-WARM network/tab-close drop: park the subprocess instead of killing
5219
+ // it so a reconnect within the grace re-attaches with ZERO replay. We
5220
+ // STILL run the normal room teardown below — the parked brain is
5221
+ // independent of the room (no longer currentLLM, not in slots, so
5222
+ // agentsActive() is false), so releaseAgents + fast-leave free the empty
5223
+ // room with no billing burn. The warm grace/watchdog free the parked brain.
5224
+ parkWarm('participant_disconnected');
5225
+ clearPipelineFastBrainSession();
5226
+ clearPipelineFastBrainSession();
5227
+ releaseAgents();
5228
+ armMeetingLeaveGrace();
5229
+ armFastLeaveTimer();
5230
+ }
5015
5231
  else {
5016
5232
  // Kill the Claude SDK subprocess BEFORE dropping the reference, otherwise the
5017
5233
  // persistent session keeps running tools and pushing TTS into a dead session.
@@ -64,6 +64,7 @@ export declare class PipelineDirectLLM extends llm.LLM {
64
64
  setMcpServers(s: any): void;
65
65
  setAgents(a: any): void;
66
66
  setTurbo(on: boolean): void;
67
+ prewarmResume(): void;
67
68
  interruptAgent(): Promise<boolean>;
68
69
  abortAgent(): void;
69
70
  rewindAgent(checkpointId?: string): Promise<boolean>;
@@ -112,6 +112,9 @@ export class PipelineDirectLLM extends llm.LLM {
112
112
  setMcpServers(s) { this.#claudeLLM.setMcpServers(s); }
113
113
  setAgents(a) { this.#claudeLLM.setAgents(a); }
114
114
  setTurbo(on) { this.#claudeLLM.setTurbo(on); }
115
+ // CLICK-TIME OVERLAP (0.9.258): start the resume replay early so it overlaps
116
+ // the connect handshake. Proxied to the inner ClaudeLLM.
117
+ prewarmResume() { this.#claudeLLM.prewarmResume(); }
115
118
  // Agent control — proxied to ClaudeLLM for fast brain access
116
119
  async interruptAgent() { return this.#claudeLLM.interruptQuery(); }
117
120
  abortAgent() { this.#claudeLLM.abortQuery(); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.257",
3
+ "version": "0.9.258",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {