@astralyn/pi 0.87.0 → 0.87.1

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 (39) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/bundle/chunks/{anthropic-messages-R2LYJUDD.js → anthropic-messages-XWFTZP2N.js} +1 -1
  3. package/dist/bundle/chunks/{chunk-RKLIHRPH.js → chunk-772GXEFD.js} +18 -18
  4. package/dist/bundle/chunks/{chunk-INDBRWNK.js → chunk-CDMUKIXY.js} +1 -1
  5. package/dist/bundle/chunks/github-copilot.js +1 -1
  6. package/dist/bundle/chunks/{openai-completions-JZCEEJ43.js → openai-completions-SHS3CAEL.js} +1 -1
  7. package/dist/bundle/chunks/{virtual-modules-CG7NJ5WO.js → virtual-modules-LQO2MG3T.js} +1 -1
  8. package/dist/bundle/cli.js +1 -1
  9. package/dist/bundle/index.js +1 -1
  10. package/dist/bundle/rpc-entry.js +1 -1
  11. package/dist/cli/args.d.ts.map +1 -1
  12. package/dist/cli/args.js +14 -4
  13. package/dist/cli/args.js.map +1 -1
  14. package/dist/core/agent-session.d.ts +16 -0
  15. package/dist/core/agent-session.d.ts.map +1 -1
  16. package/dist/core/agent-session.js +81 -13
  17. package/dist/core/agent-session.js.map +1 -1
  18. package/dist/core/background/service.d.ts +9 -0
  19. package/dist/core/background/service.d.ts.map +1 -1
  20. package/dist/core/background/service.js +13 -1
  21. package/dist/core/background/service.js.map +1 -1
  22. package/dist/core/background/session.d.ts +5 -0
  23. package/dist/core/background/session.d.ts.map +1 -1
  24. package/dist/core/background/session.js +2 -1
  25. package/dist/core/background/session.js.map +1 -1
  26. package/dist/core/compaction/compaction.js +9 -9
  27. package/dist/core/compaction/compaction.js.map +1 -1
  28. package/dist/core/model-resolver.js +1 -1
  29. package/dist/core/model-resolver.js.map +1 -1
  30. package/docs/bundled/extensions/background.md +3 -3
  31. package/docs/bundled/extensions/subagent.md +1 -1
  32. package/docs/compaction.md +1 -1
  33. package/docs/sdk.md +1 -1
  34. package/docs/usage.md +3 -0
  35. package/examples/README.md +11 -1
  36. package/examples/rpc-client.ts +35 -0
  37. package/examples/rpc-extension-ui.ts +25 -5
  38. package/npm-shrinkwrap.json +43 -43
  39. package/package.json +8 -8
@@ -38,9 +38,18 @@ export declare class BackgroundService implements BackgroundContext {
38
38
  kill(id: string): boolean;
39
39
  private cancel;
40
40
  subscribe(listener: () => void): () => void;
41
+ /**
42
+ * Pins defer history eviction and completion delivery, so a live read or a watched row
43
+ * never races an automatic notification for the same record. Releasing resumes both, and
44
+ * announces the record only when that unblocks a delivery.
45
+ */
41
46
  pin(id: string): () => void;
42
47
  pause(): () => void;
43
48
  pendingNotifications(): BackgroundTask[];
49
+ /**
50
+ * A pinned record is being read or watched, so its completion is not announced yet:
51
+ * a terminal `bg wait` or `bg read` delivers the result as its own tool result instead.
52
+ */
44
53
  private candidate;
45
54
  claimNotification(id: string): boolean;
46
55
  markDelivered(id: string): void;
@@ -1 +1 @@
1
- {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/core/background/service.ts"],"names":[],"mappings":"AAMA,OAAO,EAEN,KAAK,iBAAiB,EAEtB,KAAK,mBAAmB,EAExB,KAAK,cAAc,EACnB,KAAK,wBAAwB,EAC7B,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAG1B,MAAM,YAAY,CAAC;AAmDpB,0FAA0F;AAC1F,qBAAa,iBAAkB,YAAW,iBAAiB;IAC1D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkC;IAC1D,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyB;IACnD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,iBAAiB,CAAU;IACnC,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA4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AAG,IAAI;IAQrC,KAAK,IAAI,IAAI;IAaP,QAAQ,CAAC,OAAO,SAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvC,mBAAmB,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;YAe1D,KAAK;IAcnB,OAAO,CAAC,QAAQ;IAIhB,OAAO,CAAC,aAAa;IAoBrB,0FAA0F;IAC1F,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,IAAI;IAqBZ,OAAO,CAAC,IAAI;CAWZ"}
@@ -448,6 +448,11 @@ export class BackgroundService {
448
448
  this.listeners.delete(listener);
449
449
  };
450
450
  }
451
+ /**
452
+ * Pins defer history eviction and completion delivery, so a live read or a watched row
453
+ * never races an automatic notification for the same record. Releasing resumes both, and
454
+ * announces the record only when that unblocks a delivery.
455
+ */
451
456
  pin(id) {
452
457
  const record = this.lookup(id);
453
458
  record.pins++;
@@ -458,6 +463,8 @@ export class BackgroundService {
458
463
  released = true;
459
464
  record.pins--;
460
465
  this.trim();
466
+ if (!this.closed && this.pauses === 0 && this.candidate(record))
467
+ this.emit();
461
468
  };
462
469
  }
463
470
  pause() {
@@ -478,6 +485,10 @@ export class BackgroundService {
478
485
  .filter((record) => this.candidate(record))
479
486
  .map((record) => this.snapshot(record));
480
487
  }
488
+ /**
489
+ * A pinned record is being read or watched, so its completion is not announced yet:
490
+ * a terminal `bg wait` or `bg read` delivers the result as its own tool result instead.
491
+ */
481
492
  candidate(record) {
482
493
  return (record.visible &&
483
494
  record.settled &&
@@ -485,7 +496,8 @@ export class BackgroundService {
485
496
  record.handedOff &&
486
497
  !record.suppressed &&
487
498
  record.delivery === "pending" &&
488
- record.waiters.size === 0);
499
+ record.waiters.size === 0 &&
500
+ record.pins === 0);
489
501
  }
490
502
  claimNotification(id) {
491
503
  if (this.closed || this.pauses > 0)
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/core/background/service.ts"],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AAC;QACD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC9B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACpC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;IACF,CAAC;IAEO,IAAI;QACX,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,KAAK,MAAM,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5C,IAAI,IAAI,CAAC,MAAM;gBAAE,MAAM;YACvB,IAAI,CAAC;gBACJ,QAAQ,EAAE,CAAC;YACZ,CAAC;YAAC,MAAM,CAAC;gBACR,iDAAiD;YAClD,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport { parseBackgroundHistory } from \"./history.ts\";\nimport { BACKGROUND_TITLE_BYTES, boundedResult, boundText, finiteLimit, readOutputSlice, sliceText } from \"./output.ts\";\nimport { readBackgroundProjection } from \"./presentation.ts\";\nimport {\n\ttype BackgroundCompletion,\n\ttype BackgroundContext,\n\ttype BackgroundControl,\n\ttype BackgroundExecution,\n\tBackgroundExecutionError,\n\ttype BackgroundRead,\n\ttype BackgroundServiceOptions,\n\ttype BackgroundTask,\n\ttype BackgroundToolOutcome,\n\tisForegroundShellTask,\n\tSUBAGENT_BACKGROUND_REJECTION,\n} from \"./types.ts\";\n\ninterface RecordState {\n\ttask: BackgroundTask;\n\tcontroller: AbortController;\n\taccepted: boolean;\n\thandedOff: boolean;\n\tdetachRequested: boolean;\n\tsettled: boolean;\n\taccounted: boolean;\n\tvisible: boolean;\n\tsuppressed: boolean;\n\tdelivery: \"pending\" | \"claimed\" | \"delivered\";\n\tpins: number;\n\tcleanup?: () => void | Promise<void>;\n\treadError?: string;\n\tpublishedUsage?: Usage;\n\twaiters: Set<() => void>;\n\tremoveParent: () => void;\n\thandoff: () => void;\n\tdone: Promise<void>;\n}\n\nfunction errorText(error: unknown): string {\n\ttry {\n\t\treturn boundText(error instanceof Error ? error.message : String(error), 4096);\n\t} catch {\n\t\treturn \"Background execution failed (unprintable error)\";\n\t}\n}\n\nfunction storeResult(task: BackgroundTask, result: AgentToolResult<unknown>, truncated = false): void {\n\tconst bounded = boundedResult(result);\n\ttask.result = bounded;\n\ttask.resultTruncated =\n\t\ttruncated ||\n\t\tbounded.content.length !== result.content.length ||\n\t\tbounded.content.some((block, index) => {\n\t\t\tconst original = result.content[index];\n\t\t\treturn original?.type !== \"text\" || block.type !== \"text\" || block.text !== original.text;\n\t\t});\n}\n\nfunction oldestTask(tasks: Iterable<BackgroundTask>): BackgroundTask | undefined {\n\tlet oldest: BackgroundTask | undefined;\n\tfor (const task of tasks) {\n\t\tif (!oldest || task.endedAt! < oldest.endedAt!) oldest = task;\n\t}\n\treturn oldest;\n}\n\n/** Session-local supervision. Executors own their processes, workers and output files. */\nexport class BackgroundService implements BackgroundContext {\n\tprivate readonly records = new Map<string, RecordState>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly maxActive: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\tprivate readonly cleanups = new Set<Promise<void>>();\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\tprivate pauses = 0;\n\n\tprivate readonly options: BackgroundServiceOptions;\n\n\tconstructor(options: BackgroundServiceOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground shell history, plus the existing history/protected-record allowance.\n\t\tthis.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t}\n\n\t/**\n\t * Rehydrate terminal version-2 custom data only, newest endedAt in each history\n\t * (later input wins ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored, including for worker projections.\n\t * The host supplies the current branch; closed services ignore restoration.\n\t */\n\trestoreHistory(records: readonly unknown[]): void {\n\t\tif (this.closed) return;\n\t\t// Restoration must not evict runtime-owned records or run their cleanup callbacks.\n\t\tconst history = this.historyRecords();\n\t\tconst shells = history.filter((record) => isForegroundShellTask(record.task)).length;\n\t\tconst shellCapacity = Math.max(0, this.maxHistory - shells);\n\t\tconst taskCapacity = Math.max(0, this.maxHistory - (history.length - shells));\n\t\tconst capacity = Math.max(\n\t\t\t0,\n\t\t\tMath.min(shellCapacity + taskCapacity, this.maxRetained - this.records.size - this.cleanups.size),\n\t\t);\n\t\tconst newest = new Map<string, BackgroundTask>();\n\t\tfor (const value of records) {\n\t\t\tconst task = parseBackgroundHistory(value);\n\t\t\tif (!task) continue;\n\t\t\tconst existing = this.records.get(task.id);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.settled) existing.visible = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (capacity === 0) continue;\n\t\t\tconst previous = newest.get(task.id);\n\t\t\tif (previous && previous.endedAt! > task.endedAt!) continue;\n\t\t\tnewest.delete(task.id);\n\t\t\tconst shell = isForegroundShellTask(task);\n\t\t\tconst limit = shell ? shellCapacity : taskCapacity;\n\t\t\tif (limit === 0) continue;\n\t\t\tnewest.set(task.id, task);\n\t\t\tconst group = [...newest.values()].filter((candidate) => isForegroundShellTask(candidate) === shell);\n\t\t\tif (group.length > limit) newest.delete(oldestTask(group)!.id);\n\t\t\tif (newest.size > capacity) {\n\t\t\t\t// Protected runtime records can leave less room than both histories allow.\n\t\t\t\t// Restore inspectable tasks before hidden foreground shell logs in that case.\n\t\t\t\tconst foreground = [...newest.values()].filter(isForegroundShellTask);\n\t\t\t\tnewest.delete(oldestTask(foreground.length ? foreground : newest.values())!.id);\n\t\t\t}\n\t\t}\n\t\tfor (const task of [...newest.values()].sort((a, b) => a.endedAt! - b.endedAt!)) {\n\t\t\tthis.records.set(task.id, {\n\t\t\t\ttask,\n\t\t\t\tcontroller: new AbortController(),\n\t\t\t\taccepted: false,\n\t\t\t\thandedOff: false,\n\t\t\t\tdetachRequested: false,\n\t\t\t\tsettled: true,\n\t\t\t\taccounted: true,\n\t\t\t\tvisible: true,\n\t\t\t\tsuppressed: true,\n\t\t\t\tdelivery: \"delivered\",\n\t\t\t\tpins: 0,\n\t\t\t\twaiters: new Set(),\n\t\t\t\tremoveParent: () => {},\n\t\t\t\thandoff: () => {},\n\t\t\t\tdone: Promise.resolve(),\n\t\t\t});\n\t\t}\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.role !== \"subagent\";\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\tasync execute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (this.options.role === \"subagent\") throw new Error(SUBAGENT_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Background service is closed\");\n\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif ([...this.records.values()].filter((record) => !record.settled).length >= this.maxActive) {\n\t\t\tthrow new Error(`Background execution limit reached (${this.maxActive})`);\n\t\t}\n\t\tif (this.records.size + this.cleanups.size >= this.maxRetained) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Background history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t);\n\t\t}\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192)\n\t\t\tthrow new Error(\"Background branch anchor is too large\");\n\t\tconst task: BackgroundTask = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\ttitle: boundText(execution.title, BACKGROUND_TITLE_BYTES),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t\tcommand: execution.command === undefined ? undefined : boundText(execution.command, 8192),\n\t\t\tcommandTruncated:\n\t\t\t\texecution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,\n\t\t\tcwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),\n\t\t};\n\t\tlet resolveCaller!: (outcome: BackgroundToolOutcome<T>) => void;\n\t\tlet rejectCaller!: (error: unknown) => void;\n\t\tconst caller = new Promise<BackgroundToolOutcome<T>>((resolve, reject) => {\n\t\t\tresolveCaller = resolve;\n\t\t\trejectCaller = reject;\n\t\t});\n\t\tlet resolveDone!: () => void;\n\t\tconst record: RecordState = {\n\t\t\ttask,\n\t\t\tcontroller: new AbortController(),\n\t\t\taccepted: false,\n\t\t\thandedOff: false,\n\t\t\tdetachRequested: execution.background ?? false,\n\t\t\tsettled: false,\n\t\t\taccounted: false,\n\t\t\tvisible: true,\n\t\t\tsuppressed: false,\n\t\t\tdelivery: \"pending\",\n\t\t\tpins: 0,\n\t\t\twaiters: new Set(),\n\t\t\tremoveParent: () => {},\n\t\t\thandoff: () => {\n\t\t\t\tif (\n\t\t\t\t\t!record.accepted ||\n\t\t\t\t\t!record.detachRequested ||\n\t\t\t\t\trecord.settled ||\n\t\t\t\t\trecord.handedOff ||\n\t\t\t\t\tthis.closed ||\n\t\t\t\t\trecord.suppressed ||\n\t\t\t\t\trecord.controller.signal.aborted\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\trecord.handedOff = true;\n\t\t\t\ttask.mode = \"background\";\n\t\t\t\trecord.removeParent();\n\t\t\t\tresolveCaller({ kind: \"background\", task: this.snapshot(record) });\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tdone: new Promise<void>((resolve) => {\n\t\t\t\tresolveDone = resolve;\n\t\t\t}),\n\t\t};\n\t\tconst parentSignal = execution.signal;\n\t\tlet onUpdate = execution.background ? undefined : execution.onUpdate;\n\t\tconst parentAbort = () => {\n\t\t\tif (!record.detachRequested || !record.accepted) this.cancel(record);\n\t\t};\n\t\tparentSignal?.addEventListener(\"abort\", parentAbort, { once: true });\n\t\trecord.removeParent = () => {\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbort);\n\t\t\tonUpdate = undefined;\n\t\t};\n\t\tthis.records.set(task.id, record);\n\t\tconst control: BackgroundControl<T> = {\n\t\t\tid: task.id,\n\t\t\tsignal: record.controller.signal,\n\t\t\tget mode() {\n\t\t\t\treturn task.mode;\n\t\t\t},\n\t\t\taccept: () => {\n\t\t\t\tif (record.settled || record.accepted || this.closed || record.controller.signal.aborted) return;\n\t\t\t\trecord.accepted = true;\n\t\t\t\tif (task.status === \"queued\") task.status = \"running\";\n\t\t\t\tif (record.detachRequested) record.removeParent();\n\t\t\t\t// Let an already available final result win over a handoff.\n\t\t\t\tqueueMicrotask(() => queueMicrotask(record.handoff));\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tpublish: (result, projection) => {\n\t\t\t\tif (record.settled || this.closed) return;\n\t\t\t\tstoreResult(task, result);\n\t\t\t\tif (result.usage !== undefined) record.publishedUsage = structuredClone(result.usage);\n\t\t\t\tif (projection) task.projection = readBackgroundProjection(projection);\n\t\t\t\tif (!record.detachRequested && !record.handedOff) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonUpdate?.(result);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* UI observers cannot stop execution. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tsetOutputPath: (path, cleanup) => {\n\t\t\t\tif (record.settled) {\n\t\t\t\t\tif (cleanup) throw new Error(\"Background execution has settled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (record.cleanup) throw new Error(\"Managed output is already registered\");\n\t\t\t\t// Never truncate a real filesystem path into a different path.\n\t\t\t\tif (Buffer.byteLength(path) > 8192) throw new Error(\"Background output path is too large\");\n\t\t\t\trecord.cleanup = cleanup;\n\t\t\t\ttask.outputPath = path;\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t\tconst finish = (completion: BackgroundCompletion<T> | undefined, error?: unknown) => {\n\t\t\tif (record.settled) return;\n\t\t\trecord.settled = true;\n\t\t\trecord.removeParent();\n\t\t\ttask.endedAt = Date.now();\n\t\t\tconst failed = completion === undefined;\n\t\t\ttask.status =\n\t\t\t\tcompletion?.status ??\n\t\t\t\t(error instanceof BackgroundExecutionError\n\t\t\t\t\t? error.status\n\t\t\t\t\t: record.controller.signal.aborted\n\t\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t\t: failed\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"completed\");\n\t\t\tif (completion) {\n\t\t\t\tstoreResult(task, completion.result);\n\t\t\t\tif (completion.error !== undefined) task.error = boundText(completion.error, 4096);\n\t\t\t\tif (completion.exitCode !== undefined) task.exitCode = completion.exitCode;\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\ttask.error = errorText(error);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: task.error }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet settlementWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tthis.options.onSettled?.(\n\t\t\t\t\tthis.snapshot(record),\n\t\t\t\t\tcompletion?.usage ?? completion?.result.usage ?? record.publishedUsage,\n\t\t\t\t);\n\t\t\t} catch (accountingError) {\n\t\t\t\tconst warning = `Usage settlement failed: ${errorText(accountingError)}`;\n\t\t\t\tsettlementWarning = warning;\n\t\t\t\ttask.error = boundText([task.error, warning].filter(Boolean).join(\"\\n\"), 8192);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: warning }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\trecord.publishedUsage = undefined;\n\t\t\trecord.accounted = true;\n\t\t\tif (!record.handedOff) {\n\t\t\t\trecord.delivery = \"delivered\";\n\t\t\t\tif (failed) rejectCaller(error);\n\t\t\t\telse {\n\t\t\t\t\tconst { usage: _usage, ...result } = completion.result;\n\t\t\t\t\tif (settlementWarning) result.content = [{ type: \"text\", text: settlementWarning }, ...result.content];\n\t\t\t\t\tresolveCaller({ kind: \"result\", result, status: task.status, error: task.error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t\tresolveDone();\n\t\t\tthis.trim();\n\t\t\tthis.emit();\n\t\t};\n\t\t// The rejection handler is installed immediately, including for synchronous preflight throws.\n\t\ttry {\n\t\t\tconst running = execution.run(control);\n\t\t\tvoid Promise.resolve(running).then(\n\t\t\t\t(result) => finish(result),\n\t\t\t\t(error: unknown) => finish(undefined, error),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfinish(undefined, error);\n\t\t}\n\t\tthis.emit();\n\t\treturn caller;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst records = [...this.records.values()].filter(\n\t\t\t(record) => !record.settled && !record.detachRequested && !record.controller.signal.aborted,\n\t\t);\n\t\t// Update the whole batch before callbacks/observers can re-enter.\n\t\tfor (const record of records) {\n\t\t\trecord.detachRequested = true;\n\t\t\trecord.task.mode = \"background\";\n\t\t\tif (record.accepted) record.removeParent();\n\t\t}\n\t\tfor (const record of records) record.handoff();\n\t\tif (records.length) this.emit();\n\t\treturn records.length;\n\t}\n\n\tlist(): BackgroundTask[] {\n\t\treturn [...this.records.values()].filter((record) => record.visible).map((record) => this.snapshot(record));\n\t}\n\n\tprivate lookup(id: string): RecordState {\n\t\tconst exact = this.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.records.values()].filter(\n\t\t\t({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id),\n\t\t);\n\t\tif (!id || matches.length !== 1)\n\t\t\tthrow new Error(matches.length > 1 ? \"Ambiguous background task ID\" : \"Unknown background task ID\");\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): BackgroundTask {\n\t\treturn this.snapshot(this.lookup(id));\n\t}\n\n\tasync read(\n\t\tid: string,\n\t\toptions: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number } = {},\n\t): Promise<BackgroundRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.pin(record.task.id);\n\t\ttry {\n\t\t\tconst task = this.snapshot(record);\n\t\t\tif (task.outputPath) {\n\t\t\t\ttry {\n\t\t\t\t\treturn { task, ...(await readOutputSlice(task.outputPath, options)) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\treadError: boundText(`Output could not be read: ${errorText(error)}`, 4096),\n\t\t\t\t\t\t...sliceText(this.resultText(task), options),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { task, readError: record.readError, ...sliceText(this.resultText(task), options) };\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tprivate resultText(task: BackgroundTask): string {\n\t\treturn boundText(\n\t\t\ttask.result?.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\ttask.projection?.text ||\n\t\t\t\ttask.error ||\n\t\t\t\t\"No output yet.\",\n\t\t);\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(id: string, timeoutMs = 20_000, signal?: AbortSignal): Promise<BackgroundTask> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tif (record.settled) return this.snapshot(record);\n\t\treturn new Promise<BackgroundTask>((resolve, reject) => {\n\t\t\tlet finished = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst complete = (aborted = false) => {\n\t\t\t\tif (finished) return;\n\t\t\t\tfinished = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\t\trecord.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve(this.snapshot(record));\n\t\t\t\tthis.trim();\n\t\t\t\tthis.emit();\n\t\t\t};\n\t\t\tconst wake = () => complete();\n\t\t\tconst abort = () => complete(true);\n\t\t\trecord.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, 20_000, 60_000));\n\t\t\tif (this.closed) wake();\n\t\t});\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: RecordState): boolean {\n\t\tif (record.settled || record.controller.signal.aborted) return false;\n\t\trecord.task.status = \"stopping\";\n\t\trecord.controller.abort();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tpin(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\trecord.pins++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.pins--;\n\t\t\tthis.trim();\n\t\t};\n\t}\n\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tlet resumed = false;\n\t\treturn () => {\n\t\t\tif (resumed) return;\n\t\t\tresumed = true;\n\t\t\tthis.pauses--;\n\t\t\tthis.emit();\n\t\t};\n\t}\n\n\tpendingNotifications(): BackgroundTask[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.records.values()]\n\t\t\t.filter((record) => this.candidate(record))\n\t\t\t.map((record) => this.snapshot(record));\n\t}\n\n\tprivate candidate(record: RecordState): boolean {\n\t\treturn (\n\t\t\trecord.visible &&\n\t\t\trecord.settled &&\n\t\t\trecord.accounted &&\n\t\t\trecord.handedOff &&\n\t\t\t!record.suppressed &&\n\t\t\trecord.delivery === \"pending\" &&\n\t\t\trecord.waiters.size === 0\n\t\t);\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.records.get(id);\n\t\tif (!record || !this.candidate(record)) return false;\n\t\trecord.delivery = \"claimed\";\n\t\treturn true;\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.trim();\n\t\tthis.emit();\n\t}\n\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis._closed = true;\n\t\tthis.listeners.clear();\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.suppressed = true;\n\t\t\trecord.removeParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.records.values()], graceMs);\n\t}\n\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\t\t// Returning to a branch revives its undelivered completions; restored history\n\t\t\t// stays delivered and suppressed.\n\t\t\tif (record.visible && record.delivery === \"pending\") record.suppressed = false;\n\t\t}\n\t\tconst outside = [...this.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) record.suppressed = true;\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: RecordState[], graceMs: number): Promise<void> {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tPromise.all(records.map((record) => record.done)).then(() => Promise.all(this.cleanups)),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, finiteLimit(graceMs, 2000, 60_000));\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate snapshot(record: RecordState): BackgroundTask {\n\t\treturn structuredClone(record.task);\n\t}\n\n\tprivate cleanupOutput(record: RecordState): void {\n\t\tif (!record.settled || record.pins || record.waiters.size || !record.cleanup) return;\n\t\tconst cleanup = record.cleanup;\n\t\trecord.cleanup = undefined;\n\t\t// Snapshots retain final bounded text; expired files are never needed to render history.\n\t\trecord.task.outputPath = undefined;\n\t\trecord.readError = \"Output has expired: the managed log was released; showing the stored result.\";\n\t\tconst pending = Promise.resolve()\n\t\t\t.then(cleanup)\n\t\t\t.catch((error: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.onCleanupError?.(errorText(error));\n\t\t\t\t} catch {\n\t\t\t\t\t/* Cleanup/reporting is best effort, never an unhandled rejection. */\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => this.cleanups.delete(pending));\n\t\tthis.cleanups.add(pending);\n\t}\n\n\t/** Pending delivery, active reads and pins have their own bounded retention allowance. */\n\tprivate historyRecords(): RecordState[] {\n\t\treturn [...this.records.values()].filter(\n\t\t\t(record) => record.settled && record.delivery === \"delivered\" && !record.pins && !record.waiters.size,\n\t\t);\n\t}\n\n\tprivate trim(): void {\n\t\tif (this.closed) {\n\t\t\tfor (const record of this.records.values()) this.cleanupOutput(record);\n\t\t\treturn;\n\t\t}\n\t\t// Undelivered notifications and claims are never evicted. Admission bounds all retention.\n\t\tconst history = this.historyRecords();\n\t\t// Delivered history can be restored from branch snapshots; hidden rows must\n\t\t// not occupy the current branch's history budget. Pending results stay owned.\n\t\tconst expired = history.filter((record) => !record.visible);\n\t\tfor (const shell of [false, true]) {\n\t\t\tconst group = history.filter((record) => record.visible && isForegroundShellTask(record.task) === shell);\n\t\t\tgroup.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0));\n\t\t\texpired.push(...group.slice(0, Math.max(0, group.length - this.maxHistory)));\n\t\t}\n\t\tfor (const record of expired) {\n\t\t\tthis.records.delete(record.task.id);\n\t\t\tthis.cleanupOutput(record);\n\t\t}\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.closed) return;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (this.closed) break;\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Observers do not own execution or delivery. */\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/core/background/service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,SAA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AAG,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC9E,CAAC;QACD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC9B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACpC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;QAC5B,CAAC;IACF,CAAC;IAEO,IAAI;QACX,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,KAAK,MAAM,QAAQ,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;YAC5C,IAAI,IAAI,CAAC,MAAM;gBAAE,MAAM;YACvB,IAAI,CAAC;gBACJ,QAAQ,EAAE,CAAC;YACZ,CAAC;YAAC,MAAM,CAAC;gBACR,iDAAiD;YAClD,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport { parseBackgroundHistory } from \"./history.ts\";\nimport { BACKGROUND_TITLE_BYTES, boundedResult, boundText, finiteLimit, readOutputSlice, sliceText } from \"./output.ts\";\nimport { readBackgroundProjection } from \"./presentation.ts\";\nimport {\n\ttype BackgroundCompletion,\n\ttype BackgroundContext,\n\ttype BackgroundControl,\n\ttype BackgroundExecution,\n\tBackgroundExecutionError,\n\ttype BackgroundRead,\n\ttype BackgroundServiceOptions,\n\ttype BackgroundTask,\n\ttype BackgroundToolOutcome,\n\tisForegroundShellTask,\n\tSUBAGENT_BACKGROUND_REJECTION,\n} from \"./types.ts\";\n\ninterface RecordState {\n\ttask: BackgroundTask;\n\tcontroller: AbortController;\n\taccepted: boolean;\n\thandedOff: boolean;\n\tdetachRequested: boolean;\n\tsettled: boolean;\n\taccounted: boolean;\n\tvisible: boolean;\n\tsuppressed: boolean;\n\tdelivery: \"pending\" | \"claimed\" | \"delivered\";\n\tpins: number;\n\tcleanup?: () => void | Promise<void>;\n\treadError?: string;\n\tpublishedUsage?: Usage;\n\twaiters: Set<() => void>;\n\tremoveParent: () => void;\n\thandoff: () => void;\n\tdone: Promise<void>;\n}\n\nfunction errorText(error: unknown): string {\n\ttry {\n\t\treturn boundText(error instanceof Error ? error.message : String(error), 4096);\n\t} catch {\n\t\treturn \"Background execution failed (unprintable error)\";\n\t}\n}\n\nfunction storeResult(task: BackgroundTask, result: AgentToolResult<unknown>, truncated = false): void {\n\tconst bounded = boundedResult(result);\n\ttask.result = bounded;\n\ttask.resultTruncated =\n\t\ttruncated ||\n\t\tbounded.content.length !== result.content.length ||\n\t\tbounded.content.some((block, index) => {\n\t\t\tconst original = result.content[index];\n\t\t\treturn original?.type !== \"text\" || block.type !== \"text\" || block.text !== original.text;\n\t\t});\n}\n\nfunction oldestTask(tasks: Iterable<BackgroundTask>): BackgroundTask | undefined {\n\tlet oldest: BackgroundTask | undefined;\n\tfor (const task of tasks) {\n\t\tif (!oldest || task.endedAt! < oldest.endedAt!) oldest = task;\n\t}\n\treturn oldest;\n}\n\n/** Session-local supervision. Executors own their processes, workers and output files. */\nexport class BackgroundService implements BackgroundContext {\n\tprivate readonly records = new Map<string, RecordState>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly maxActive: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\tprivate readonly cleanups = new Set<Promise<void>>();\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\tprivate pauses = 0;\n\n\tprivate readonly options: BackgroundServiceOptions;\n\n\tconstructor(options: BackgroundServiceOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground shell history, plus the existing history/protected-record allowance.\n\t\tthis.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t}\n\n\t/**\n\t * Rehydrate terminal version-2 custom data only, newest endedAt in each history\n\t * (later input wins ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored, including for worker projections.\n\t * The host supplies the current branch; closed services ignore restoration.\n\t */\n\trestoreHistory(records: readonly unknown[]): void {\n\t\tif (this.closed) return;\n\t\t// Restoration must not evict runtime-owned records or run their cleanup callbacks.\n\t\tconst history = this.historyRecords();\n\t\tconst shells = history.filter((record) => isForegroundShellTask(record.task)).length;\n\t\tconst shellCapacity = Math.max(0, this.maxHistory - shells);\n\t\tconst taskCapacity = Math.max(0, this.maxHistory - (history.length - shells));\n\t\tconst capacity = Math.max(\n\t\t\t0,\n\t\t\tMath.min(shellCapacity + taskCapacity, this.maxRetained - this.records.size - this.cleanups.size),\n\t\t);\n\t\tconst newest = new Map<string, BackgroundTask>();\n\t\tfor (const value of records) {\n\t\t\tconst task = parseBackgroundHistory(value);\n\t\t\tif (!task) continue;\n\t\t\tconst existing = this.records.get(task.id);\n\t\t\tif (existing) {\n\t\t\t\tif (existing.settled) existing.visible = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (capacity === 0) continue;\n\t\t\tconst previous = newest.get(task.id);\n\t\t\tif (previous && previous.endedAt! > task.endedAt!) continue;\n\t\t\tnewest.delete(task.id);\n\t\t\tconst shell = isForegroundShellTask(task);\n\t\t\tconst limit = shell ? shellCapacity : taskCapacity;\n\t\t\tif (limit === 0) continue;\n\t\t\tnewest.set(task.id, task);\n\t\t\tconst group = [...newest.values()].filter((candidate) => isForegroundShellTask(candidate) === shell);\n\t\t\tif (group.length > limit) newest.delete(oldestTask(group)!.id);\n\t\t\tif (newest.size > capacity) {\n\t\t\t\t// Protected runtime records can leave less room than both histories allow.\n\t\t\t\t// Restore inspectable tasks before hidden foreground shell logs in that case.\n\t\t\t\tconst foreground = [...newest.values()].filter(isForegroundShellTask);\n\t\t\t\tnewest.delete(oldestTask(foreground.length ? foreground : newest.values())!.id);\n\t\t\t}\n\t\t}\n\t\tfor (const task of [...newest.values()].sort((a, b) => a.endedAt! - b.endedAt!)) {\n\t\t\tthis.records.set(task.id, {\n\t\t\t\ttask,\n\t\t\t\tcontroller: new AbortController(),\n\t\t\t\taccepted: false,\n\t\t\t\thandedOff: false,\n\t\t\t\tdetachRequested: false,\n\t\t\t\tsettled: true,\n\t\t\t\taccounted: true,\n\t\t\t\tvisible: true,\n\t\t\t\tsuppressed: true,\n\t\t\t\tdelivery: \"delivered\",\n\t\t\t\tpins: 0,\n\t\t\t\twaiters: new Set(),\n\t\t\t\tremoveParent: () => {},\n\t\t\t\thandoff: () => {},\n\t\t\t\tdone: Promise.resolve(),\n\t\t\t});\n\t\t}\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.role !== \"subagent\";\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\tasync execute<T>(execution: BackgroundExecution<T>): Promise<BackgroundToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (this.options.role === \"subagent\") throw new Error(SUBAGENT_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Background service is closed\");\n\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif ([...this.records.values()].filter((record) => !record.settled).length >= this.maxActive) {\n\t\t\tthrow new Error(`Background execution limit reached (${this.maxActive})`);\n\t\t}\n\t\tif (this.records.size + this.cleanups.size >= this.maxRetained) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Background history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t);\n\t\t}\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192)\n\t\t\tthrow new Error(\"Background branch anchor is too large\");\n\t\tconst task: BackgroundTask = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\ttitle: boundText(execution.title, BACKGROUND_TITLE_BYTES),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t\tcommand: execution.command === undefined ? undefined : boundText(execution.command, 8192),\n\t\t\tcommandTruncated:\n\t\t\t\texecution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,\n\t\t\tcwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),\n\t\t};\n\t\tlet resolveCaller!: (outcome: BackgroundToolOutcome<T>) => void;\n\t\tlet rejectCaller!: (error: unknown) => void;\n\t\tconst caller = new Promise<BackgroundToolOutcome<T>>((resolve, reject) => {\n\t\t\tresolveCaller = resolve;\n\t\t\trejectCaller = reject;\n\t\t});\n\t\tlet resolveDone!: () => void;\n\t\tconst record: RecordState = {\n\t\t\ttask,\n\t\t\tcontroller: new AbortController(),\n\t\t\taccepted: false,\n\t\t\thandedOff: false,\n\t\t\tdetachRequested: execution.background ?? false,\n\t\t\tsettled: false,\n\t\t\taccounted: false,\n\t\t\tvisible: true,\n\t\t\tsuppressed: false,\n\t\t\tdelivery: \"pending\",\n\t\t\tpins: 0,\n\t\t\twaiters: new Set(),\n\t\t\tremoveParent: () => {},\n\t\t\thandoff: () => {\n\t\t\t\tif (\n\t\t\t\t\t!record.accepted ||\n\t\t\t\t\t!record.detachRequested ||\n\t\t\t\t\trecord.settled ||\n\t\t\t\t\trecord.handedOff ||\n\t\t\t\t\tthis.closed ||\n\t\t\t\t\trecord.suppressed ||\n\t\t\t\t\trecord.controller.signal.aborted\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\trecord.handedOff = true;\n\t\t\t\ttask.mode = \"background\";\n\t\t\t\trecord.removeParent();\n\t\t\t\tresolveCaller({ kind: \"background\", task: this.snapshot(record) });\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tdone: new Promise<void>((resolve) => {\n\t\t\t\tresolveDone = resolve;\n\t\t\t}),\n\t\t};\n\t\tconst parentSignal = execution.signal;\n\t\tlet onUpdate = execution.background ? undefined : execution.onUpdate;\n\t\tconst parentAbort = () => {\n\t\t\tif (!record.detachRequested || !record.accepted) this.cancel(record);\n\t\t};\n\t\tparentSignal?.addEventListener(\"abort\", parentAbort, { once: true });\n\t\trecord.removeParent = () => {\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbort);\n\t\t\tonUpdate = undefined;\n\t\t};\n\t\tthis.records.set(task.id, record);\n\t\tconst control: BackgroundControl<T> = {\n\t\t\tid: task.id,\n\t\t\tsignal: record.controller.signal,\n\t\t\tget mode() {\n\t\t\t\treturn task.mode;\n\t\t\t},\n\t\t\taccept: () => {\n\t\t\t\tif (record.settled || record.accepted || this.closed || record.controller.signal.aborted) return;\n\t\t\t\trecord.accepted = true;\n\t\t\t\tif (task.status === \"queued\") task.status = \"running\";\n\t\t\t\tif (record.detachRequested) record.removeParent();\n\t\t\t\t// Let an already available final result win over a handoff.\n\t\t\t\tqueueMicrotask(() => queueMicrotask(record.handoff));\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tpublish: (result, projection) => {\n\t\t\t\tif (record.settled || this.closed) return;\n\t\t\t\tstoreResult(task, result);\n\t\t\t\tif (result.usage !== undefined) record.publishedUsage = structuredClone(result.usage);\n\t\t\t\tif (projection) task.projection = readBackgroundProjection(projection);\n\t\t\t\tif (!record.detachRequested && !record.handedOff) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonUpdate?.(result);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* UI observers cannot stop execution. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tsetOutputPath: (path, cleanup) => {\n\t\t\t\tif (record.settled) {\n\t\t\t\t\tif (cleanup) throw new Error(\"Background execution has settled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (record.cleanup) throw new Error(\"Managed output is already registered\");\n\t\t\t\t// Never truncate a real filesystem path into a different path.\n\t\t\t\tif (Buffer.byteLength(path) > 8192) throw new Error(\"Background output path is too large\");\n\t\t\t\trecord.cleanup = cleanup;\n\t\t\t\ttask.outputPath = path;\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t\tconst finish = (completion: BackgroundCompletion<T> | undefined, error?: unknown) => {\n\t\t\tif (record.settled) return;\n\t\t\trecord.settled = true;\n\t\t\trecord.removeParent();\n\t\t\ttask.endedAt = Date.now();\n\t\t\tconst failed = completion === undefined;\n\t\t\ttask.status =\n\t\t\t\tcompletion?.status ??\n\t\t\t\t(error instanceof BackgroundExecutionError\n\t\t\t\t\t? error.status\n\t\t\t\t\t: record.controller.signal.aborted\n\t\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t\t: failed\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"completed\");\n\t\t\tif (completion) {\n\t\t\t\tstoreResult(task, completion.result);\n\t\t\t\tif (completion.error !== undefined) task.error = boundText(completion.error, 4096);\n\t\t\t\tif (completion.exitCode !== undefined) task.exitCode = completion.exitCode;\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\ttask.error = errorText(error);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: task.error }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\tlet settlementWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tthis.options.onSettled?.(\n\t\t\t\t\tthis.snapshot(record),\n\t\t\t\t\tcompletion?.usage ?? completion?.result.usage ?? record.publishedUsage,\n\t\t\t\t);\n\t\t\t} catch (accountingError) {\n\t\t\t\tconst warning = `Usage settlement failed: ${errorText(accountingError)}`;\n\t\t\t\tsettlementWarning = warning;\n\t\t\t\ttask.error = boundText([task.error, warning].filter(Boolean).join(\"\\n\"), 8192);\n\t\t\t\tstoreResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: warning }, ...(task.result?.content ?? [])],\n\t\t\t\t\t\tdetails: task.result?.details,\n\t\t\t\t\t},\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\trecord.publishedUsage = undefined;\n\t\t\trecord.accounted = true;\n\t\t\tif (!record.handedOff) {\n\t\t\t\trecord.delivery = \"delivered\";\n\t\t\t\tif (failed) rejectCaller(error);\n\t\t\t\telse {\n\t\t\t\t\tconst { usage: _usage, ...result } = completion.result;\n\t\t\t\t\tif (settlementWarning) result.content = [{ type: \"text\", text: settlementWarning }, ...result.content];\n\t\t\t\t\tresolveCaller({ kind: \"result\", result, status: task.status, error: task.error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t\tresolveDone();\n\t\t\tthis.trim();\n\t\t\tthis.emit();\n\t\t};\n\t\t// The rejection handler is installed immediately, including for synchronous preflight throws.\n\t\ttry {\n\t\t\tconst running = execution.run(control);\n\t\t\tvoid Promise.resolve(running).then(\n\t\t\t\t(result) => finish(result),\n\t\t\t\t(error: unknown) => finish(undefined, error),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfinish(undefined, error);\n\t\t}\n\t\tthis.emit();\n\t\treturn caller;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst records = [...this.records.values()].filter(\n\t\t\t(record) => !record.settled && !record.detachRequested && !record.controller.signal.aborted,\n\t\t);\n\t\t// Update the whole batch before callbacks/observers can re-enter.\n\t\tfor (const record of records) {\n\t\t\trecord.detachRequested = true;\n\t\t\trecord.task.mode = \"background\";\n\t\t\tif (record.accepted) record.removeParent();\n\t\t}\n\t\tfor (const record of records) record.handoff();\n\t\tif (records.length) this.emit();\n\t\treturn records.length;\n\t}\n\n\tlist(): BackgroundTask[] {\n\t\treturn [...this.records.values()].filter((record) => record.visible).map((record) => this.snapshot(record));\n\t}\n\n\tprivate lookup(id: string): RecordState {\n\t\tconst exact = this.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.records.values()].filter(\n\t\t\t({ task }) => task.id.startsWith(id) || task.id.slice(task.kind.length + 1).startsWith(id),\n\t\t);\n\t\tif (!id || matches.length !== 1)\n\t\t\tthrow new Error(matches.length > 1 ? \"Ambiguous background task ID\" : \"Unknown background task ID\");\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): BackgroundTask {\n\t\treturn this.snapshot(this.lookup(id));\n\t}\n\n\tasync read(\n\t\tid: string,\n\t\toptions: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number } = {},\n\t): Promise<BackgroundRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.pin(record.task.id);\n\t\ttry {\n\t\t\tconst task = this.snapshot(record);\n\t\t\tif (task.outputPath) {\n\t\t\t\ttry {\n\t\t\t\t\treturn { task, ...(await readOutputSlice(task.outputPath, options)) };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttask,\n\t\t\t\t\t\treadError: boundText(`Output could not be read: ${errorText(error)}`, 4096),\n\t\t\t\t\t\t...sliceText(this.resultText(task), options),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { task, readError: record.readError, ...sliceText(this.resultText(task), options) };\n\t\t} finally {\n\t\t\trelease();\n\t\t}\n\t}\n\n\tprivate resultText(task: BackgroundTask): string {\n\t\treturn boundText(\n\t\t\ttask.result?.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\ttask.projection?.text ||\n\t\t\t\ttask.error ||\n\t\t\t\t\"No output yet.\",\n\t\t);\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(id: string, timeoutMs = 20_000, signal?: AbortSignal): Promise<BackgroundTask> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tif (record.settled) return this.snapshot(record);\n\t\treturn new Promise<BackgroundTask>((resolve, reject) => {\n\t\t\tlet finished = false;\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst complete = (aborted = false) => {\n\t\t\t\tif (finished) return;\n\t\t\t\tfinished = true;\n\t\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t\t\tsignal?.removeEventListener(\"abort\", abort);\n\t\t\t\trecord.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve(this.snapshot(record));\n\t\t\t\tthis.trim();\n\t\t\t\tthis.emit();\n\t\t\t};\n\t\t\tconst wake = () => complete();\n\t\t\tconst abort = () => complete(true);\n\t\t\trecord.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, 20_000, 60_000));\n\t\t\tif (this.closed) wake();\n\t\t});\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: RecordState): boolean {\n\t\tif (record.settled || record.controller.signal.aborted) return false;\n\t\trecord.task.status = \"stopping\";\n\t\trecord.controller.abort();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * Pins defer history eviction and completion delivery, so a live read or a watched row\n\t * never races an automatic notification for the same record. Releasing resumes both, and\n\t * announces the record only when that unblocks a delivery.\n\t */\n\tpin(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\trecord.pins++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.pins--;\n\t\t\tthis.trim();\n\t\t\tif (!this.closed && this.pauses === 0 && this.candidate(record)) this.emit();\n\t\t};\n\t}\n\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tlet resumed = false;\n\t\treturn () => {\n\t\t\tif (resumed) return;\n\t\t\tresumed = true;\n\t\t\tthis.pauses--;\n\t\t\tthis.emit();\n\t\t};\n\t}\n\n\tpendingNotifications(): BackgroundTask[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.records.values()]\n\t\t\t.filter((record) => this.candidate(record))\n\t\t\t.map((record) => this.snapshot(record));\n\t}\n\n\t/**\n\t * A pinned record is being read or watched, so its completion is not announced yet:\n\t * a terminal `bg wait` or `bg read` delivers the result as its own tool result instead.\n\t */\n\tprivate candidate(record: RecordState): boolean {\n\t\treturn (\n\t\t\trecord.visible &&\n\t\t\trecord.settled &&\n\t\t\trecord.accounted &&\n\t\t\trecord.handedOff &&\n\t\t\t!record.suppressed &&\n\t\t\trecord.delivery === \"pending\" &&\n\t\t\trecord.waiters.size === 0 &&\n\t\t\trecord.pins === 0\n\t\t);\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.records.get(id);\n\t\tif (!record || !this.candidate(record)) return false;\n\t\trecord.delivery = \"claimed\";\n\t\treturn true;\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.trim();\n\t\tthis.emit();\n\t}\n\n\tclose(): void {\n\t\tif (this.closed) return;\n\t\tthis._closed = true;\n\t\tthis.listeners.clear();\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.suppressed = true;\n\t\t\trecord.removeParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.records.values()], graceMs);\n\t}\n\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.records.values()) {\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\t\t// Returning to a branch revives its undelivered completions; restored history\n\t\t\t// stays delivered and suppressed.\n\t\t\tif (record.visible && record.delivery === \"pending\") record.suppressed = false;\n\t\t}\n\t\tconst outside = [...this.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) record.suppressed = true;\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: RecordState[], graceMs: number): Promise<void> {\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tPromise.all(records.map((record) => record.done)).then(() => Promise.all(this.cleanups)),\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\ttimer = setTimeout(resolve, finiteLimit(graceMs, 2000, 60_000));\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (timer !== undefined) clearTimeout(timer);\n\t\t}\n\t}\n\n\tprivate snapshot(record: RecordState): BackgroundTask {\n\t\treturn structuredClone(record.task);\n\t}\n\n\tprivate cleanupOutput(record: RecordState): void {\n\t\tif (!record.settled || record.pins || record.waiters.size || !record.cleanup) return;\n\t\tconst cleanup = record.cleanup;\n\t\trecord.cleanup = undefined;\n\t\t// Snapshots retain final bounded text; expired files are never needed to render history.\n\t\trecord.task.outputPath = undefined;\n\t\trecord.readError = \"Output has expired: the managed log was released; showing the stored result.\";\n\t\tconst pending = Promise.resolve()\n\t\t\t.then(cleanup)\n\t\t\t.catch((error: unknown) => {\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.onCleanupError?.(errorText(error));\n\t\t\t\t} catch {\n\t\t\t\t\t/* Cleanup/reporting is best effort, never an unhandled rejection. */\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => this.cleanups.delete(pending));\n\t\tthis.cleanups.add(pending);\n\t}\n\n\t/** Pending delivery, active reads and pins have their own bounded retention allowance. */\n\tprivate historyRecords(): RecordState[] {\n\t\treturn [...this.records.values()].filter(\n\t\t\t(record) => record.settled && record.delivery === \"delivered\" && !record.pins && !record.waiters.size,\n\t\t);\n\t}\n\n\tprivate trim(): void {\n\t\tif (this.closed) {\n\t\t\tfor (const record of this.records.values()) this.cleanupOutput(record);\n\t\t\treturn;\n\t\t}\n\t\t// Undelivered notifications and claims are never evicted. Admission bounds all retention.\n\t\tconst history = this.historyRecords();\n\t\t// Delivered history can be restored from branch snapshots; hidden rows must\n\t\t// not occupy the current branch's history budget. Pending results stay owned.\n\t\tconst expired = history.filter((record) => !record.visible);\n\t\tfor (const shell of [false, true]) {\n\t\t\tconst group = history.filter((record) => record.visible && isForegroundShellTask(record.task) === shell);\n\t\t\tgroup.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0));\n\t\t\texpired.push(...group.slice(0, Math.max(0, group.length - this.maxHistory)));\n\t\t}\n\t\tfor (const record of expired) {\n\t\t\tthis.records.delete(record.task.id);\n\t\t\tthis.cleanupOutput(record);\n\t\t}\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.closed) return;\n\t\tfor (const listener of [...this.listeners]) {\n\t\t\tif (this.closed) break;\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Observers do not own execution or delivery. */\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -9,6 +9,11 @@ interface BackgroundSessionOptions {
9
9
  role: "main" | "subagent";
10
10
  /** The main session owns prompt queues, preflight and idle state. */
11
11
  canDeliver(): boolean;
12
+ /**
13
+ * Hand one completion to the host's prompt path. The promise must settle only after the
14
+ * message is persisted, or after it can no longer be persisted: a claim is released for
15
+ * a delivery attempt that ended without the transcript containing the message.
16
+ */
12
17
  deliver(message: CustomMessage): Promise<void>;
13
18
  onEntry(entry: SessionEntry): void;
14
19
  onError(event: string, message: string): void;
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/core/background/session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAK1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,KAAK,cAAc,EAAwB,MAAM,YAAY,CAAC;AAEvE,UAAU,wBAAwB;IACjC,OAAO,EAAE,cAAc,CAAC;IACxB,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC;IAC1B,qEAAqE;IACrE,UAAU,IAAI,OAAO,CAAC;IACtB,OAAO,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/C,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;IACnC,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9C;AAED,MAAM,WAAW,+BAA+B;IA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C,QAAQ,CAAC,CAAW;IAC5B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;IAC9C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAyC;gBAExD,OAAO,EAAE,wBAAwB;IAK7C,IAAI,OAAO,IAAI,iBAAiB,CAE/B;IAED,IAAI,sBAAsB,IAAI,SAAS,+BAA+B,EAAE,CAEvE;IAED,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAKlC,2FAA2F;IAC3F,cAAc,IAAI,IAAI;IAMtB,OAAO,CAAC,aAAa;IA0BrB,cAAc,CAAC,OAAO,oBAAe,GAAG,IAAI;IAU5C,OAAO,CAAC,oBAAoB;IAsB5B,OAAO,CAAC,iBAAiB;IAyBzB,OAAO,CAAC,IAAI;IAQZ,sEAAsE;IACtE,KAAK,IAAI,MAAM,IAAI;IAanB,KAAK,IAAI,IAAI;IAKb,OAAO,CAAC,QAAQ;IAWhB,OAAO,CAAC,UAAU;YAMJ,KAAK;IAmCnB,2FAA2F;IAC3F,sBAAsB,CAAC,OAAO,EAAE,YAAY,GAAG,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS;IAYvE,8EAA8E;IAC9E,qBAAqB,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAY7C,OAAO,IAAI,IAAI;CAMf"}
@@ -160,7 +160,8 @@ export class BackgroundSession {
160
160
  const task = service.pendingNotifications().find((task) => !this.failures.has(task.id));
161
161
  if (!task || !service.claimNotification(task.id))
162
162
  return;
163
- // Exactly one completion turn may be in flight; no separate claim registry.
163
+ // Exactly one completion may be in flight, whether queued for steering or running its
164
+ // own turn; there is no separate claim registry.
164
165
  const delivery = { id: task.id, service, persisted: false };
165
166
  this.delivery = delivery;
166
167
  let deliveryError;
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/core/background/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpD,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,CAAC;QACpE,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,QAAQ,IAAI,OAAO,EAAE,MAAM,KAAK,QAAQ,CAAC,EAAE;YAAE,OAAO;QACzD,OAAO,GAAG,EAAE;YACX,IAAI,QAAQ,CAAC,SAAS;gBAAE,OAAO;YAC/B,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC;YAC1B,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAC7C,CAAC,CAAC;IACH,CAAC;IAED,8EAA8E;IAC9E,qBAAqB,CAAC,OAAgB;QACrC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,kBAAkB,IAAI,OAAO,CAAC;YAAE,OAAO;QACxF,MAAM,EAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC;QACpC,IACC,OAAO,EAAE,KAAK,QAAQ;YACtB,IAAI,CAAC,OAAO;iBACV,IAAI,EAAE;iBACN,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,IAAI,oBAAoB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAEnG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;IACjC,CAAC;IAED,OAAO;QACN,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,KAAK;YAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzC,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;IACxB,CAAC;CACD","sourcesContent":["import { appendFileSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { SessionEntry, SessionManager } from \"../session-manager.ts\";\nimport { truncateHead } from \"../tools/truncate.ts\";\nimport { BACKGROUND_USAGE_TYPE, getBackgroundUsageRecord } from \"../usage-totals.ts\";\nimport { BACKGROUND_HISTORY_VERSION } from \"./history.ts\";\nimport { backgroundCompletionMessage } from \"./presentation.ts\";\nimport { BackgroundService } from \"./service.ts\";\nimport { type BackgroundTask, isBackgroundTerminal } from \"./types.ts\";\n\ninterface BackgroundSessionOptions {\n\tmanager: SessionManager;\n\trole: \"main\" | \"subagent\";\n\t/** The main session owns prompt queues, preflight and idle state. */\n\tcanDeliver(): boolean;\n\tdeliver(message: CustomMessage): Promise<void>;\n\tonEntry(entry: SessionEntry): void;\n\tonError(event: string, message: string): void;\n}\n\nexport interface QuarantinedBackgroundSettlement {\n\tsessionId: string;\n\tgeneration: number;\n\ttask: BackgroundTask;\n\tusage?: Usage;\n}\n\ninterface Delivery {\n\tid: string;\n\tservice: BackgroundService;\n\tpersisted: boolean;\n}\n\n/** Session persistence and completion delivery; execution supervision stays in BackgroundService. */\nexport class BackgroundSession {\n\tprivate readonly options: BackgroundSessionOptions;\n\tprivate _service: BackgroundService;\n\tprivate enabled = false;\n\tprivate disposed = false;\n\tprivate generation = 0;\n\tprivate pauses = 0;\n\tprivate timer?: ReturnType<typeof setTimeout>;\n\tprivate delivery?: Delivery;\n\tprivate readonly failures = new Set<string>();\n\tprivate readonly quarantine: QuarantinedBackgroundSettlement[] = [];\n\n\tconstructor(options: BackgroundSessionOptions) {\n\t\tthis.options = options;\n\t\tthis._service = this.createService();\n\t}\n\n\tget service(): BackgroundService {\n\t\treturn this._service;\n\t}\n\n\tget quarantinedSettlements(): readonly QuarantinedBackgroundSettlement[] {\n\t\treturn structuredClone(this.quarantine);\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.enabled = enabled && this.options.role === \"main\";\n\t\tthis.service.setEnabled(this.enabled);\n\t}\n\n\t/** Called after the old service's bounded shutdown, while lifecycle delivery is paused. */\n\treplaceService(): void {\n\t\tthis.service.close();\n\t\tthis._service = this.createService();\n\t\tthis.failures.clear();\n\t}\n\n\tprivate createService(): BackgroundService {\n\t\tconst { manager, role } = this.options;\n\t\tconst generation = ++this.generation;\n\t\tconst sessionId = manager.getSessionId();\n\t\tconst sessionFile = manager.getSessionFile();\n\t\tconst service = new BackgroundService({\n\t\t\tenabled: this.enabled,\n\t\t\trole,\n\t\t\tanchor: () => manager.getLeafId(),\n\t\t\tonCleanupError: (message) => this.warn(\"background_cleanup\", message),\n\t\t\tonSettled: (task, usage) => {\n\t\t\t\tconst onBranch =\n\t\t\t\t\tmanager.getSessionId() === sessionId &&\n\t\t\t\t\t(task.anchorId === null || manager.getBranch().some((entry) => entry.id === task.anchorId));\n\t\t\t\tif (this.disposed || this.service !== service || !onBranch) {\n\t\t\t\t\tthis.quarantineSettlement({ sessionId, generation, task, usage }, sessionFile);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.persistSettlement(task, usage);\n\t\t\t},\n\t\t});\n\t\tthis.restoreHistory(service);\n\t\tservice.subscribe(() => this.schedule());\n\t\treturn service;\n\t}\n\n\trestoreHistory(service = this.service): void {\n\t\tservice.restoreHistory(\n\t\t\tthis.options.manager\n\t\t\t\t.getBranch()\n\t\t\t\t.flatMap((entry) =>\n\t\t\t\t\tentry.type === \"custom\" && entry.customType === \"background-task-result\" ? [entry.data] : [],\n\t\t\t\t),\n\t\t);\n\t}\n\n\tprivate quarantineSettlement(record: QuarantinedBackgroundSettlement, sessionFile: string | undefined): void {\n\t\t// Never move the active leaf to append late usage: JSONL's last entry also\n\t\t// selects its resumed branch. The sidecar is diagnostic evidence only.\n\t\tthis.quarantine.push(structuredClone(record));\n\t\tif (this.quarantine.length > 32) this.quarantine.shift();\n\t\tlet persistence =\n\t\t\t\"Not persisted: only the latest 32 snapshots are retained in quarantinedBackgroundSettlements; late usage is not accounted in session totals.\";\n\t\tif (sessionFile) {\n\t\t\ttry {\n\t\t\t\tmkdirSync(dirname(sessionFile), { recursive: true });\n\t\t\t\tappendFileSync(`${sessionFile}.background-late.jsonl`, `${JSON.stringify({ version: 1, ...record })}\\n`);\n\t\t\t\tpersistence = `Saved diagnostic sidecar: ${sessionFile}.background-late.jsonl (not included in normal session totals).`;\n\t\t\t} catch {\n\t\t\t\tpersistence = `Sidecar write failed. ${persistence}`;\n\t\t\t}\n\t\t}\n\t\tthis.warn(\n\t\t\t\"background_settlement_quarantined\",\n\t\t\t`Late background settlement ${record.task.id} was quarantined. ${persistence}`,\n\t\t);\n\t}\n\n\tprivate persistSettlement(task: BackgroundTask, usage: Usage | undefined): void {\n\t\tconst manager = this.options.manager;\n\t\tconst appended: SessionEntry[] = [];\n\t\tconst append = (customType: string, data: unknown) => {\n\t\t\tconst entry = manager.getEntry(manager.appendCustomEntry(customType, data));\n\t\t\tif (entry) appended.push(entry);\n\t\t};\n\t\ttry {\n\t\t\tif (usage && !manager.getEntries().some((entry) => getBackgroundUsageRecord(entry)?.taskId === task.id)) {\n\t\t\t\tappend(BACKGROUND_USAGE_TYPE, { version: 1, taskId: task.id, usage });\n\t\t\t}\n\t\t\tappend(\"background-task-result\", JSON.parse(JSON.stringify({ version: BACKGROUND_HISTORY_VERSION, task })));\n\t\t} finally {\n\t\t\t// Complete the writes before observers can replace the runtime or its manager.\n\t\t\t// If a write fails, still report entries that were successfully appended.\n\t\t\tfor (const entry of appended) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.onEntry(entry);\n\t\t\t\t} catch {\n\t\t\t\t\t// Observers cannot interrupt settlement or result publication.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate warn(event: string, message: string): void {\n\t\ttry {\n\t\t\tthis.options.onError(event, truncateHead(message, { maxBytes: 4096, maxLines: 32 }).content);\n\t\t} catch {\n\t\t\t// Diagnostics cannot reject settlement, cleanup or scheduled callbacks.\n\t\t}\n\t}\n\n\t/** Nestable across asynchronous preflight and service replacement. */\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tconst releaseService = this.service.pause();\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tthis.pauses--;\n\t\t\treleaseService();\n\t\t\tthis.schedule();\n\t\t};\n\t}\n\n\tretry(): void {\n\t\tthis.failures.clear();\n\t\tthis.schedule();\n\t}\n\n\tprivate schedule(): void {\n\t\tif (this.disposed || this.timer || this.delivery) return;\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = undefined;\n\t\t\tvoid this.drain().catch(() =>\n\t\t\t\tthis.warn(\"background_delivery\", \"Background notification drain failed; delivery was not confirmed.\"),\n\t\t\t);\n\t\t}, 0);\n\t\tthis.timer.unref?.();\n\t}\n\n\tprivate canDeliver(service: BackgroundService): boolean {\n\t\treturn (\n\t\t\t!this.disposed && service === this.service && service.enabled && this.pauses === 0 && this.options.canDeliver()\n\t\t);\n\t}\n\n\tprivate async drain(): Promise<void> {\n\t\tconst service = this.service;\n\t\tif (this.delivery || !this.canDeliver(service)) return;\n\t\tif (this.failures.size) {\n\t\t\tconst retained = new Set(service.list().map((task) => task.id));\n\t\t\tfor (const id of this.failures) if (!retained.has(id)) this.failures.delete(id);\n\t\t}\n\t\tconst task = service.pendingNotifications().find((task) => !this.failures.has(task.id));\n\t\tif (!task || !service.claimNotification(task.id)) return;\n\t\t// Exactly one completion turn may be in flight; no separate claim registry.\n\t\tconst delivery: Delivery = { id: task.id, service, persisted: false };\n\t\tthis.delivery = delivery;\n\t\tlet deliveryError: unknown;\n\t\ttry {\n\t\t\tawait this.options.deliver(backgroundCompletionMessage(task));\n\t\t} catch (error) {\n\t\t\tdeliveryError = error;\n\t\t} finally {\n\t\t\tif (!delivery.persisted) {\n\t\t\t\tservice.releaseNotification(task.id);\n\t\t\t\tif (service === this.service) this.failures.add(task.id);\n\t\t\t\tconst reason = deliveryError instanceof Error ? `: ${deliveryError.message}` : \"\";\n\t\t\t\tthis.warn(\n\t\t\t\t\t\"background_delivery\",\n\t\t\t\t\t`Background completion delivery failed for ${task.id}${reason}; it will retry on the next prompt.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.delivery = undefined;\n\t\t\tconst current = this.service;\n\t\t\tif (this.canDeliver(current) && current.pendingNotifications().some((task) => !this.failures.has(task.id)))\n\t\t\t\tthis.schedule();\n\t\t}\n\t}\n\n\t/** Capture before message hooks, invoke only after the resulting message was persisted. */\n\tmessageAcknowledgement(message: AgentMessage): (() => void) | undefined {\n\t\tif (message.role !== \"custom\" || message.customType !== \"background-completion\") return;\n\t\tconst details = message.details as { taskId?: unknown } | undefined;\n\t\tconst delivery = this.delivery;\n\t\tif (!delivery || details?.taskId !== delivery.id) return;\n\t\treturn () => {\n\t\t\tif (delivery.persisted) return;\n\t\t\tdelivery.persisted = true;\n\t\t\tdelivery.service.markDelivered(delivery.id);\n\t\t};\n\t}\n\n\t/** A wait result claims delivery only through its final, persisted marker. */\n\tacknowledgeWaitResult(details: unknown): void {\n\t\tif (!details || typeof details !== \"object\" || !(\"backgroundTaskId\" in details)) return;\n\t\tconst id = details.backgroundTaskId;\n\t\tif (\n\t\t\ttypeof id === \"string\" &&\n\t\t\tthis.service\n\t\t\t\t.list()\n\t\t\t\t.some((task) => task.id === id && task.mode === \"background\" && isBackgroundTerminal(task.status))\n\t\t)\n\t\t\tthis.service.markDelivered(id);\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.service.close();\n\t\tif (this.timer) clearTimeout(this.timer);\n\t\tthis.timer = undefined;\n\t}\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/core/background/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAKpC,OAAO,EAAE,YAAY,EAAE,MAAM,s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AI,CAAC,QAAQ,IAAI,OAAO,EAAE,MAAM,KAAK,QAAQ,CAAC,EAAE;YAAE,OAAO;QACzD,OAAO,GAAG,EAAE;YACX,IAAI,QAAQ,CAAC,SAAS;gBAAE,OAAO;YAC/B,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC;YAC1B,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAC7C,CAAC,CAAC;IACH,CAAC;IAED,8EAA8E;IAC9E,qBAAqB,CAAC,OAAgB;QACrC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,kBAAkB,IAAI,OAAO,CAAC;YAAE,OAAO;QACxF,MAAM,EAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC;QACpC,IACC,OAAO,EAAE,KAAK,QAAQ;YACtB,IAAI,CAAC,OAAO;iBACV,IAAI,EAAE;iBACN,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,IAAI,oBAAoB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAEnG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;IACjC,CAAC;IAED,OAAO;QACN,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACrB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,KAAK;YAAE,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACzC,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;IACxB,CAAC;CACD","sourcesContent":["import { appendFileSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport type { CustomMessage } from \"../messages.ts\";\nimport type { SessionEntry, SessionManager } from \"../session-manager.ts\";\nimport { truncateHead } from \"../tools/truncate.ts\";\nimport { BACKGROUND_USAGE_TYPE, getBackgroundUsageRecord } from \"../usage-totals.ts\";\nimport { BACKGROUND_HISTORY_VERSION } from \"./history.ts\";\nimport { backgroundCompletionMessage } from \"./presentation.ts\";\nimport { BackgroundService } from \"./service.ts\";\nimport { type BackgroundTask, isBackgroundTerminal } from \"./types.ts\";\n\ninterface BackgroundSessionOptions {\n\tmanager: SessionManager;\n\trole: \"main\" | \"subagent\";\n\t/** The main session owns prompt queues, preflight and idle state. */\n\tcanDeliver(): boolean;\n\t/**\n\t * Hand one completion to the host's prompt path. The promise must settle only after the\n\t * message is persisted, or after it can no longer be persisted: a claim is released for\n\t * a delivery attempt that ended without the transcript containing the message.\n\t */\n\tdeliver(message: CustomMessage): Promise<void>;\n\tonEntry(entry: SessionEntry): void;\n\tonError(event: string, message: string): void;\n}\n\nexport interface QuarantinedBackgroundSettlement {\n\tsessionId: string;\n\tgeneration: number;\n\ttask: BackgroundTask;\n\tusage?: Usage;\n}\n\ninterface Delivery {\n\tid: string;\n\tservice: BackgroundService;\n\tpersisted: boolean;\n}\n\n/** Session persistence and completion delivery; execution supervision stays in BackgroundService. */\nexport class BackgroundSession {\n\tprivate readonly options: BackgroundSessionOptions;\n\tprivate _service: BackgroundService;\n\tprivate enabled = false;\n\tprivate disposed = false;\n\tprivate generation = 0;\n\tprivate pauses = 0;\n\tprivate timer?: ReturnType<typeof setTimeout>;\n\tprivate delivery?: Delivery;\n\tprivate readonly failures = new Set<string>();\n\tprivate readonly quarantine: QuarantinedBackgroundSettlement[] = [];\n\n\tconstructor(options: BackgroundSessionOptions) {\n\t\tthis.options = options;\n\t\tthis._service = this.createService();\n\t}\n\n\tget service(): BackgroundService {\n\t\treturn this._service;\n\t}\n\n\tget quarantinedSettlements(): readonly QuarantinedBackgroundSettlement[] {\n\t\treturn structuredClone(this.quarantine);\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.enabled = enabled && this.options.role === \"main\";\n\t\tthis.service.setEnabled(this.enabled);\n\t}\n\n\t/** Called after the old service's bounded shutdown, while lifecycle delivery is paused. */\n\treplaceService(): void {\n\t\tthis.service.close();\n\t\tthis._service = this.createService();\n\t\tthis.failures.clear();\n\t}\n\n\tprivate createService(): BackgroundService {\n\t\tconst { manager, role } = this.options;\n\t\tconst generation = ++this.generation;\n\t\tconst sessionId = manager.getSessionId();\n\t\tconst sessionFile = manager.getSessionFile();\n\t\tconst service = new BackgroundService({\n\t\t\tenabled: this.enabled,\n\t\t\trole,\n\t\t\tanchor: () => manager.getLeafId(),\n\t\t\tonCleanupError: (message) => this.warn(\"background_cleanup\", message),\n\t\t\tonSettled: (task, usage) => {\n\t\t\t\tconst onBranch =\n\t\t\t\t\tmanager.getSessionId() === sessionId &&\n\t\t\t\t\t(task.anchorId === null || manager.getBranch().some((entry) => entry.id === task.anchorId));\n\t\t\t\tif (this.disposed || this.service !== service || !onBranch) {\n\t\t\t\t\tthis.quarantineSettlement({ sessionId, generation, task, usage }, sessionFile);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.persistSettlement(task, usage);\n\t\t\t},\n\t\t});\n\t\tthis.restoreHistory(service);\n\t\tservice.subscribe(() => this.schedule());\n\t\treturn service;\n\t}\n\n\trestoreHistory(service = this.service): void {\n\t\tservice.restoreHistory(\n\t\t\tthis.options.manager\n\t\t\t\t.getBranch()\n\t\t\t\t.flatMap((entry) =>\n\t\t\t\t\tentry.type === \"custom\" && entry.customType === \"background-task-result\" ? [entry.data] : [],\n\t\t\t\t),\n\t\t);\n\t}\n\n\tprivate quarantineSettlement(record: QuarantinedBackgroundSettlement, sessionFile: string | undefined): void {\n\t\t// Never move the active leaf to append late usage: JSONL's last entry also\n\t\t// selects its resumed branch. The sidecar is diagnostic evidence only.\n\t\tthis.quarantine.push(structuredClone(record));\n\t\tif (this.quarantine.length > 32) this.quarantine.shift();\n\t\tlet persistence =\n\t\t\t\"Not persisted: only the latest 32 snapshots are retained in quarantinedBackgroundSettlements; late usage is not accounted in session totals.\";\n\t\tif (sessionFile) {\n\t\t\ttry {\n\t\t\t\tmkdirSync(dirname(sessionFile), { recursive: true });\n\t\t\t\tappendFileSync(`${sessionFile}.background-late.jsonl`, `${JSON.stringify({ version: 1, ...record })}\\n`);\n\t\t\t\tpersistence = `Saved diagnostic sidecar: ${sessionFile}.background-late.jsonl (not included in normal session totals).`;\n\t\t\t} catch {\n\t\t\t\tpersistence = `Sidecar write failed. ${persistence}`;\n\t\t\t}\n\t\t}\n\t\tthis.warn(\n\t\t\t\"background_settlement_quarantined\",\n\t\t\t`Late background settlement ${record.task.id} was quarantined. ${persistence}`,\n\t\t);\n\t}\n\n\tprivate persistSettlement(task: BackgroundTask, usage: Usage | undefined): void {\n\t\tconst manager = this.options.manager;\n\t\tconst appended: SessionEntry[] = [];\n\t\tconst append = (customType: string, data: unknown) => {\n\t\t\tconst entry = manager.getEntry(manager.appendCustomEntry(customType, data));\n\t\t\tif (entry) appended.push(entry);\n\t\t};\n\t\ttry {\n\t\t\tif (usage && !manager.getEntries().some((entry) => getBackgroundUsageRecord(entry)?.taskId === task.id)) {\n\t\t\t\tappend(BACKGROUND_USAGE_TYPE, { version: 1, taskId: task.id, usage });\n\t\t\t}\n\t\t\tappend(\"background-task-result\", JSON.parse(JSON.stringify({ version: BACKGROUND_HISTORY_VERSION, task })));\n\t\t} finally {\n\t\t\t// Complete the writes before observers can replace the runtime or its manager.\n\t\t\t// If a write fails, still report entries that were successfully appended.\n\t\t\tfor (const entry of appended) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.onEntry(entry);\n\t\t\t\t} catch {\n\t\t\t\t\t// Observers cannot interrupt settlement or result publication.\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate warn(event: string, message: string): void {\n\t\ttry {\n\t\t\tthis.options.onError(event, truncateHead(message, { maxBytes: 4096, maxLines: 32 }).content);\n\t\t} catch {\n\t\t\t// Diagnostics cannot reject settlement, cleanup or scheduled callbacks.\n\t\t}\n\t}\n\n\t/** Nestable across asynchronous preflight and service replacement. */\n\tpause(): () => void {\n\t\tthis.pauses++;\n\t\tconst releaseService = this.service.pause();\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tthis.pauses--;\n\t\t\treleaseService();\n\t\t\tthis.schedule();\n\t\t};\n\t}\n\n\tretry(): void {\n\t\tthis.failures.clear();\n\t\tthis.schedule();\n\t}\n\n\tprivate schedule(): void {\n\t\tif (this.disposed || this.timer || this.delivery) return;\n\t\tthis.timer = setTimeout(() => {\n\t\t\tthis.timer = undefined;\n\t\t\tvoid this.drain().catch(() =>\n\t\t\t\tthis.warn(\"background_delivery\", \"Background notification drain failed; delivery was not confirmed.\"),\n\t\t\t);\n\t\t}, 0);\n\t\tthis.timer.unref?.();\n\t}\n\n\tprivate canDeliver(service: BackgroundService): boolean {\n\t\treturn (\n\t\t\t!this.disposed && service === this.service && service.enabled && this.pauses === 0 && this.options.canDeliver()\n\t\t);\n\t}\n\n\tprivate async drain(): Promise<void> {\n\t\tconst service = this.service;\n\t\tif (this.delivery || !this.canDeliver(service)) return;\n\t\tif (this.failures.size) {\n\t\t\tconst retained = new Set(service.list().map((task) => task.id));\n\t\t\tfor (const id of this.failures) if (!retained.has(id)) this.failures.delete(id);\n\t\t}\n\t\tconst task = service.pendingNotifications().find((task) => !this.failures.has(task.id));\n\t\tif (!task || !service.claimNotification(task.id)) return;\n\t\t// Exactly one completion may be in flight, whether queued for steering or running its\n\t\t// own turn; there is no separate claim registry.\n\t\tconst delivery: Delivery = { id: task.id, service, persisted: false };\n\t\tthis.delivery = delivery;\n\t\tlet deliveryError: unknown;\n\t\ttry {\n\t\t\tawait this.options.deliver(backgroundCompletionMessage(task));\n\t\t} catch (error) {\n\t\t\tdeliveryError = error;\n\t\t} finally {\n\t\t\tif (!delivery.persisted) {\n\t\t\t\tservice.releaseNotification(task.id);\n\t\t\t\tif (service === this.service) this.failures.add(task.id);\n\t\t\t\tconst reason = deliveryError instanceof Error ? `: ${deliveryError.message}` : \"\";\n\t\t\t\tthis.warn(\n\t\t\t\t\t\"background_delivery\",\n\t\t\t\t\t`Background completion delivery failed for ${task.id}${reason}; it will retry on the next prompt.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.delivery = undefined;\n\t\t\tconst current = this.service;\n\t\t\tif (this.canDeliver(current) && current.pendingNotifications().some((task) => !this.failures.has(task.id)))\n\t\t\t\tthis.schedule();\n\t\t}\n\t}\n\n\t/** Capture before message hooks, invoke only after the resulting message was persisted. */\n\tmessageAcknowledgement(message: AgentMessage): (() => void) | undefined {\n\t\tif (message.role !== \"custom\" || message.customType !== \"background-completion\") return;\n\t\tconst details = message.details as { taskId?: unknown } | undefined;\n\t\tconst delivery = this.delivery;\n\t\tif (!delivery || details?.taskId !== delivery.id) return;\n\t\treturn () => {\n\t\t\tif (delivery.persisted) return;\n\t\t\tdelivery.persisted = true;\n\t\t\tdelivery.service.markDelivered(delivery.id);\n\t\t};\n\t}\n\n\t/** A wait result claims delivery only through its final, persisted marker. */\n\tacknowledgeWaitResult(details: unknown): void {\n\t\tif (!details || typeof details !== \"object\" || !(\"backgroundTaskId\" in details)) return;\n\t\tconst id = details.backgroundTaskId;\n\t\tif (\n\t\t\ttypeof id === \"string\" &&\n\t\t\tthis.service\n\t\t\t\t.list()\n\t\t\t\t.some((task) => task.id === id && task.mode === \"background\" && isBackgroundTerminal(task.status))\n\t\t)\n\t\t\tthis.service.markDelivered(id);\n\t}\n\n\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.service.close();\n\t\tif (this.timer) clearTimeout(this.timer);\n\t\tthis.timer = undefined;\n\t}\n}\n"]}
@@ -681,20 +681,20 @@ export function prepareCompaction(pathEntries, settings) {
681
681
  // ============================================================================
682
682
  // Main compaction function
683
683
  // ============================================================================
684
- const TURN_PREFIX_SUMMARIZATION_PROMPT = `This is the PREFIX of a turn that was too large to keep. The SUFFIX (recent work) is retained.
684
+ const TURN_PREFIX_SUMMARIZATION_PROMPT = `The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
685
685
 
686
- Summarize the prefix to provide context for the retained suffix:
686
+ Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.
687
687
 
688
688
  ## Original Request
689
- [What did the user ask for in this turn?]
689
+ [What did the user ask for?]
690
690
 
691
- ## Early Progress
692
- - [Key decisions and work done in the prefix]
691
+ ## Progress So Far
692
+ - [Key decisions and work completed in these messages]
693
693
 
694
- ## Context for Suffix
695
- - [Information needed to understand the retained recent work]
694
+ ## Context Needed to Continue
695
+ - [Information from these messages needed to understand the later work]
696
696
 
697
- Be concise. Focus on what's needed to understand the kept suffix.`;
697
+ Only summarize information explicitly present above. Do not infer or recreate later messages.`;
698
698
  /**
699
699
  * Generate summaries for compaction using prepared data.
700
700
  * Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.
@@ -748,7 +748,7 @@ async function generateTurnPrefixSummary(messages, model, reserveTokens, apiKey,
748
748
  const maxTokens = Math.min(Math.floor(0.5 * reserveTokens), model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY); // Smaller budget for turn prefix
749
749
  const llmMessages = convertToLlm(messages);
750
750
  const conversationText = serializeConversation(llmMessages);
751
- const promptText = `<conversation>\n${conversationText}\n</conversation>\n\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;
751
+ const promptText = `# Conversation\n${conversationText}\n\n# Instructions\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;
752
752
  const response = await completeSummarization(model, buildSummarizationContext(promptText), createSummarizationOptions(model, maxTokens, apiKey, headers, env, signal, thinkingLevel, sessionId), streamFn, retry, callbacks);
753
753
  const failure = getSummarizationFailure(response, "Turn prefix summarization");
754
754
  if (failure) {