osborn 0.9.262 → 0.9.263

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
  */
@@ -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
@@ -1444,6 +1451,7 @@ export class ClaudeLLM extends llm.LLM {
1444
1451
  * the heap-OOM crashes (11x since 2026-10-02). Read-only — no behavior change.
1445
1452
  */
1446
1453
  getMemDebug() {
1454
+ const last = this.#memLastMsg;
1447
1455
  return {
1448
1456
  checkpoints: this.#checkpoints.length,
1449
1457
  tasksById: this.#tasksById.size,
@@ -1453,6 +1461,13 @@ export class ClaudeLLM extends llm.LLM {
1453
1461
  dispatchedFor: this.#dispatchedFor.size,
1454
1462
  busListeners: this.#eventEmitter.eventNames()
1455
1463
  .reduce((n, e) => n + this.#eventEmitter.listenerCount(e), 0),
1464
+ // v2 attribution: if heap creep tracks charsSeenMB, content flowing
1465
+ // through the consumer is being retained; a spike right after a huge
1466
+ // lastMsg names the allocator.
1467
+ msgCount: this.#memMsgCount,
1468
+ charsSeenMB: Math.round(this.#memCharsSeen / 1e6),
1469
+ maxMsgKB: Math.round(this.#memMaxMsgChars / 1e3),
1470
+ lastMsg: last ? `${last.type}${last.subtype ? '/' + last.subtype : ''}:${last.chars}ch@${Math.round((Date.now() - last.t) / 1000)}s` : 'none',
1456
1471
  };
1457
1472
  }
1458
1473
  /**
@@ -1853,6 +1868,23 @@ export class ClaudeLLM extends llm.LLM {
1853
1868
  try {
1854
1869
  for await (const message of pq) {
1855
1870
  const msg = message;
1871
+ // MEM probe v2: cheap attribution — count text chars (no stringify).
1872
+ {
1873
+ let chars = 0;
1874
+ const c = msg.message?.content;
1875
+ if (typeof c === 'string')
1876
+ chars = c.length;
1877
+ else if (Array.isArray(c))
1878
+ for (const b of c) {
1879
+ if (typeof b?.text === 'string')
1880
+ chars += b.text.length;
1881
+ }
1882
+ this.#memMsgCount++;
1883
+ this.#memCharsSeen += chars;
1884
+ if (chars > this.#memMaxMsgChars)
1885
+ this.#memMaxMsgChars = chars;
1886
+ this.#memLastMsg = { type: msg.type, subtype: msg.subtype, chars, t: Date.now() };
1887
+ }
1856
1888
  // Background-task lifecycle → registry (task_started/updated/notification).
1857
1889
  // This is what makes the per-flow stop button real: stopTask() needs the
1858
1890
  // task_id these messages carry.
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.263",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {