osborn 0.9.262 → 0.9.264

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.
@@ -247,7 +247,7 @@ export declare class ClaudeLLM extends llm.LLM {
247
247
  * whichever counter climbs in lockstep with heapUsed is the retainer behind
248
248
  * the heap-OOM crashes (11x since 2026-10-02). Read-only — no behavior change.
249
249
  */
250
- getMemDebug(): Record<string, number>;
250
+ getMemDebug(): Record<string, number | string>;
251
251
  /**
252
252
  * Check if checkpoints are available
253
253
  */
@@ -290,6 +290,17 @@ export declare class ClaudeLLM extends llm.LLM {
290
290
  noteTaskDispatch(toolUseId: string | undefined, subagentType: string | undefined): void;
291
291
  /** SubagentStart claim: pair this agent_id with the oldest unclaimed dispatch of its type. */
292
292
  claimTaskDispatch(agentId: string | undefined, subagentType: string | undefined): void;
293
+ /**
294
+ * Bounded-leak fix (0.9.264): drop a finished agent's pairing entries at
295
+ * SubagentStop. BOTH maps must go together — #resolveTaskId deliberately
296
+ * returns null when a pairing exists for an ended task (so a stale stop-click
297
+ * can never retarget a DIFFERENT live agent of the same type); with both
298
+ * entries deleted the resolve is null just the same, so behavior is unchanged
299
+ * while the maps stay bounded (they previously grew one entry per sub-agent
300
+ * for the life of the session, 200+ in heavy use). #dispatchedFor is NOT
301
+ * cleared here: it IS the double-fire dedup for the SubagentStop hook itself.
302
+ */
303
+ releaseAgentTracking(agentId: string | undefined): void;
293
304
  /** Background consumer feed: track SDK task lifecycle messages. */
294
305
  trackTaskMessage(msg: any): void;
295
306
  /** Live background tasks (for truthful status/UX). */
@@ -1115,6 +1115,13 @@ export class ClaudeLLM extends llm.LLM {
1115
1115
  // Dedup guard — prevents double-firing reviewer/gate if SubagentStop fires
1116
1116
  // more than once for the same agent_id (e.g. retry edge cases).
1117
1117
  #dispatchedFor = new Set();
1118
+ // MEM probe v2 (leak hunt, 0.9.263): cheap per-message attribution so a heap
1119
+ // spike in the [MEM] log can be correlated with what just flowed through the
1120
+ // SDK consumer. No stringify — only text lengths, O(blocks) per message.
1121
+ #memMsgCount = 0;
1122
+ #memCharsSeen = 0; // cumulative text chars observed on the stream
1123
+ #memMaxMsgChars = 0; // largest single message seen
1124
+ #memLastMsg = null;
1118
1125
  // Embedded session.db write-through guard. The store write is triggered from the
1119
1126
  // UserPromptSubmit hook (once per real user submission, main-thread only) and sweeps
1120
1127
  // the FULL source set — main JSONL + every sub-agent JSONL — exactly like the flat
@@ -1404,6 +1411,14 @@ export class ClaudeLLM extends llm.LLM {
1404
1411
  captureCheckpoint(checkpointId) {
1405
1412
  this.#checkpoints.push(checkpointId);
1406
1413
  this.#latestCheckpoint = checkpointId;
1414
+ // Bounded-leak fix (0.9.264): a checkpoint lands on EVERY user-type SDK
1415
+ // message (tool results included) — thousands over a long session, never
1416
+ // pruned. Rewind only ever consumes the FIRST (getFirstCheckpoint →
1417
+ // session start) and the LATEST (#latestCheckpoint, kept separately), so
1418
+ // retain [0] + the most recent 500 and drop the middle.
1419
+ if (this.#checkpoints.length > 600) {
1420
+ this.#checkpoints.splice(1, this.#checkpoints.length - 501);
1421
+ }
1407
1422
  console.log(`📍 Checkpoint captured: ${checkpointId.substring(0, 8)}...`);
1408
1423
  this.#eventEmitter.emit('checkpoint_captured', { checkpointId });
1409
1424
  }
@@ -1444,6 +1459,7 @@ export class ClaudeLLM extends llm.LLM {
1444
1459
  * the heap-OOM crashes (11x since 2026-10-02). Read-only — no behavior change.
1445
1460
  */
1446
1461
  getMemDebug() {
1462
+ const last = this.#memLastMsg;
1447
1463
  return {
1448
1464
  checkpoints: this.#checkpoints.length,
1449
1465
  tasksById: this.#tasksById.size,
@@ -1453,6 +1469,13 @@ export class ClaudeLLM extends llm.LLM {
1453
1469
  dispatchedFor: this.#dispatchedFor.size,
1454
1470
  busListeners: this.#eventEmitter.eventNames()
1455
1471
  .reduce((n, e) => n + this.#eventEmitter.listenerCount(e), 0),
1472
+ // v2 attribution: if heap creep tracks charsSeenMB, content flowing
1473
+ // through the consumer is being retained; a spike right after a huge
1474
+ // lastMsg names the allocator.
1475
+ msgCount: this.#memMsgCount,
1476
+ charsSeenMB: Math.round(this.#memCharsSeen / 1e6),
1477
+ maxMsgKB: Math.round(this.#memMaxMsgChars / 1e3),
1478
+ lastMsg: last ? `${last.type}${last.subtype ? '/' + last.subtype : ''}:${last.chars}ch@${Math.round((Date.now() - last.t) / 1000)}s` : 'none',
1456
1479
  };
1457
1480
  }
1458
1481
  /**
@@ -1655,6 +1678,22 @@ export class ClaudeLLM extends llm.LLM {
1655
1678
  this.#toolUseByAgentId.set(agentId, toolUse);
1656
1679
  }
1657
1680
  }
1681
+ /**
1682
+ * Bounded-leak fix (0.9.264): drop a finished agent's pairing entries at
1683
+ * SubagentStop. BOTH maps must go together — #resolveTaskId deliberately
1684
+ * returns null when a pairing exists for an ended task (so a stale stop-click
1685
+ * can never retarget a DIFFERENT live agent of the same type); with both
1686
+ * entries deleted the resolve is null just the same, so behavior is unchanged
1687
+ * while the maps stay bounded (they previously grew one entry per sub-agent
1688
+ * for the life of the session, 200+ in heavy use). #dispatchedFor is NOT
1689
+ * cleared here: it IS the double-fire dedup for the SubagentStop hook itself.
1690
+ */
1691
+ releaseAgentTracking(agentId) {
1692
+ if (!agentId)
1693
+ return;
1694
+ this.#toolUseByAgentId.delete(agentId);
1695
+ this.#typeByAgentId.delete(agentId);
1696
+ }
1658
1697
  /** Background consumer feed: track SDK task lifecycle messages. */
1659
1698
  trackTaskMessage(msg) {
1660
1699
  if (msg?.type !== 'system')
@@ -1853,6 +1892,23 @@ export class ClaudeLLM extends llm.LLM {
1853
1892
  try {
1854
1893
  for await (const message of pq) {
1855
1894
  const msg = message;
1895
+ // MEM probe v2: cheap attribution — count text chars (no stringify).
1896
+ {
1897
+ let chars = 0;
1898
+ const c = msg.message?.content;
1899
+ if (typeof c === 'string')
1900
+ chars = c.length;
1901
+ else if (Array.isArray(c))
1902
+ for (const b of c) {
1903
+ if (typeof b?.text === 'string')
1904
+ chars += b.text.length;
1905
+ }
1906
+ this.#memMsgCount++;
1907
+ this.#memCharsSeen += chars;
1908
+ if (chars > this.#memMaxMsgChars)
1909
+ this.#memMaxMsgChars = chars;
1910
+ this.#memLastMsg = { type: msg.type, subtype: msg.subtype, chars, t: Date.now() };
1911
+ }
1856
1912
  // Background-task lifecycle → registry (task_started/updated/notification).
1857
1913
  // This is what makes the per-flow stop button real: stopTask() needs the
1858
1914
  // task_id these messages carry.
@@ -2739,6 +2795,10 @@ class ClaudeLLMStream extends llm.LLMStream {
2739
2795
  console.warn('Pattern#1 chain push failed:', e);
2740
2796
  }
2741
2797
  }
2798
+ // Bounded-leak fix (0.9.264): the agent is done — release its
2799
+ // pairing entries (after the chain logic above has run).
2800
+ if (input?.agent_id)
2801
+ this.#llmRef.releaseAgentTracking(input.agent_id);
2742
2802
  return {};
2743
2803
  }]
2744
2804
  }],
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ import { existsSync, readdirSync, readFileSync, mkdirSync, writeFileSync, mkdtem
19
19
  import { dirname, join } from 'node:path';
20
20
  import { fileURLToPath } from 'node:url';
21
21
  import { spawn } from 'node:child_process';
22
+ import { getHeapStatistics } from 'node:v8';
22
23
  import { randomUUID, randomBytes } from 'node:crypto';
23
24
  import httpProxy from 'http-proxy';
24
25
  import { createRequire } from 'node:module';
@@ -2351,26 +2352,80 @@ async function main() {
2351
2352
  warmStats.reattachHits++;
2352
2353
  return llm;
2353
2354
  };
2354
- // ── MEM PROBE (leak hunt, 0.9.262) ──
2355
- // The heap-OOM crashes (11x since 2026-10-02) exceed what the known small
2356
- // leaks can retain — something holds LARGE message content in the main heap.
2357
- // Every 2 min, log heapUsed alongside the size of every suspect structure;
2358
- // over one heavy session, whichever counter climbs in lockstep with heapUsed
2359
- // is the retainer. heapUsed is the series that matters for the V8 limit
2360
- // (external/arrayBuffers — LiveKit audio — do NOT count toward it).
2355
+ // ── MEM PROBE v2 + GRACEFUL SELF-RECYCLE (leak hunt, 0.9.263) ──
2356
+ // v1 (0.9.262) proved the crash shape: transient 1–2.4GB allocation spikes on
2357
+ // a ~17MB/min creeping post-GC baseline; every suspect counter stayed in the
2358
+ // kilobytes — the retained content is NOT in the registries. v2 adds:
2359
+ // • 15s sampling with SPIKE detection — a ≥200MB jump between samples logs
2360
+ // an immediate [MEM-SPIKE] line carrying lastMsg attribution from the SDK
2361
+ // consumer (what just flowed through names the allocator); the normal
2362
+ // [MEM] cadence line still prints every 2 min (8 ticks).
2363
+ // • GRACEFUL SELF-RECYCLE, two tiers, so the process never OOM-dies:
2364
+ // SOFT (≥82% of ceiling, idle: no user in room, voice quiet, no bg
2365
+ // agents) → exit(0): machine stops cleanly, next connect boots a fresh
2366
+ // low-memory process and resumes the session. Same shape as idle-exit,
2367
+ // just memory-triggered.
2368
+ // HARD (≥95% of ceiling, even mid-session) → notify frontend, exit(1):
2369
+ // Fly's on-failure policy restarts the process immediately; the client
2370
+ // auto-rejoin + resume recovers in ~15s — vs an uncontrolled OOM crash
2371
+ // mid-sentence (same outcome, but announced and at a flush boundary).
2372
+ // Local dev (no FLY_APP_NAME) never self-exits. Ceiling read from V8 (the
2373
+ // --max-old-space-size the launcher set). Escape hatch: OSBORN_RECYCLE=off.
2374
+ const HEAP_LIMIT_MB = Math.round(getHeapStatistics().heap_size_limit / 1048576);
2375
+ const RECYCLE_ON = process.env.OSBORN_RECYCLE !== 'off';
2376
+ const RECYCLE_SOFT_MB = Math.round(HEAP_LIMIT_MB * Number(process.env.OSBORN_RECYCLE_SOFT_FRAC || 0.82));
2377
+ const RECYCLE_HARD_MB = Math.round(HEAP_LIMIT_MB * Number(process.env.OSBORN_RECYCLE_HARD_FRAC || 0.95));
2378
+ let memHighWaterMB = 0;
2379
+ let memLastSampleMB = 0;
2380
+ let memTick = 0;
2381
+ let recycling = false;
2382
+ console.log(`🧠 [MEM] heap ceiling ${HEAP_LIMIT_MB}MB — soft recycle ≥${RECYCLE_SOFT_MB}MB (idle only), hard ≥${RECYCLE_HARD_MB}MB`);
2383
+ const memLine = (tag, m) => {
2384
+ const mb = (b) => Math.round((b || 0) / 1048576);
2385
+ const s = currentLLM?.getMemDebug?.() ?? {};
2386
+ const chatCtxItems = currentAgent?.chatCtx?.items?.length ?? -1;
2387
+ const structs = Object.entries(s).map(([k, v]) => `${k}=${v}`).join(' ');
2388
+ return `🧠 [${tag}] heapUsed=${mb(m.heapUsed)}MB heapTotal=${mb(m.heapTotal)}MB rss=${mb(m.rss)}MB ` +
2389
+ `external=${mb(m.external)}MB arrayBuffers=${mb(m.arrayBuffers)}MB high=${memHighWaterMB}/${HEAP_LIMIT_MB}MB ` +
2390
+ `chatCtxItems=${chatCtxItems} slots=${slots.size} warm=${warmLLM ? 1 : 0} ${structs}`;
2391
+ };
2392
+ // Safe to recycle = nothing a restart would interrupt: no user in the room,
2393
+ // voice pipeline quiet, no host/background agents running.
2394
+ const safeToRecycle = () => {
2395
+ const noUser = !activeRoom || activeRoom.remoteParticipants.size === 0;
2396
+ const voiceQuiet = !currentSpeechHandle && voiceQueue.length === 0 && userState !== 'speaking';
2397
+ return noUser && voiceQuiet && !agentsActive();
2398
+ };
2361
2399
  setInterval(() => {
2362
2400
  try {
2363
2401
  const m = process.memoryUsage();
2364
- const mb = (b) => Math.round((b || 0) / 1048576);
2365
- const s = currentLLM?.getMemDebug?.() ?? {};
2366
- const chatCtxItems = currentAgent?.chatCtx?.items?.length ?? -1;
2367
- const structs = Object.entries(s).map(([k, v]) => `${k}=${v}`).join(' ');
2368
- console.log(`🧠 [MEM] heapUsed=${mb(m.heapUsed)}MB heapTotal=${mb(m.heapTotal)}MB rss=${mb(m.rss)}MB ` +
2369
- `external=${mb(m.external)}MB arrayBuffers=${mb(m.arrayBuffers)}MB ` +
2370
- `chatCtxItems=${chatCtxItems} slots=${slots.size} warm=${warmLLM ? 1 : 0} ${structs}`);
2402
+ const usedMB = Math.round(m.heapUsed / 1048576);
2403
+ if (usedMB > memHighWaterMB)
2404
+ memHighWaterMB = usedMB;
2405
+ memTick++;
2406
+ const spiked = memLastSampleMB > 0 && usedMB - memLastSampleMB >= 200;
2407
+ if (spiked)
2408
+ console.log(memLine('MEM-SPIKE', m) + ` Δ=+${usedMB - memLastSampleMB}MB/15s`);
2409
+ else if (memTick % 8 === 0)
2410
+ console.log(memLine('MEM', m));
2411
+ memLastSampleMB = usedMB;
2412
+ // Self-recycle tiers (Fly only, never local dev, escape hatch honored).
2413
+ if (!RECYCLE_ON || !process.env.FLY_APP_NAME || recycling)
2414
+ return;
2415
+ if (usedMB >= RECYCLE_HARD_MB) {
2416
+ recycling = true;
2417
+ console.warn(`♻️ [MEM] HARD recycle: heapUsed ${usedMB}MB ≥ ${RECYCLE_HARD_MB}MB (95% of ${HEAP_LIMIT_MB}MB) — restarting process NOW to pre-empt an OOM crash; client auto-rejoin + resume recovers`);
2418
+ sendToFrontend({ type: 'agent_recycling', reason: 'memory_hard', heapMB: usedMB }).catch(() => { });
2419
+ setTimeout(() => process.exit(1), 1500); // exit(1): on-failure policy RESTARTS the process (machine stays up)
2420
+ }
2421
+ else if (usedMB >= RECYCLE_SOFT_MB && safeToRecycle()) {
2422
+ recycling = true;
2423
+ console.warn(`♻️ [MEM] SOFT recycle: heapUsed ${usedMB}MB ≥ ${RECYCLE_SOFT_MB}MB and idle — stopping cleanly; next connect boots a fresh process and resumes`);
2424
+ setTimeout(() => process.exit(0), 1500); // exit(0): machine stops (same as idle-exit); next Resume boots fresh
2425
+ }
2371
2426
  }
2372
2427
  catch { /* probe must never break the agent */ }
2373
- }, 120_000).unref();
2428
+ }, 15_000).unref();
2374
2429
  // ── 0.9.83: Zombie-presence watchdog + event-loss adopter DELETED ──
2375
2430
  // Both poll-based layers existed solely to compensate for Room-reuse damage:
2376
2431
  // • zombie-watchdog: RoomEvent callbacks stopped firing after a leave/rejoin
@@ -65,7 +65,7 @@ export declare class PipelineDirectLLM extends llm.LLM {
65
65
  setAgents(a: any): void;
66
66
  setTurbo(on: boolean): void;
67
67
  prewarmResume(): void;
68
- getMemDebug(): Record<string, number>;
68
+ getMemDebug(): Record<string, string | number>;
69
69
  interruptAgent(): Promise<boolean>;
70
70
  abortAgent(): void;
71
71
  rewindAgent(checkpointId?: string): Promise<boolean>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.262",
3
+ "version": "0.9.264",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {