@astralyn/pi 1.4.6 → 1.4.7
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.
- package/CHANGELOG.md +22 -0
- package/dist/bundle/chunks/{chunk-KDO6L76C.js → chunk-FODCTZXW.js} +4 -4
- package/dist/bundle/chunks/{chunk-EYKC6ESU.js → chunk-FYKNSJG6.js} +1 -1
- package/dist/bundle/chunks/{chunk-AXFWZIHH.js → chunk-MG5XDTXV.js} +1 -1
- package/dist/bundle/chunks/{chunk-ALHAFUHP.js → chunk-PU2IWWXV.js} +1 -1
- package/dist/bundle/chunks/{chunk-5M3YJ54Z.js → chunk-RO2VH6UZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-RBTJBQWX.js → chunk-YJTSOLP2.js} +73 -74
- package/dist/bundle/chunks/{cli-FH77R7JR.js → cli-MEL7SGJD.js} +1 -1
- package/dist/bundle/chunks/{execute-5ZQUS52M.js → execute-4CWRNHPO.js} +1 -1
- package/dist/bundle/chunks/{runtime-R5CMHJ5P.js → runtime-R3X67XMR.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-KCQU7LOC.js → virtual-modules-PKEOKGYI.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/agent-session.d.ts +0 -3
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +0 -4
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/package-manager.d.ts +7 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +72 -1
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/resource-loader.d.ts +1 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +23 -7
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +11 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +7 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +6 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/skills.d.ts +10 -0
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +23 -0
- package/dist/core/skills.js.map +1 -1
- package/dist/core/tasks/delivery.d.ts +11 -4
- package/dist/core/tasks/delivery.d.ts.map +1 -1
- package/dist/core/tasks/delivery.js +9 -9
- package/dist/core/tasks/delivery.js.map +1 -1
- package/dist/core/tasks/execution.d.ts +10 -3
- package/dist/core/tasks/execution.d.ts.map +1 -1
- package/dist/core/tasks/execution.js +72 -52
- package/dist/core/tasks/execution.js.map +1 -1
- package/dist/core/tasks/format.d.ts +0 -2
- package/dist/core/tasks/format.d.ts.map +1 -1
- package/dist/core/tasks/format.js +1 -16
- package/dist/core/tasks/format.js.map +1 -1
- package/dist/core/tasks/limits.d.ts +12 -1
- package/dist/core/tasks/limits.d.ts.map +1 -1
- package/dist/core/tasks/limits.js +20 -1
- package/dist/core/tasks/limits.js.map +1 -1
- package/dist/core/tasks/output.d.ts +6 -12
- package/dist/core/tasks/output.d.ts.map +1 -1
- package/dist/core/tasks/output.js +35 -32
- package/dist/core/tasks/output.js.map +1 -1
- package/dist/core/tasks/record.d.ts +45 -0
- package/dist/core/tasks/record.d.ts.map +1 -0
- package/dist/core/tasks/record.js +80 -0
- package/dist/core/tasks/record.js.map +1 -0
- package/dist/core/tasks/runtime.d.ts +14 -14
- package/dist/core/tasks/runtime.d.ts.map +1 -1
- package/dist/core/tasks/runtime.js +111 -93
- package/dist/core/tasks/runtime.js.map +1 -1
- package/dist/core/tasks/session.d.ts +0 -1
- package/dist/core/tasks/session.d.ts.map +1 -1
- package/dist/core/tasks/session.js +7 -8
- package/dist/core/tasks/session.js.map +1 -1
- package/dist/core/tasks/store.d.ts +18 -25
- package/dist/core/tasks/store.d.ts.map +1 -1
- package/dist/core/tasks/store.js +42 -40
- package/dist/core/tasks/store.js.map +1 -1
- package/dist/core/tasks/types.d.ts +96 -17
- package/dist/core/tasks/types.d.ts.map +1 -1
- package/dist/core/tasks/types.js.map +1 -1
- package/dist/core/tools/shell-execution.d.ts +8 -7
- package/dist/core/tools/shell-execution.d.ts.map +1 -1
- package/dist/core/tools/shell-execution.js +18 -26
- package/dist/core/tools/shell-execution.js.map +1 -1
- package/dist/core/tools/shell-tool.d.ts.map +1 -1
- package/dist/core/tools/shell-tool.js +31 -29
- package/dist/core/tools/shell-tool.js.map +1 -1
- package/dist/core/usage-totals.d.ts +3 -0
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +15 -0
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/agent/progress.d.ts.map +1 -1
- package/dist/extensions/agent/progress.js +1 -11
- package/dist/extensions/agent/progress.js.map +1 -1
- package/dist/extensions/agent/tool.d.ts.map +1 -1
- package/dist/extensions/agent/tool.js +9 -5
- package/dist/extensions/agent/tool.js.map +1 -1
- package/dist/extensions/agent/worker.d.ts.map +1 -1
- package/dist/extensions/agent/worker.js +3 -5
- package/dist/extensions/agent/worker.js.map +1 -1
- package/dist/extensions/btw/agent.d.ts +1 -1
- package/dist/extensions/btw/agent.d.ts.map +1 -1
- package/dist/extensions/btw/agent.js +3 -20
- package/dist/extensions/btw/agent.js.map +1 -1
- package/dist/extensions/cached-compaction/index.d.ts.map +1 -1
- package/dist/extensions/cached-compaction/index.js +3 -22
- package/dist/extensions/cached-compaction/index.js.map +1 -1
- package/dist/extensions/cached-compaction/render.d.ts +1 -0
- package/dist/extensions/cached-compaction/render.d.ts.map +1 -1
- package/dist/extensions/cached-compaction/render.js +42 -14
- package/dist/extensions/cached-compaction/render.js.map +1 -1
- package/dist/extensions/deepwiki/client.d.ts.map +1 -1
- package/dist/extensions/deepwiki/client.js +6 -78
- package/dist/extensions/deepwiki/client.js.map +1 -1
- package/dist/extensions/deepwiki/transport.d.ts +3 -0
- package/dist/extensions/deepwiki/transport.d.ts.map +1 -0
- package/dist/extensions/deepwiki/transport.js +96 -0
- package/dist/extensions/deepwiki/transport.js.map +1 -0
- package/dist/extensions/provider/ui/builtin-data.d.ts +3 -3
- package/dist/extensions/provider/ui/builtin-data.d.ts.map +1 -1
- package/dist/extensions/provider/ui/builtin-data.js.map +1 -1
- package/dist/extensions/provider/ui/compat.d.ts +3 -3
- package/dist/extensions/provider/ui/compat.d.ts.map +1 -1
- package/dist/extensions/provider/ui/compat.js.map +1 -1
- package/dist/extensions/provider/ui/controls.d.ts +2 -2
- package/dist/extensions/provider/ui/controls.d.ts.map +1 -1
- package/dist/extensions/provider/ui/controls.js.map +1 -1
- package/dist/extensions/provider/ui/dialogs.d.ts +3 -3
- package/dist/extensions/provider/ui/dialogs.d.ts.map +1 -1
- package/dist/extensions/provider/ui/dialogs.js.map +1 -1
- package/dist/extensions/provider/ui/dictionary.d.ts +2 -2
- package/dist/extensions/provider/ui/dictionary.d.ts.map +1 -1
- package/dist/extensions/provider/ui/dictionary.js.map +1 -1
- package/dist/extensions/provider/ui/editor.d.ts.map +1 -1
- package/dist/extensions/provider/ui/editor.js +1 -3
- package/dist/extensions/provider/ui/editor.js.map +1 -1
- package/dist/extensions/provider/ui/fetch-models.d.ts +2 -2
- package/dist/extensions/provider/ui/fetch-models.d.ts.map +1 -1
- package/dist/extensions/provider/ui/fetch-models.js.map +1 -1
- package/dist/extensions/provider/ui/model-fields.d.ts +2 -2
- package/dist/extensions/provider/ui/model-fields.d.ts.map +1 -1
- package/dist/extensions/provider/ui/model-fields.js.map +1 -1
- package/dist/extensions/provider/ui/model-options.d.ts +6 -6
- package/dist/extensions/provider/ui/model-options.d.ts.map +1 -1
- package/dist/extensions/provider/ui/model-options.js.map +1 -1
- package/dist/extensions/provider/ui/pane.d.ts +21 -12
- package/dist/extensions/provider/ui/pane.d.ts.map +1 -1
- package/dist/extensions/provider/ui/pane.js.map +1 -1
- package/dist/extensions/provider/ui/provider-fields.d.ts +3 -3
- package/dist/extensions/provider/ui/provider-fields.d.ts.map +1 -1
- package/dist/extensions/provider/ui/provider-fields.js.map +1 -1
- package/dist/extensions/provider/ui/thinking-map.d.ts +2 -2
- package/dist/extensions/provider/ui/thinking-map.d.ts.map +1 -1
- package/dist/extensions/provider/ui/thinking-map.js.map +1 -1
- package/dist/extensions/run-summary/format.js +1 -1
- package/dist/extensions/run-summary/format.js.map +1 -1
- package/dist/extensions/statusline/usage.d.ts.map +1 -1
- package/dist/extensions/statusline/usage.js +2 -6
- package/dist/extensions/statusline/usage.js.map +1 -1
- package/dist/extensions/tasks/tool/actions.d.ts +1 -1
- package/dist/extensions/tasks/tool/actions.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/actions.js +49 -106
- package/dist/extensions/tasks/tool/actions.js.map +1 -1
- package/dist/extensions/tasks/tool/constants.d.ts +1 -6
- package/dist/extensions/tasks/tool/constants.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/constants.js +1 -6
- package/dist/extensions/tasks/tool/constants.js.map +1 -1
- package/dist/extensions/tasks/tool/schema.d.ts +0 -3
- package/dist/extensions/tasks/tool/schema.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/schema.js +4 -13
- package/dist/extensions/tasks/tool/schema.js.map +1 -1
- package/dist/extensions/tasks/tool.d.ts.map +1 -1
- package/dist/extensions/tasks/tool.js +2 -2
- package/dist/extensions/tasks/tool.js.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.js +31 -33
- package/dist/extensions/tasks/ui/completion-render.js.map +1 -1
- package/dist/extensions/tasks/ui/layout.d.ts +7 -7
- package/dist/extensions/tasks/ui/layout.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/layout.js +17 -19
- package/dist/extensions/tasks/ui/layout.js.map +1 -1
- package/dist/extensions/tasks/ui/list.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/list.js +2 -3
- package/dist/extensions/tasks/ui/list.js.map +1 -1
- package/dist/extensions/tasks/ui/manager.d.ts +16 -7
- package/dist/extensions/tasks/ui/manager.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/manager.js +163 -131
- package/dist/extensions/tasks/ui/manager.js.map +1 -1
- package/dist/extensions/tasks/ui/model.d.ts +25 -0
- package/dist/extensions/tasks/ui/model.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/model.js +4 -0
- package/dist/extensions/tasks/ui/model.js.map +1 -1
- package/dist/extensions/tasks/ui/render.d.ts +1 -1
- package/dist/extensions/tasks/ui/render.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/render.js +11 -7
- package/dist/extensions/tasks/ui/render.js.map +1 -1
- package/dist/extensions/tasks/ui/status.d.ts +15 -0
- package/dist/extensions/tasks/ui/status.d.ts.map +1 -0
- package/dist/extensions/tasks/ui/status.js +16 -0
- package/dist/extensions/tasks/ui/status.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts +14 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +258 -7
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/status-marker.d.ts +2 -1
- package/dist/modes/interactive/components/status-marker.d.ts.map +1 -1
- package/dist/modes/interactive/components/status-marker.js +0 -1
- package/dist/modes/interactive/components/status-marker.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +7 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/duration.d.ts +3 -0
- package/dist/utils/duration.d.ts.map +1 -0
- package/dist/utils/duration.js +17 -0
- package/dist/utils/duration.js.map +1 -0
- package/dist/utils/number.d.ts +3 -0
- package/dist/utils/number.d.ts.map +1 -0
- package/dist/utils/number.js +5 -0
- package/dist/utils/number.js.map +1 -0
- package/docs/bundled/extensions/agent.md +3 -3
- package/docs/bundled/extensions/cached-compaction.md +13 -4
- package/docs/bundled/extensions/deepwiki.md +3 -1
- package/docs/extensions.md +5 -5
- package/docs/packages.md +5 -3
- package/docs/sdk.md +1 -1
- package/docs/session-format.md +1 -1
- package/docs/settings.md +11 -0
- package/docs/skills.md +23 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/schemas/settings.schema.json +36 -0
- package/dist/extensions/deepwiki/http.d.ts +0 -13
- package/dist/extensions/deepwiki/http.d.ts.map +0 -1
- package/dist/extensions/deepwiki/http.js +0 -88
- package/dist/extensions/deepwiki/http.js.map +0 -1
- package/dist/extensions/tasks/ui/task-view.d.ts +0 -8
- package/dist/extensions/tasks/ui/task-view.d.ts.map +0 -1
- package/dist/extensions/tasks/ui/task-view.js +0 -13
- package/dist/extensions/tasks/ui/task-view.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/core/tasks/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAsB,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EACN,UAAU,EACV,UAAU,EACV,SAAS,EACT,WAAW,EACX,eAAe,EACf,SAAS,EACT,gBAAgB,EAChB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAmB,SAAS,EAAE,MAAM,YAAY,CAAC;AACpE,OAAO,EACN,yBAAyB,EACzB,iBAAiB,EAEjB,eAAe,GA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CACzF,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAChC;gBACD,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;oBAC7B,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;gBACjE,CAAC,CAAC;aACF,CAAC,CAAC;QACJ,CAAC;gBAAS,CAAC;YACV,IAAI,KAAK,KAAK,SAAS;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;QAC9C,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 { Execution, type ExecutionHost, errorText } from \"./execution.ts\";\nimport { TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS } from \"./limits.ts\";\nimport {\n\tboundFacts,\n\tboundInput,\n\tboundText,\n\tfiniteLimit,\n\treadOutputSlice,\n\tsliceText,\n\tTASK_LABEL_BYTES,\n\tTASK_TITLE_BYTES,\n} from \"./output.ts\";\nimport { TaskScheduler } from \"./scheduler.ts\";\nimport { snapshotOf, type TaskRecord, TaskStore } from \"./store.ts\";\nimport {\n\tTASK_BACKGROUND_REJECTION,\n\tTASK_KIND_PATTERN,\n\ttype TaskExecution,\n\tTaskLookupError,\n\ttype TaskRead,\n\ttype TaskRuntimeOptions,\n\ttype TaskSnapshot,\n\ttype TasksContext,\n\ttype TaskToolOutcome,\n} from \"./types.ts\";\n\n/** Session-local supervision. Executors own their processes, items and output files. */\nexport class TaskRuntime implements TasksContext {\n\tprivate readonly store: TaskStore;\n\tprivate readonly executions = new Map<string, Execution<unknown>>();\n\tprivate readonly scheduler = new TaskScheduler();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly host: ExecutionHost;\n\tprivate readonly maxBackground: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate readonly options: TaskRuntimeOptions;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\tprivate pauses = 0;\n\n\tconstructor(options: TaskRuntimeOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxBackground = Math.max(1, finiteLimit(options.maxBackground, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground and background histories, plus the protected-record allowance.\n\t\tthis.maxRetained = this.maxBackground + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t\tthis.store = new TaskStore(this.maxHistory, this.maxRetained, () => this.closed, options.onCleanupError);\n\t\tconst runtime = this;\n\t\tthis.host = {\n\t\t\tget closed() {\n\t\t\t\treturn runtime.closed;\n\t\t\t},\n\t\t\temit: () => this.emit(),\n\t\t\tsettle: (task, usage) => this.options.onSettled?.(task, usage),\n\t\t\treleased: (execution) => {\n\t\t\t\tthis.executions.delete(execution.task.id);\n\t\t\t\tthis.scheduler.release(execution);\n\t\t\t\tthis.store.trim();\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t}\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\n\tget session(): TaskRuntimeOptions[\"session\"] {\n\t\treturn this.options.session;\n\t}\n\n\t/**\n\t * Rehydrate terminal snapshots only, newest endedAt in each history (later input wins\n\t * ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored. Foreground records take their output\n\t * from the branch's tool results. The host supplies the current branch; closed services\n\t * ignore restoration.\n\t */\n\trestoreHistory(\n\t\trecords: readonly unknown[],\n\t\ttoolResults?: ReadonlyMap<string, AgentToolResult<unknown>[\"content\"]>,\n\t): void {\n\t\tthis.store.restoreHistory(records, toolResults);\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.backgroundAllowed !== false;\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\t/** Foreground work is bounded by its caller; only background work, queued or running, holds a slot. */\n\tprivate backgroundActive(): number {\n\t\tlet count = 0;\n\t\tfor (const record of this.store.records.values())\n\t\t\tif (!record.settled && record.task.mode === \"background\") count++;\n\t\treturn count;\n\t}\n\n\tprivate limitError(): Error {\n\t\treturn new Error(\n\t\t\t`Background task limit reached (${this.maxBackground}); stop or wait for a background task, or run in the foreground.`,\n\t\t);\n\t}\n\n\tasync execute<T>(execution: TaskExecution<T>): Promise<TaskToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (execution.background && this.options.backgroundAllowed === false) throw new Error(TASK_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Task service is closed\");\n\t\tif (execution.background) {\n\t\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\t\tif (this.backgroundActive() >= this.maxBackground) throw this.limitError();\n\t\t\tif (this.store.records.size + this.store.cleanups.size >= this.maxRetained) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Task history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif (!TASK_KIND_PATTERN.test(execution.kind)) throw new Error(\"Invalid task source\");\n\t\tconst concurrency = execution.concurrency;\n\t\tif (concurrency && (!concurrency.key || !Number.isSafeInteger(concurrency.limit) || concurrency.limit < 1))\n\t\t\tthrow new Error(\"Invalid task concurrency\");\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192) throw new Error(\"Task branch anchor is too large\");\n\t\tconst task: TaskSnapshot = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\tlabel: boundText(execution.label ?? execution.kind, TASK_LABEL_BYTES),\n\t\t\ttitle: boundText(execution.title, TASK_TITLE_BYTES),\n\t\t\toutput: execution.output ?? \"log\",\n\t\t\t...(execution.input ? { input: boundInput(execution.input) } : {}),\n\t\t\t...(execution.facts?.length ? { facts: boundFacts(execution.facts) } : {}),\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};\n\t\tconst record: TaskRecord = {\n\t\t\ttask,\n\t\t\tsettled: false,\n\t\t\tvisible: true,\n\t\t\tdelivery: \"none\",\n\t\t\tpins: 0,\n\t\t\tdeliveryHolds: 0,\n\t\t\twaiters: new Set(),\n\t\t};\n\t\tconst active = new Execution(this.host, record, execution);\n\t\tthis.store.records.set(task.id, record);\n\t\tthis.executions.set(task.id, active as Execution<unknown>);\n\t\tthis.scheduler.schedule(active);\n\t\t// Queued background work returns at once; started work hands off after its own accept().\n\t\tif (active.queued) active.handoff();\n\t\tthis.emit();\n\t\treturn active.caller;\n\t}\n\n\tprivate detachable(record: TaskRecord): boolean {\n\t\treturn this.executions.get(record.task.id)?.detachable ?? false;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst eligible = [...this.store.records.values()]\n\t\t\t.filter((record) => this.detachable(record))\n\t\t\t.sort((left, right) => left.task.startedAt - right.task.startedAt);\n\t\tif (!eligible.length) return 0;\n\t\tconst free = this.maxBackground - this.backgroundActive();\n\t\tif (free <= 0) throw this.limitError();\n\t\tconst executions = eligible.slice(0, free).map((record) => this.executions.get(record.task.id)!);\n\t\tfor (const execution of executions) execution.requestDetach();\n\t\tfor (const execution of executions) execution.completeDetach();\n\t\tthis.emit();\n\t\treturn executions.length;\n\t}\n\n\tcanDetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\treturn this.enabled && this.backgroundActive() < this.maxBackground && this.detachable(record);\n\t}\n\n\tdetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\tif (!this.enabled || !this.detachable(record)) return false;\n\t\tif (this.backgroundActive() >= this.maxBackground) throw this.limitError();\n\t\tconst execution = this.executions.get(record.task.id)!;\n\t\texecution.requestDetach();\n\t\texecution.completeDetach();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tlist(): TaskSnapshot[] {\n\t\treturn [...this.store.records.values()].filter((record) => record.visible).map(snapshotOf);\n\t}\n\n\tprivate lookup(id: string): TaskRecord {\n\t\tconst exact = this.store.records.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = [...this.store.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 TaskLookupError(matches.length > 1 ? \"ambiguous\" : \"unknown\", matches.map(snapshotOf));\n\t\t}\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): TaskSnapshot {\n\t\treturn snapshotOf(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<TaskRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.retain(record.task.id);\n\t\ttry {\n\t\t\tconst task = snapshotOf(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: TaskSnapshot): string {\n\t\treturn task.result?.text || task.error || \"No output yet.\";\n\t}\n\n\t/** One event-driven waiter can observe a whole waitAny cohort without per-task timers. */\n\tprivate waitForRecords(\n\t\trecords: readonly TaskRecord[],\n\t\ttimeoutMs: number,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<void> {\n\t\tif (records.some((record) => record.settled) || interruptSignal?.aborted) return Promise.resolve();\n\t\treturn new Promise<void>((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\tinterruptSignal?.removeEventListener(\"abort\", interrupt);\n\t\t\t\tfor (const record of records) record.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve();\n\t\t\t\tthis.store.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\tconst interrupt = () => complete();\n\t\t\tfor (const record of records) record.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tinterruptSignal?.addEventListener(\"abort\", interrupt, { once: true });\n\t\t\ttimer = setTimeout(wake, finiteLimit(timeoutMs, TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS));\n\t\t\tif (this.closed || interruptSignal?.aborted) wake();\n\t\t\tif (signal?.aborted) abort();\n\t\t});\n\t}\n\n\t/** Observe completion without consuming delivery; the host acknowledges only persisted tool results. */\n\tasync wait(\n\t\tid: string,\n\t\ttimeoutMs = TASKS_WAIT_DEFAULT_MS,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<TaskSnapshot> {\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 snapshotOf(record);\n\t\tawait this.waitForRecords([record], timeoutMs, signal, interruptSignal);\n\t\treturn snapshotOf(record);\n\t}\n\n\tasync waitAny(\n\t\ttimeoutMs = TASKS_WAIT_DEFAULT_MS,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<TaskSnapshot | undefined> {\n\t\tif (signal?.aborted) throw signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst records = [...this.store.records.values()].filter(\n\t\t\t(record) => record.visible && record.task.mode === \"background\" && !record.settled,\n\t\t);\n\t\tif (records.length === 0 || interruptSignal?.aborted) return undefined;\n\t\tawait this.waitForRecords(records, timeoutMs, signal, interruptSignal);\n\t\tconst settled = records\n\t\t\t.filter((record) => record.settled)\n\t\t\t.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0))[0];\n\t\treturn settled ? snapshotOf(settled) : undefined;\n\t}\n\n\tkill(id: string): boolean {\n\t\treturn this.cancel(this.lookup(id));\n\t}\n\n\tprivate cancel(record: TaskRecord): boolean {\n\t\treturn this.executions.get(record.task.id)?.cancel() ?? false;\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 * Retention protects snapshots and logs only. Delivery has its own explicit hold.\n\t */\n\tretain(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.store.trim();\n\t\t\tif (!this.closed && this.pauses === 0 && this.candidate(record)) this.emit();\n\t\t};\n\t}\n\n\tholdDelivery(id: string): () => void {\n\t\tconst record = this.lookup(id);\n\t\tconst releaseRetention = this.retain(id);\n\t\trecord.deliveryHolds++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.deliveryHolds--;\n\t\t\treleaseRetention();\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(): TaskSnapshot[] {\n\t\tif (this.closed || this.pauses > 0) return [];\n\t\treturn [...this.store.records.values()].filter((record) => this.candidate(record)).map(snapshotOf);\n\t}\n\n\t/** Only explicit result-delivery holds delay an automatic completion. */\n\tprivate candidate(record: TaskRecord): boolean {\n\t\treturn record.visible && record.delivery === \"pending\" && record.waiters.size === 0 && record.deliveryHolds === 0;\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\tif (this.closed || this.pauses > 0) return false;\n\t\tconst record = this.store.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.store.records.get(id);\n\t\tif (!record) return;\n\t\trecord.delivery = \"delivered\";\n\t\tthis.store.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tconst record = this.store.records.get(id);\n\t\tif (!record || record.delivery !== \"claimed\") return;\n\t\trecord.delivery = \"pending\";\n\t\tthis.store.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.store.records.values()) {\n\t\t\tthis.executions.get(record.task.id)?.releaseParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.store.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain([...this.store.records.values()], graceMs);\n\t}\n\n\t/** Running tasks whose launch anchor is outside the branch made of `ancestors`. */\n\tactiveOutsideBranch(ancestors: ReadonlySet<string>): TaskSnapshot[] {\n\t\treturn [...this.store.records.values()]\n\t\t\t.filter((record) => !record.settled && record.task.anchorId !== null && !ancestors.has(record.task.anchorId))\n\t\t\t.map(snapshotOf);\n\t}\n\n\t/**\n\t * Hidden results stay pending: returning to their branch delivers them again.\n\t * Restored history is already delivered.\n\t */\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tfor (const record of this.store.records.values())\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\tconst outside = [...this.store.records.values()].filter((record) => !record.visible);\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.store.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: TaskRecord[], 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) => this.executions.get(record.task.id)?.done)).then(() =>\n\t\t\t\t\tPromise.all(this.store.cleanups),\n\t\t\t\t),\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 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":"runtime.js","sourceRoot":"","sources":["../../../src/core/tasks/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,SAAS,EAAsB,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EACN,UAAU,EACV,UAAU,EACV,SAAS,EACT,SAAS,EACT,eAAe,EACf,SAAS,EACT,gBAAgB,EAChB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EACN,yBAAyB,EACzB,iBAAiB,EAGjB,eAAe,GAYf,MAAM,YAAY,CAAC;AAEpB,wFAAwF;AACxF,MAAM,OAAO,WAAW;IAavB,YAAY,UAA8B,EAAE;QAX3B,eAAU,GAAG,IAAI,GAAG,EAA8B,CAAC;QACnD,cAAS,GAAG,IAAI,aAAa,EAAE,CAAC;QAChC,cAAS,GAAG,IAAI,GAAG,EAAc,CAAC;QAO3C,YAAO,GAAG,KAAK,CAAC;QAGvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,iBAAiB,GAAG,OAAO,CAAC,OAAO,IAAI,KAAK,CAAC;QAClD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC,EAAE,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AO,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC;gBACjE,CAAC,CAAC;aACF,CAAC,CAAC;QACJ,CAAC;gBAAS,CAAC;YACV,IAAI,KAAK,KAAK,SAAS;gBAAE,YAAY,CAAC,KAAK,CAAC,CAAC;QAC9C,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 { finiteLimit } from \"../../utils/number.ts\";\nimport { Execution, type ExecutionHost } from \"./execution.ts\";\nimport { boundWaitMs, TASKS_WAIT_DEFAULT_MS } from \"./limits.ts\";\nimport {\n\tboundFacts,\n\tboundInput,\n\tboundText,\n\terrorText,\n\treadOutputSlice,\n\tsliceText,\n\tTASK_LABEL_BYTES,\n\tTASK_TITLE_BYTES,\n} from \"./output.ts\";\nimport { TaskRecord } from \"./record.ts\";\nimport { TaskScheduler } from \"./scheduler.ts\";\nimport { TaskStore } from \"./store.ts\";\nimport {\n\tTASK_BACKGROUND_REJECTION,\n\tTASK_KIND_PATTERN,\n\ttype TaskDeliveryLedger,\n\ttype TaskExecution,\n\tTaskLookupError,\n\ttype TaskRead,\n\ttype TaskReadOptions,\n\ttype TaskRuntimeOptions,\n\ttype TaskSnapshot,\n\ttype TasksContext,\n\ttype TaskToolOutcome,\n\ttype TaskWaitAnyOptions,\n\ttype TaskWaitAnyResult,\n\ttype TaskWaitOptions,\n\ttype TaskWaitOutcome,\n\ttype TaskWaitResult,\n} from \"./types.ts\";\n\n/** Session-local supervision. Executors own their processes, items and output files. */\nexport class TaskRuntime implements TasksContext, TaskDeliveryLedger {\n\tprivate readonly store: TaskStore;\n\tprivate readonly executions = new Map<string, Execution<unknown>>();\n\tprivate readonly scheduler = new TaskScheduler();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly host: ExecutionHost;\n\tprivate readonly maxBackground: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate readonly options: TaskRuntimeOptions;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\n\tconstructor(options: TaskRuntimeOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxBackground = Math.max(1, finiteLimit(options.maxBackground, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground and background histories, plus the protected-record allowance.\n\t\tthis.maxRetained = this.maxBackground + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t\tthis.store = new TaskStore(this.maxHistory, this.maxRetained, () => this.closed, options.onCleanupError);\n\t\tconst runtime = this;\n\t\tthis.host = {\n\t\t\tget closed() {\n\t\t\t\treturn runtime.closed;\n\t\t\t},\n\t\t\temit: () => this.emit(),\n\t\t\tsettle: (task, usage) => this.options.onSettled?.(task, usage),\n\t\t\treleased: (execution) => {\n\t\t\t\tthis.executions.delete(execution.task.id);\n\t\t\t\tthis.scheduler.release(execution);\n\t\t\t\tthis.store.trim();\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t}\n\n\tget closed(): boolean {\n\t\treturn this._closed;\n\t}\n\n\tget session(): TaskRuntimeOptions[\"session\"] {\n\t\treturn this.options.session;\n\t}\n\n\t/**\n\t * Rehydrate terminal snapshots only, newest endedAt in each history (later input wins\n\t * ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored. Foreground records take their output\n\t * from the branch's tool results. The host supplies the current branch; closed services\n\t * ignore restoration.\n\t */\n\trestoreHistory(\n\t\trecords: readonly unknown[],\n\t\ttoolResults?: ReadonlyMap<string, AgentToolResult<unknown>[\"content\"]>,\n\t): void {\n\t\tthis.store.restoreHistory(records, toolResults);\n\t}\n\n\tget enabled(): boolean {\n\t\treturn this.configuredEnabled && !this.closed && this.options.backgroundAllowed !== false;\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.configuredEnabled = enabled;\n\t\tthis.emit();\n\t}\n\n\t/** Foreground work is bounded by its caller; only background work, queued or running, holds a slot. */\n\tprivate activeBackground(): TaskRecord[] {\n\t\treturn this.store.unsettled().filter((record) => record.task.mode === \"background\");\n\t}\n\n\tprivate backgroundActive(): number {\n\t\treturn this.activeBackground().length;\n\t}\n\n\tprivate limitError(): Error {\n\t\treturn new Error(\n\t\t\t`Background task limit reached (${this.maxBackground}); stop or wait for a background task, or run in the foreground.`,\n\t\t);\n\t}\n\n\tasync execute<T>(execution: TaskExecution<T>): Promise<TaskToolOutcome<T>> {\n\t\t// Admission and registration happen synchronously, before invoking user code or awaiting anything.\n\t\tif (execution.background && this.options.backgroundAllowed === false) throw new Error(TASK_BACKGROUND_REJECTION);\n\t\tif (this.closed) throw new Error(\"Task service is closed\");\n\t\tif (execution.background) {\n\t\t\tif (!this.enabled) throw new Error(\"Background execution is not available in this host\");\n\t\t\tif (this.backgroundActive() >= this.maxBackground) throw this.limitError();\n\t\t\tif (this.store.retainedCount() >= this.maxRetained) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Task history retention limit reached; deliver pending notifications or release pinned or claimed records\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (execution.signal?.aborted) throw execution.signal.reason ?? new Error(\"Execution aborted\");\n\t\tif (!TASK_KIND_PATTERN.test(execution.kind)) throw new Error(\"Invalid task source\");\n\t\tconst concurrency = execution.concurrency;\n\t\tif (concurrency && (!concurrency.key || !Number.isSafeInteger(concurrency.limit) || concurrency.limit < 1))\n\t\t\tthrow new Error(\"Invalid task concurrency\");\n\t\tconst anchorId = this.options.anchor?.() ?? null;\n\t\tif (anchorId !== null && Buffer.byteLength(anchorId) > 8192) throw new Error(\"Task branch anchor is too large\");\n\t\tconst task: TaskSnapshot = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\tlabel: boundText(execution.label ?? execution.kind, TASK_LABEL_BYTES),\n\t\t\ttitle: boundText(execution.title, TASK_TITLE_BYTES),\n\t\t\toutput: execution.output ?? \"log\",\n\t\t\t...(execution.input ? { input: boundInput(execution.input) } : {}),\n\t\t\t...(execution.facts?.length ? { facts: boundFacts(execution.facts) } : {}),\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};\n\t\tconst record = new TaskRecord(task);\n\t\tconst active = new Execution(this.host, record, execution);\n\t\tthis.store.add(record);\n\t\tthis.executions.set(task.id, active as Execution<unknown>);\n\t\tthis.scheduler.schedule(active);\n\t\t// Queued background work returns at once; started work hands off after its own accept().\n\t\tif (active.queued) active.handoff();\n\t\tthis.emit();\n\t\treturn active.caller;\n\t}\n\n\tprivate detachable(record: TaskRecord): boolean {\n\t\treturn this.executions.get(record.task.id)?.detachable ?? false;\n\t}\n\n\tdetachForeground(): number {\n\t\tif (!this.enabled) return 0;\n\t\tconst eligible = [...this.executions.values()]\n\t\t\t.filter((execution) => execution.detachable)\n\t\t\t.sort((left, right) => left.task.startedAt - right.task.startedAt);\n\t\tif (!eligible.length) return 0;\n\t\tconst free = this.maxBackground - this.backgroundActive();\n\t\tif (free <= 0) throw this.limitError();\n\t\tconst executions = eligible.slice(0, free);\n\t\tfor (const execution of executions) execution.requestDetach();\n\t\tfor (const execution of executions) execution.completeDetach();\n\t\tthis.emit();\n\t\treturn executions.length;\n\t}\n\n\tcanDetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\treturn this.enabled && this.backgroundActive() < this.maxBackground && this.detachable(record);\n\t}\n\n\tdetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\tif (!this.enabled || !this.detachable(record)) return false;\n\t\tif (this.backgroundActive() >= this.maxBackground) throw this.limitError();\n\t\tconst execution = this.executions.get(record.task.id)!;\n\t\texecution.requestDetach();\n\t\texecution.completeDetach();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tlist(): TaskSnapshot[] {\n\t\treturn this.store.visible().map((record) => record.snapshot());\n\t}\n\n\tprivate lookup(id: string): TaskRecord {\n\t\tconst exact = this.store.get(id);\n\t\tif (exact) return exact;\n\t\tconst matches = this.store.match(id);\n\t\tif (!id || matches.length !== 1) {\n\t\t\tthrow new TaskLookupError(\n\t\t\t\tmatches.length > 1 ? \"ambiguous\" : \"unknown\",\n\t\t\t\tmatches.map((record) => record.snapshot()),\n\t\t\t);\n\t\t}\n\t\treturn matches[0]!;\n\t}\n\n\tget(id: string): TaskSnapshot {\n\t\treturn this.lookup(id).snapshot();\n\t}\n\n\tasync read(id: string, options: TaskReadOptions = {}): Promise<TaskRead> {\n\t\tconst record = this.lookup(id);\n\t\tconst release = this.retain(record.task.id);\n\t\ttry {\n\t\t\tconst task = record.snapshot();\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: TaskSnapshot): string {\n\t\treturn task.result?.text || task.error || \"No output yet.\";\n\t}\n\n\t/** One event-driven waiter can observe a whole waitAny cohort without per-task timers. */\n\tprivate waitForRecords(\n\t\trecords: readonly TaskRecord[],\n\t\ttimeoutMs: number,\n\t\tsignal?: AbortSignal,\n\t\tinterruptSignal?: AbortSignal,\n\t): Promise<void> {\n\t\tif (records.some((record) => record.settled) || interruptSignal?.aborted) return Promise.resolve();\n\t\treturn new Promise<void>((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\tinterruptSignal?.removeEventListener(\"abort\", interrupt);\n\t\t\t\tfor (const record of records) record.waiters.delete(wake);\n\t\t\t\tif (aborted) reject(signal?.reason ?? new Error(\"Wait aborted\"));\n\t\t\t\telse resolve();\n\t\t\t\tthis.store.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\tconst interrupt = () => complete();\n\t\t\tfor (const record of records) record.waiters.add(wake);\n\t\t\tsignal?.addEventListener(\"abort\", abort, { once: true });\n\t\t\tinterruptSignal?.addEventListener(\"abort\", interrupt, { once: true });\n\t\t\ttimer = setTimeout(wake, boundWaitMs(timeoutMs));\n\t\t\tif (this.closed || interruptSignal?.aborted) wake();\n\t\t\tif (signal?.aborted) abort();\n\t\t});\n\t}\n\n\t/**\n\t * One observation: hold delivery for the observed records, wait, read, then register the\n\t * receipt with the host, and only then release. Nothing the caller does between those steps\n\t * can leak a settled result into an automatic notification or lose it.\n\t */\n\tprivate async observe(\n\t\trecords: readonly TaskRecord[],\n\t\toptions: TaskWaitOptions,\n\t\t/** Record to read when none settled; a cohort has none. */\n\t\tfallback?: TaskRecord,\n\t): Promise<{\n\t\toutcome: TaskWaitOutcome;\n\t\twaitedMs: number;\n\t\tsettled?: TaskRecord;\n\t\trunning: TaskSnapshot[];\n\t\tread?: TaskRead;\n\t}> {\n\t\tconst { signal } = options;\n\t\tconst releases = records.map((record) => this.holdRecord(record));\n\t\ttry {\n\t\t\tconst start = Date.now();\n\t\t\tconst interrupt = this.options.waits?.interruptSignal;\n\t\t\tawait this.waitForRecords(records, options.timeoutMs ?? TASKS_WAIT_DEFAULT_MS, signal, interrupt);\n\t\t\tconst waitedMs = Date.now() - start;\n\t\t\tconst settled = records\n\t\t\t\t.filter((record) => record.settled)\n\t\t\t\t.sort((left, right) => (left.task.endedAt ?? 0) - (right.task.endedAt ?? 0))[0];\n\t\t\tconst outcome: TaskWaitOutcome = settled\n\t\t\t\t? \"settled\"\n\t\t\t\t: this.closed\n\t\t\t\t\t? \"closed\"\n\t\t\t\t\t: interrupt?.aborted\n\t\t\t\t\t\t? \"interrupted\"\n\t\t\t\t\t\t: \"timed_out\";\n\t\t\tconst running = records\n\t\t\t\t.filter((record) => record.visible && !record.settled)\n\t\t\t\t.map((record) => record.snapshot());\n\t\t\tconst observed = settled ?? fallback;\n\t\t\tconst read =\n\t\t\t\toptions.read && observed && outcome !== \"interrupted\"\n\t\t\t\t\t? await this.read(observed.task.id, options.read)\n\t\t\t\t\t: undefined;\n\t\t\tsignal?.throwIfAborted();\n\t\t\tif (settled && settled.task.mode === \"background\" && options.toolCallId)\n\t\t\t\tthis.options.waits?.bind(options.toolCallId, settled.task.id);\n\t\t\treturn { outcome, waitedMs, settled, running, read };\n\t\t} finally {\n\t\t\tfor (const release of releases) release();\n\t\t}\n\t}\n\n\tasync wait(id: string, options: TaskWaitOptions = {}): Promise<TaskWaitResult> {\n\t\tif (options.signal?.aborted) throw options.signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst record = this.lookup(id);\n\t\tconst { outcome, waitedMs, read } = await this.observe([record], options, record);\n\t\treturn { outcome, waitedMs, task: record.snapshot(), ...(read ? { read } : {}) };\n\t}\n\n\tasync waitAny(options: TaskWaitAnyOptions = {}): Promise<TaskWaitAnyResult> {\n\t\tif (options.signal?.aborted) throw options.signal.reason ?? new Error(\"Wait aborted\");\n\t\tconst records = this.activeBackground().filter((record) => record.visible);\n\t\tif (records.length === 0) return { outcome: \"no_tasks\", waitedMs: 0, running: [] };\n\t\tconst { outcome, waitedMs, settled, running, read } = await this.observe(records, options);\n\t\treturn {\n\t\t\toutcome,\n\t\t\twaitedMs,\n\t\t\trunning,\n\t\t\t...(settled ? { task: settled.snapshot() } : {}),\n\t\t\t...(read ? { read } : {}),\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: TaskRecord): boolean {\n\t\treturn this.executions.get(record.task.id)?.cancel() ?? false;\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 * Retention protects snapshots and logs only. Delivery has its own explicit hold.\n\t */\n\tretain(id: string): () => void {\n\t\treturn this.pin(this.lookup(id));\n\t}\n\n\tprivate pin(record: TaskRecord): () => void {\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.store.trim();\n\t\t\t// Listeners decide whether delivery may proceed; TaskDelivery owns pausing.\n\t\t\tif (!this.closed && record.deliverable) this.emit();\n\t\t};\n\t}\n\n\tholdDelivery(id: string): () => void {\n\t\treturn this.holdRecord(this.lookup(id));\n\t}\n\n\tprivate holdRecord(record: TaskRecord): () => void {\n\t\tconst releasePin = this.pin(record);\n\t\trecord.deliveryHolds++;\n\t\tlet released = false;\n\t\treturn () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\trecord.deliveryHolds--;\n\t\t\treleasePin();\n\t\t};\n\t}\n\n\tpendingNotifications(): TaskSnapshot[] {\n\t\tif (this.closed) return [];\n\t\treturn this.store.deliverable().map((record) => record.snapshot());\n\t}\n\n\tclaimNotification(id: string): boolean {\n\t\treturn !this.closed && (this.store.get(id)?.claim() ?? false);\n\t}\n\n\tmarkDelivered(id: string): void {\n\t\tconst record = this.store.get(id);\n\t\tif (!record) return;\n\t\trecord.acknowledge();\n\t\tthis.store.trim();\n\t}\n\n\treleaseNotification(id: string): void {\n\t\tif (!this.store.get(id)?.unclaim()) return;\n\t\tthis.store.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.store.all()) {\n\t\t\tthis.executions.get(record.task.id)?.releaseParent();\n\t\t\tthis.cancel(record);\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t}\n\t\tthis.store.trim();\n\t}\n\n\tasync shutdown(graceMs = 2000): Promise<void> {\n\t\tthis.close();\n\t\tawait this.drain(this.store.all(), graceMs);\n\t}\n\n\t/** Running tasks whose launch anchor is outside the branch made of `ancestors`. */\n\tactiveOutsideBranch(ancestors: ReadonlySet<string>): TaskSnapshot[] {\n\t\treturn this.store\n\t\t\t.unsettled()\n\t\t\t.filter((record) => record.task.anchorId !== null && !ancestors.has(record.task.anchorId))\n\t\t\t.map((record) => record.snapshot());\n\t}\n\n\t/**\n\t * Hidden results stay pending: returning to their branch delivers them again.\n\t * Restored history is already delivered.\n\t */\n\tasync cancelOutsideBranch(ancestors: ReadonlySet<string>): Promise<void> {\n\t\tconst records = this.store.all();\n\t\tfor (const record of records)\n\t\t\trecord.visible = record.task.anchorId === null || ancestors.has(record.task.anchorId);\n\t\tconst outside = records.filter((record) => !record.visible);\n\t\tfor (const record of outside) this.cancel(record);\n\t\tthis.store.trim();\n\t\tthis.emit();\n\t\tawait this.drain(outside, 2000);\n\t}\n\n\tprivate async drain(records: TaskRecord[], 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) => this.executions.get(record.task.id)?.done)).then(() =>\n\t\t\t\t\tthis.store.cleanupsDone(),\n\t\t\t\t),\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 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"]}
|
|
@@ -37,7 +37,6 @@ export declare class TaskSession {
|
|
|
37
37
|
private readonly quarantine;
|
|
38
38
|
constructor(options: TaskSessionOptions);
|
|
39
39
|
get service(): TaskRuntime;
|
|
40
|
-
get waitInterruptSignal(): AbortSignal;
|
|
41
40
|
/** End only current task waits; the next wait observes a fresh signal. */
|
|
42
41
|
interruptWaits(): void;
|
|
43
42
|
noteCompaction(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/session.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAmB,MAAM,+BAA+B,CAAC;AACnF,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;AAI1E,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;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AAI,OAAO,IAAI,WAAW,CAEzB;IAED,0EAA0E;IAC1E,cAAc,IAAI,IAAI;IAMtB,cAAc,IAAI,IAAI;IAItB,sBAAsB,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,YAAY,EAAE;IAIhE,sBAAsB,IAAI,IAAI;IAI9B,IAAI,sBAAsB,IAAI,SAAS,yBAAyB,EAAE,CAEjE;IAED,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAKlC;;;;OAIG;IACH,uBAAuB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,cAAe,GAAG,YAAY,EAAE;IAUjF,2EAA2E;IAC3E,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAIzD,OAAO,CAAC,SAAS;IAIjB,2FAA2F;IAC3F,cAAc,IAAI,IAAI;IAOtB,OAAO,CAAC,aAAa;IAoCrB,cAAc,CAAC,OAAO,cAAe,GAAG,IAAI;IAW5C,OAAO,CAAC,oBAAoB;IAsB5B,8FAA8F;IAC9F,OAAO,CAAC,iBAAiB;IAkBzB,OAAO,CAAC,IAAI;IAQZ,OAAO,IAAI,IAAI;CAOf"}
|
|
@@ -27,9 +27,6 @@ export class TaskSession {
|
|
|
27
27
|
get service() {
|
|
28
28
|
return this._service;
|
|
29
29
|
}
|
|
30
|
-
get waitInterruptSignal() {
|
|
31
|
-
return this.waitInterrupt.signal;
|
|
32
|
-
}
|
|
33
30
|
/** End only current task waits; the next wait observes a fresh signal. */
|
|
34
31
|
interruptWaits() {
|
|
35
32
|
const previous = this.waitInterrupt;
|
|
@@ -85,17 +82,19 @@ export class TaskSession {
|
|
|
85
82
|
const generation = ++this.generation;
|
|
86
83
|
const sessionId = manager.getSessionId();
|
|
87
84
|
const sessionFile = manager.getSessionFile();
|
|
88
|
-
const
|
|
85
|
+
const interrupts = () => this.waitInterrupt.signal;
|
|
89
86
|
const service = new TaskRuntime({
|
|
90
87
|
enabled: this.enabled,
|
|
91
88
|
backgroundAllowed,
|
|
92
89
|
session: {
|
|
93
|
-
get waitInterruptSignal() {
|
|
94
|
-
return waitInterruptSignal();
|
|
95
|
-
},
|
|
96
|
-
prepareWait: (toolCallId, taskId) => this.delivery.prepareWait(toolCallId, taskId),
|
|
97
90
|
stoppedByTreeNavigation: (targetId) => this.stoppedByTreeNavigation(targetId, service),
|
|
98
91
|
},
|
|
92
|
+
waits: {
|
|
93
|
+
get interruptSignal() {
|
|
94
|
+
return interrupts();
|
|
95
|
+
},
|
|
96
|
+
bind: (toolCallId, taskId) => this.delivery.bindWait(service, toolCallId, taskId),
|
|
97
|
+
},
|
|
99
98
|
anchor: () => manager.getLeafId(),
|
|
100
99
|
onCleanupError: (message) => this.warn("task_cleanup", message),
|
|
101
100
|
onSettled: (task, usage) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/core/tasks/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,sBAAsB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAwB3C,+FAA+F;AAC/F,MAAM,OAAO,WAAW;IAWvB,YAAY,OAA2B;QAR/B,YAAO,GAAG,KAAK,CAAC;QAChB,aAAQ,GAAG,KAAK,CAAC;QACjB,eAAU,GAAG,CAAC,CAAC;QACf,kBAAa,GAAG,IAAI,eAAe,EAAE,CAAC;QAC7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,CAAC;CACD","sourcesContent":["import { appendFileSync, mkdirSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport type { AgentMessage, AgentToolResult } 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 { getTaskUsageRecord } from \"../usage-totals.ts\";\nimport { TASK_RECORD_TYPE, TASK_SNAPSHOT_VERSION } from \"./codec.ts\";\nimport { TaskDelivery } from \"./delivery.ts\";\nimport { TaskContextReminder } from \"./reminder.ts\";\nimport { TaskRuntime } from \"./runtime.ts\";\nimport type { TaskSnapshot } from \"./types.ts\";\n\ninterface TaskSessionOptions {\n\tmanager: SessionManager;\n\tbackgroundAllowed?: boolean;\n\t/** The main session owns input queues, preflight and idle state. */\n\tcanDeliver(): boolean;\n\t/**\n\t * Start a completion turn, or enqueue the message and return waitForPersistence().\n\t * The host owns input routing; this adapter owns the queued delivery's lifetime.\n\t */\n\tdeliver(message: CustomMessage, waitForPersistence: () => Promise<void>): Promise<void>;\n\tonEntry(entry: SessionEntry): void;\n\tonError(event: string, message: string): void;\n}\n\nexport interface QuarantinedTaskSettlement {\n\tsessionId: string;\n\tgeneration: number;\n\ttask: TaskSnapshot;\n\tusage?: Usage;\n}\n\n/** Session persistence and completion delivery; execution supervision stays in TaskRuntime. */\nexport class TaskSession {\n\tprivate readonly options: TaskSessionOptions;\n\tprivate _service: TaskRuntime;\n\tprivate enabled = false;\n\tprivate disposed = false;\n\tprivate generation = 0;\n\tprivate waitInterrupt = new AbortController();\n\tprivate readonly contextReminder = new TaskContextReminder();\n\treadonly delivery: TaskDelivery;\n\tprivate readonly quarantine: QuarantinedTaskSettlement[] = [];\n\n\tconstructor(options: TaskSessionOptions) {\n\t\tthis.options = options;\n\t\tthis.delivery = new TaskDelivery({\n\t\t\tservice: () => this.service,\n\t\t\tcanDeliver: options.canDeliver,\n\t\t\tdeliver: options.deliver,\n\t\t\twarn: (event, message) => this.warn(event, message),\n\t\t});\n\t\tthis._service = this.createService();\n\t}\n\n\tget service(): TaskRuntime {\n\t\treturn this._service;\n\t}\n\n\tget waitInterruptSignal(): AbortSignal {\n\t\treturn this.waitInterrupt.signal;\n\t}\n\n\t/** End only current task waits; the next wait observes a fresh signal. */\n\tinterruptWaits(): void {\n\t\tconst previous = this.waitInterrupt;\n\t\tthis.waitInterrupt = new AbortController();\n\t\tprevious.abort();\n\t}\n\n\tnoteCompaction(): void {\n\t\tthis.contextReminder.compacted();\n\t}\n\n\tprojectContextReminder(messages: AgentMessage[]): AgentMessage[] {\n\t\treturn this.contextReminder.project(this.service, messages);\n\t}\n\n\tnoteAssistantCompleted(): void {\n\t\tthis.contextReminder.assistantCompleted();\n\t}\n\n\tget quarantinedSettlements(): readonly QuarantinedTaskSettlement[] {\n\t\treturn structuredClone(this.quarantine);\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.enabled = enabled && this.options.backgroundAllowed !== false;\n\t\tthis.service.setEnabled(this.enabled);\n\t}\n\n\t/**\n\t * Running tasks that navigating to `targetId` would cancel, since results are saved on their\n\t * launch branch. Mirrors navigateTree's destination: selecting a user or custom message moves\n\t * the leaf to its parent.\n\t */\n\tstoppedByTreeNavigation(targetId: string, service = this.service): TaskSnapshot[] {\n\t\tconst target = this.options.manager.getEntry(targetId);\n\t\tif (!target) return [];\n\t\tconst leafId =\n\t\t\t(target.type === \"message\" && target.message.role === \"user\") || target.type === \"custom_message\"\n\t\t\t\t? target.parentId\n\t\t\t\t: targetId;\n\t\treturn service.activeOutsideBranch(this.branchIds(leafId));\n\t}\n\n\t/** Cancel running tasks launched outside the branch ending at `leafId`. */\n\tcancelOutsideBranch(leafId: string | null): Promise<void> {\n\t\treturn this.service.cancelOutsideBranch(this.branchIds(leafId));\n\t}\n\n\tprivate branchIds(leafId: string | null): Set<string> {\n\t\treturn new Set(leafId === null ? [] : this.options.manager.getBranch(leafId).map((entry) => entry.id));\n\t}\n\n\t/** Called after the old service's bounded shutdown, while lifecycle delivery is paused. */\n\treplaceService(): void {\n\t\tthis.contextReminder.reset();\n\t\tthis.service.close();\n\t\tthis._service = this.createService();\n\t\tthis.delivery.retry();\n\t}\n\n\tprivate createService(): TaskRuntime {\n\t\tconst { manager, backgroundAllowed } = this.options;\n\t\tconst generation = ++this.generation;\n\t\tconst sessionId = manager.getSessionId();\n\t\tconst sessionFile = manager.getSessionFile();\n\t\tconst waitInterruptSignal = () => this.waitInterruptSignal;\n\t\tconst service: TaskRuntime = new TaskRuntime({\n\t\t\tenabled: this.enabled,\n\t\t\tbackgroundAllowed,\n\t\t\tsession: {\n\t\t\t\tget waitInterruptSignal() {\n\t\t\t\t\treturn waitInterruptSignal();\n\t\t\t\t},\n\t\t\t\tprepareWait: (toolCallId, taskId) => this.delivery.prepareWait(toolCallId, taskId),\n\t\t\t\tstoppedByTreeNavigation: (targetId): TaskSnapshot[] => this.stoppedByTreeNavigation(targetId, service),\n\t\t\t},\n\t\t\tanchor: () => manager.getLeafId(),\n\t\t\tonCleanupError: (message) => this.warn(\"task_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.delivery.schedule());\n\t\treturn service;\n\t}\n\n\trestoreHistory(service = this.service): void {\n\t\tconst records: unknown[] = [];\n\t\tconst toolResults = new Map<string, AgentToolResult<unknown>[\"content\"]>();\n\t\tfor (const entry of this.options.manager.getBranch()) {\n\t\t\tif (entry.type === \"custom\" && entry.customType === TASK_RECORD_TYPE) records.push(entry.data);\n\t\t\telse if (entry.type === \"message\" && entry.message.role === \"toolResult\")\n\t\t\t\ttoolResults.set(entry.message.toolCallId, entry.message.content);\n\t\t}\n\t\tservice.restoreHistory(records, toolResults);\n\t}\n\n\tprivate quarantineSettlement(record: QuarantinedTaskSettlement, 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 quarantinedTaskSettlements; 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}.tasks-late.jsonl`, `${JSON.stringify({ version: 1, ...record })}\\n`);\n\t\t\t\tpersistence = `Saved diagnostic sidecar: ${sessionFile}.tasks-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\"task_settlement_quarantined\",\n\t\t\t`Late background settlement ${record.task.id} was quarantined. ${persistence}`,\n\t\t);\n\t}\n\n\t/** One entry per settlement: the bounded terminal snapshot and its first usage settlement. */\n\tprivate persistSettlement(task: TaskSnapshot, usage: Usage | undefined): void {\n\t\tconst manager = this.options.manager;\n\t\tconst accounted = usage && manager.getEntries().some((entry) => getTaskUsageRecord(entry)?.taskId === task.id);\n\t\t// A foreground result is the tool result the transcript already saves; restoration reads it from there.\n\t\tconst { result: _result, ...metadata } = task;\n\t\tconst saved = task.mode === \"foreground\" ? metadata : task;\n\t\tconst data = JSON.parse(\n\t\t\tJSON.stringify({ version: TASK_SNAPSHOT_VERSION, task: saved, ...(usage && !accounted ? { usage } : {}) }),\n\t\t);\n\t\tconst entry = manager.getEntry(manager.appendCustomEntry(TASK_RECORD_TYPE, data));\n\t\tif (!entry) return;\n\t\ttry {\n\t\t\tthis.options.onEntry(entry);\n\t\t} catch {\n\t\t\t// Observers cannot interrupt settlement or result publication.\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\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.contextReminder.reset();\n\t\tthis.interruptWaits();\n\t\tthis.service.close();\n\t\tthis.delivery.dispose();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/core/tasks/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,sBAAsB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAwB3C,+FAA+F;AAC/F,MAAM,OAAO,WAAW;IAWvB,YAAY,OAA2B;QAR/B,YAAO,GAAG,KAAK,CAAC;QAChB,aAAQ,GAAG,KAAK,CAAC;QACjB,eAAU,GAAG,CAAC,CAAC;QACf,kBAAa,GAAG,IAAI,eAAe,EAAE,CAAC;QAC7B,oBAAe,GAAG,IAAI,mBAAmB,E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port type { AgentMessage, AgentToolResult } 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 { getTaskUsageRecord } from \"../usage-totals.ts\";\nimport { TASK_RECORD_TYPE, TASK_SNAPSHOT_VERSION } from \"./codec.ts\";\nimport { TaskDelivery } from \"./delivery.ts\";\nimport { TaskContextReminder } from \"./reminder.ts\";\nimport { TaskRuntime } from \"./runtime.ts\";\nimport type { TaskSnapshot } from \"./types.ts\";\n\ninterface TaskSessionOptions {\n\tmanager: SessionManager;\n\tbackgroundAllowed?: boolean;\n\t/** The main session owns input queues, preflight and idle state. */\n\tcanDeliver(): boolean;\n\t/**\n\t * Start a completion turn, or enqueue the message and return waitForPersistence().\n\t * The host owns input routing; this adapter owns the queued delivery's lifetime.\n\t */\n\tdeliver(message: CustomMessage, waitForPersistence: () => Promise<void>): Promise<void>;\n\tonEntry(entry: SessionEntry): void;\n\tonError(event: string, message: string): void;\n}\n\nexport interface QuarantinedTaskSettlement {\n\tsessionId: string;\n\tgeneration: number;\n\ttask: TaskSnapshot;\n\tusage?: Usage;\n}\n\n/** Session persistence and completion delivery; execution supervision stays in TaskRuntime. */\nexport class TaskSession {\n\tprivate readonly options: TaskSessionOptions;\n\tprivate _service: TaskRuntime;\n\tprivate enabled = false;\n\tprivate disposed = false;\n\tprivate generation = 0;\n\tprivate waitInterrupt = new AbortController();\n\tprivate readonly contextReminder = new TaskContextReminder();\n\treadonly delivery: TaskDelivery;\n\tprivate readonly quarantine: QuarantinedTaskSettlement[] = [];\n\n\tconstructor(options: TaskSessionOptions) {\n\t\tthis.options = options;\n\t\tthis.delivery = new TaskDelivery({\n\t\t\tservice: () => this.service,\n\t\t\tcanDeliver: options.canDeliver,\n\t\t\tdeliver: options.deliver,\n\t\t\twarn: (event, message) => this.warn(event, message),\n\t\t});\n\t\tthis._service = this.createService();\n\t}\n\n\tget service(): TaskRuntime {\n\t\treturn this._service;\n\t}\n\n\t/** End only current task waits; the next wait observes a fresh signal. */\n\tinterruptWaits(): void {\n\t\tconst previous = this.waitInterrupt;\n\t\tthis.waitInterrupt = new AbortController();\n\t\tprevious.abort();\n\t}\n\n\tnoteCompaction(): void {\n\t\tthis.contextReminder.compacted();\n\t}\n\n\tprojectContextReminder(messages: AgentMessage[]): AgentMessage[] {\n\t\treturn this.contextReminder.project(this.service, messages);\n\t}\n\n\tnoteAssistantCompleted(): void {\n\t\tthis.contextReminder.assistantCompleted();\n\t}\n\n\tget quarantinedSettlements(): readonly QuarantinedTaskSettlement[] {\n\t\treturn structuredClone(this.quarantine);\n\t}\n\n\tsetEnabled(enabled: boolean): void {\n\t\tthis.enabled = enabled && this.options.backgroundAllowed !== false;\n\t\tthis.service.setEnabled(this.enabled);\n\t}\n\n\t/**\n\t * Running tasks that navigating to `targetId` would cancel, since results are saved on their\n\t * launch branch. Mirrors navigateTree's destination: selecting a user or custom message moves\n\t * the leaf to its parent.\n\t */\n\tstoppedByTreeNavigation(targetId: string, service = this.service): TaskSnapshot[] {\n\t\tconst target = this.options.manager.getEntry(targetId);\n\t\tif (!target) return [];\n\t\tconst leafId =\n\t\t\t(target.type === \"message\" && target.message.role === \"user\") || target.type === \"custom_message\"\n\t\t\t\t? target.parentId\n\t\t\t\t: targetId;\n\t\treturn service.activeOutsideBranch(this.branchIds(leafId));\n\t}\n\n\t/** Cancel running tasks launched outside the branch ending at `leafId`. */\n\tcancelOutsideBranch(leafId: string | null): Promise<void> {\n\t\treturn this.service.cancelOutsideBranch(this.branchIds(leafId));\n\t}\n\n\tprivate branchIds(leafId: string | null): Set<string> {\n\t\treturn new Set(leafId === null ? [] : this.options.manager.getBranch(leafId).map((entry) => entry.id));\n\t}\n\n\t/** Called after the old service's bounded shutdown, while lifecycle delivery is paused. */\n\treplaceService(): void {\n\t\tthis.contextReminder.reset();\n\t\tthis.service.close();\n\t\tthis._service = this.createService();\n\t\tthis.delivery.retry();\n\t}\n\n\tprivate createService(): TaskRuntime {\n\t\tconst { manager, backgroundAllowed } = this.options;\n\t\tconst generation = ++this.generation;\n\t\tconst sessionId = manager.getSessionId();\n\t\tconst sessionFile = manager.getSessionFile();\n\t\tconst interrupts = () => this.waitInterrupt.signal;\n\t\tconst service: TaskRuntime = new TaskRuntime({\n\t\t\tenabled: this.enabled,\n\t\t\tbackgroundAllowed,\n\t\t\tsession: {\n\t\t\t\tstoppedByTreeNavigation: (targetId): TaskSnapshot[] => this.stoppedByTreeNavigation(targetId, service),\n\t\t\t},\n\t\t\twaits: {\n\t\t\t\tget interruptSignal() {\n\t\t\t\t\treturn interrupts();\n\t\t\t\t},\n\t\t\t\tbind: (toolCallId, taskId) => this.delivery.bindWait(service, toolCallId, taskId),\n\t\t\t},\n\t\t\tanchor: () => manager.getLeafId(),\n\t\t\tonCleanupError: (message) => this.warn(\"task_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.delivery.schedule());\n\t\treturn service;\n\t}\n\n\trestoreHistory(service = this.service): void {\n\t\tconst records: unknown[] = [];\n\t\tconst toolResults = new Map<string, AgentToolResult<unknown>[\"content\"]>();\n\t\tfor (const entry of this.options.manager.getBranch()) {\n\t\t\tif (entry.type === \"custom\" && entry.customType === TASK_RECORD_TYPE) records.push(entry.data);\n\t\t\telse if (entry.type === \"message\" && entry.message.role === \"toolResult\")\n\t\t\t\ttoolResults.set(entry.message.toolCallId, entry.message.content);\n\t\t}\n\t\tservice.restoreHistory(records, toolResults);\n\t}\n\n\tprivate quarantineSettlement(record: QuarantinedTaskSettlement, 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 quarantinedTaskSettlements; 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}.tasks-late.jsonl`, `${JSON.stringify({ version: 1, ...record })}\\n`);\n\t\t\t\tpersistence = `Saved diagnostic sidecar: ${sessionFile}.tasks-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\"task_settlement_quarantined\",\n\t\t\t`Late background settlement ${record.task.id} was quarantined. ${persistence}`,\n\t\t);\n\t}\n\n\t/** One entry per settlement: the bounded terminal snapshot and its first usage settlement. */\n\tprivate persistSettlement(task: TaskSnapshot, usage: Usage | undefined): void {\n\t\tconst manager = this.options.manager;\n\t\tconst accounted = usage && manager.getEntries().some((entry) => getTaskUsageRecord(entry)?.taskId === task.id);\n\t\t// A foreground result is the tool result the transcript already saves; restoration reads it from there.\n\t\tconst { result: _result, ...metadata } = task;\n\t\tconst saved = task.mode === \"foreground\" ? metadata : task;\n\t\tconst data = JSON.parse(\n\t\t\tJSON.stringify({ version: TASK_SNAPSHOT_VERSION, task: saved, ...(usage && !accounted ? { usage } : {}) }),\n\t\t);\n\t\tconst entry = manager.getEntry(manager.appendCustomEntry(TASK_RECORD_TYPE, data));\n\t\tif (!entry) return;\n\t\ttry {\n\t\t\tthis.options.onEntry(entry);\n\t\t} catch {\n\t\t\t// Observers cannot interrupt settlement or result publication.\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\tdispose(): void {\n\t\tthis.disposed = true;\n\t\tthis.contextReminder.reset();\n\t\tthis.interruptWaits();\n\t\tthis.service.close();\n\t\tthis.delivery.dispose();\n\t}\n}\n"]}
|
|
@@ -1,38 +1,31 @@
|
|
|
1
1
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
2
|
-
import
|
|
3
|
-
export interface TaskRecord {
|
|
4
|
-
/** The runtime's working copy. Call changed() after every mutation. */
|
|
5
|
-
task: TaskSnapshot;
|
|
6
|
-
settled: boolean;
|
|
7
|
-
/** Whether the launch anchor is on the selected branch. */
|
|
8
|
-
visible: boolean;
|
|
9
|
-
/**
|
|
10
|
-
* none: running, or answered inline by its tool call; pending: a settled handoff
|
|
11
|
-
* awaiting automatic delivery; claimed: handed to the host; delivered: acknowledged.
|
|
12
|
-
*/
|
|
13
|
-
delivery: "none" | "pending" | "claimed" | "delivered";
|
|
14
|
-
pins: number;
|
|
15
|
-
deliveryHolds: number;
|
|
16
|
-
cleanup?: () => void | Promise<void>;
|
|
17
|
-
readError?: string;
|
|
18
|
-
waiters: Set<() => void>;
|
|
19
|
-
/** Frozen snapshot shared by readers until the task changes. */
|
|
20
|
-
snapshot?: TaskSnapshot;
|
|
21
|
-
}
|
|
2
|
+
import { TaskRecord } from "./record.ts";
|
|
22
3
|
export declare const EXPIRED_OUTPUT = "Output has expired: the managed log was released; showing the stored result.";
|
|
23
|
-
/** Readers share one frozen copy, so polling and status rendering never clone unchanged output. */
|
|
24
|
-
export declare function snapshotOf(record: TaskRecord): TaskSnapshot;
|
|
25
|
-
export declare function changed(record: TaskRecord): void;
|
|
26
4
|
/** Retained snapshots and output leases. This store never owns executable handles. */
|
|
27
5
|
export declare class TaskStore {
|
|
28
|
-
readonly records
|
|
29
|
-
readonly cleanups
|
|
6
|
+
private readonly records;
|
|
7
|
+
private readonly cleanups;
|
|
30
8
|
private readonly maxHistory;
|
|
31
9
|
private readonly maxRetained;
|
|
32
10
|
private readonly isClosed;
|
|
33
11
|
private readonly onCleanupError?;
|
|
34
12
|
constructor(maxHistory: number, maxRetained: number, isClosed: () => boolean, onCleanupError?: (message: string) => void);
|
|
35
13
|
private get closed();
|
|
14
|
+
get(id: string): TaskRecord | undefined;
|
|
15
|
+
/** Records whose ID, or whose ID without its kind prefix, starts with `prefix`. */
|
|
16
|
+
match(prefix: string): TaskRecord[];
|
|
17
|
+
add(record: TaskRecord): void;
|
|
18
|
+
all(): TaskRecord[];
|
|
19
|
+
/** Records whose execution has not settled, queued or running. */
|
|
20
|
+
unsettled(): TaskRecord[];
|
|
21
|
+
/** Records on the selected branch. */
|
|
22
|
+
visible(): TaskRecord[];
|
|
23
|
+
/** Settled handoffs eligible for automatic delivery. */
|
|
24
|
+
deliverable(): TaskRecord[];
|
|
25
|
+
/** Records plus output cleanups still running; admission bounds this. */
|
|
26
|
+
retainedCount(): number;
|
|
27
|
+
/** Settles once every output cleanup started so far has finished. */
|
|
28
|
+
cleanupsDone(): Promise<unknown>;
|
|
36
29
|
/**
|
|
37
30
|
* Foreground records save no output of their own: their tool result already holds it,
|
|
38
31
|
* so `toolResults` maps each tool call ID on the branch to that content.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAGrE,OAAO,
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,E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AsBrB,0FAA0F;IAC1F,OAAO,CAAC,cAAc;IAItB,IAAI,IAAI,IAAI;CAoBZ"}
|
package/dist/core/tasks/store.js
CHANGED
|
@@ -1,30 +1,7 @@
|
|
|
1
1
|
import { readVersionedTask } from "./codec.js";
|
|
2
|
-
import {
|
|
2
|
+
import { errorText, resultText } from "./output.js";
|
|
3
|
+
import { TaskRecord } from "./record.js";
|
|
3
4
|
export const EXPIRED_OUTPUT = "Output has expired: the managed log was released; showing the stored result.";
|
|
4
|
-
function freeze(value) {
|
|
5
|
-
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
|
6
|
-
for (const child of Object.values(value))
|
|
7
|
-
freeze(child);
|
|
8
|
-
Object.freeze(value);
|
|
9
|
-
}
|
|
10
|
-
return value;
|
|
11
|
-
}
|
|
12
|
-
/** Readers share one frozen copy, so polling and status rendering never clone unchanged output. */
|
|
13
|
-
export function snapshotOf(record) {
|
|
14
|
-
record.snapshot ??= freeze(structuredClone(record.task));
|
|
15
|
-
return record.snapshot;
|
|
16
|
-
}
|
|
17
|
-
export function changed(record) {
|
|
18
|
-
record.snapshot = undefined;
|
|
19
|
-
}
|
|
20
|
-
function errorText(error) {
|
|
21
|
-
try {
|
|
22
|
-
return boundText(error instanceof Error ? error.message : String(error), 4096);
|
|
23
|
-
}
|
|
24
|
-
catch {
|
|
25
|
-
return "Task cleanup failed";
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
5
|
function oldestTask(tasks) {
|
|
29
6
|
let oldest;
|
|
30
7
|
for (const task of tasks) {
|
|
@@ -47,6 +24,39 @@ export class TaskStore {
|
|
|
47
24
|
get closed() {
|
|
48
25
|
return this.isClosed();
|
|
49
26
|
}
|
|
27
|
+
get(id) {
|
|
28
|
+
return this.records.get(id);
|
|
29
|
+
}
|
|
30
|
+
/** Records whose ID, or whose ID without its kind prefix, starts with `prefix`. */
|
|
31
|
+
match(prefix) {
|
|
32
|
+
return this.all().filter(({ task }) => task.id.startsWith(prefix) || task.id.slice(task.kind.length + 1).startsWith(prefix));
|
|
33
|
+
}
|
|
34
|
+
add(record) {
|
|
35
|
+
this.records.set(record.task.id, record);
|
|
36
|
+
}
|
|
37
|
+
all() {
|
|
38
|
+
return [...this.records.values()];
|
|
39
|
+
}
|
|
40
|
+
/** Records whose execution has not settled, queued or running. */
|
|
41
|
+
unsettled() {
|
|
42
|
+
return this.all().filter((record) => !record.settled);
|
|
43
|
+
}
|
|
44
|
+
/** Records on the selected branch. */
|
|
45
|
+
visible() {
|
|
46
|
+
return this.all().filter((record) => record.visible);
|
|
47
|
+
}
|
|
48
|
+
/** Settled handoffs eligible for automatic delivery. */
|
|
49
|
+
deliverable() {
|
|
50
|
+
return this.all().filter((record) => record.deliverable);
|
|
51
|
+
}
|
|
52
|
+
/** Records plus output cleanups still running; admission bounds this. */
|
|
53
|
+
retainedCount() {
|
|
54
|
+
return this.records.size + this.cleanups.size;
|
|
55
|
+
}
|
|
56
|
+
/** Settles once every output cleanup started so far has finished. */
|
|
57
|
+
cleanupsDone() {
|
|
58
|
+
return Promise.all(this.cleanups);
|
|
59
|
+
}
|
|
50
60
|
/**
|
|
51
61
|
* Foreground records save no output of their own: their tool result already holds it,
|
|
52
62
|
* so `toolResults` maps each tool call ID on the branch to that content.
|
|
@@ -59,7 +69,7 @@ export class TaskStore {
|
|
|
59
69
|
const foreground = history.filter((record) => isForeground(record.task)).length;
|
|
60
70
|
const foregroundCapacity = Math.max(0, this.maxHistory - foreground);
|
|
61
71
|
const backgroundCapacity = Math.max(0, this.maxHistory - (history.length - foreground));
|
|
62
|
-
const capacity = Math.max(0, Math.min(foregroundCapacity + backgroundCapacity, this.maxRetained - this.
|
|
72
|
+
const capacity = Math.max(0, Math.min(foregroundCapacity + backgroundCapacity, this.maxRetained - this.retainedCount()));
|
|
63
73
|
const newest = new Map();
|
|
64
74
|
for (const value of records) {
|
|
65
75
|
const task = readVersionedTask(value);
|
|
@@ -99,16 +109,7 @@ export class TaskStore {
|
|
|
99
109
|
// Logs never outlive the runtime that wrote them.
|
|
100
110
|
const expired = task.outputPath !== undefined;
|
|
101
111
|
task.outputPath = undefined;
|
|
102
|
-
this.
|
|
103
|
-
task,
|
|
104
|
-
settled: true,
|
|
105
|
-
visible: true,
|
|
106
|
-
delivery: "delivered",
|
|
107
|
-
pins: 0,
|
|
108
|
-
deliveryHolds: 0,
|
|
109
|
-
waiters: new Set(),
|
|
110
|
-
readError: expired ? EXPIRED_OUTPUT : undefined,
|
|
111
|
-
});
|
|
112
|
+
this.add(TaskRecord.restored(task, expired ? EXPIRED_OUTPUT : undefined));
|
|
112
113
|
}
|
|
113
114
|
}
|
|
114
115
|
cleanupOutput(record) {
|
|
@@ -117,14 +118,15 @@ export class TaskStore {
|
|
|
117
118
|
const cleanup = record.cleanup;
|
|
118
119
|
record.cleanup = undefined;
|
|
119
120
|
// Snapshots retain final bounded text; expired files are never needed to render history.
|
|
120
|
-
record.task
|
|
121
|
-
|
|
121
|
+
record.update((task) => {
|
|
122
|
+
task.outputPath = undefined;
|
|
123
|
+
});
|
|
122
124
|
record.readError = EXPIRED_OUTPUT;
|
|
123
125
|
const pending = Promise.resolve()
|
|
124
126
|
.then(cleanup)
|
|
125
127
|
.catch((error) => {
|
|
126
128
|
try {
|
|
127
|
-
this.onCleanupError?.(errorText(error));
|
|
129
|
+
this.onCleanupError?.(errorText(error, "Task cleanup failed"));
|
|
128
130
|
}
|
|
129
131
|
catch {
|
|
130
132
|
/* Cleanup/reporting is best effort, never an unhandled rejection. */
|
|
@@ -135,7 +137,7 @@ export class TaskStore {
|
|
|
135
137
|
}
|
|
136
138
|
/** Pending delivery, active reads and pins have their own bounded retention allowance. */
|
|
137
139
|
historyRecords() {
|
|
138
|
-
return
|
|
140
|
+
return this.all().filter((record) => record.inHistory);
|
|
139
141
|
}
|
|
140
142
|
trim() {
|
|
141
143
|
if (this.closed) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/core/tasks/store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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;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport { readVersionedTask } from \"./codec.ts\";\nimport { boundText, resultText } from \"./output.ts\";\nimport type { TaskSnapshot } from \"./types.ts\";\n\nexport interface TaskRecord {\n\t/** The runtime's working copy. Call changed() after every mutation. */\n\ttask: TaskSnapshot;\n\tsettled: boolean;\n\t/** Whether the launch anchor is on the selected branch. */\n\tvisible: boolean;\n\t/**\n\t * none: running, or answered inline by its tool call; pending: a settled handoff\n\t * awaiting automatic delivery; claimed: handed to the host; delivered: acknowledged.\n\t */\n\tdelivery: \"none\" | \"pending\" | \"claimed\" | \"delivered\";\n\tpins: number;\n\tdeliveryHolds: number;\n\tcleanup?: () => void | Promise<void>;\n\treadError?: string;\n\twaiters: Set<() => void>;\n\t/** Frozen snapshot shared by readers until the task changes. */\n\tsnapshot?: TaskSnapshot;\n}\n\nexport const EXPIRED_OUTPUT = \"Output has expired: the managed log was released; showing the stored result.\";\n\nfunction freeze<T>(value: T): T {\n\tif (value !== null && typeof value === \"object\" && !Object.isFrozen(value)) {\n\t\tfor (const child of Object.values(value)) freeze(child);\n\t\tObject.freeze(value);\n\t}\n\treturn value;\n}\n\n/** Readers share one frozen copy, so polling and status rendering never clone unchanged output. */\nexport function snapshotOf(record: TaskRecord): TaskSnapshot {\n\trecord.snapshot ??= freeze(structuredClone(record.task));\n\treturn record.snapshot;\n}\n\nexport function changed(record: TaskRecord): void {\n\trecord.snapshot = undefined;\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 \"Task cleanup failed\";\n\t}\n}\n\nfunction oldestTask(tasks: Iterable<TaskSnapshot>): TaskSnapshot | undefined {\n\tlet oldest: TaskSnapshot | undefined;\n\tfor (const task of tasks) {\n\t\tif (!oldest || task.endedAt! < oldest.endedAt!) oldest = task;\n\t}\n\treturn oldest;\n}\n\nconst isForeground = (task: TaskSnapshot) => task.mode === \"foreground\";\n\n/** Retained snapshots and output leases. This store never owns executable handles. */\nexport class TaskStore {\n\treadonly records = new Map<string, TaskRecord>();\n\treadonly cleanups = new Set<Promise<void>>();\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate readonly isClosed: () => boolean;\n\tprivate readonly onCleanupError?: (message: string) => void;\n\tconstructor(\n\t\tmaxHistory: number,\n\t\tmaxRetained: number,\n\t\tisClosed: () => boolean,\n\t\tonCleanupError?: (message: string) => void,\n\t) {\n\t\tthis.maxHistory = maxHistory;\n\t\tthis.maxRetained = maxRetained;\n\t\tthis.isClosed = isClosed;\n\t\tthis.onCleanupError = onCleanupError;\n\t}\n\tprivate get closed(): boolean {\n\t\treturn this.isClosed();\n\t}\n\n\t/**\n\t * Foreground records save no output of their own: their tool result already holds it,\n\t * so `toolResults` maps each tool call ID on the branch to that content.\n\t */\n\trestoreHistory(\n\t\trecords: readonly unknown[],\n\t\ttoolResults: ReadonlyMap<string, AgentToolResult<unknown>[\"content\"]> = new Map(),\n\t): 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 foreground = history.filter((record) => isForeground(record.task)).length;\n\t\tconst foregroundCapacity = Math.max(0, this.maxHistory - foreground);\n\t\tconst backgroundCapacity = Math.max(0, this.maxHistory - (history.length - foreground));\n\t\tconst capacity = Math.max(\n\t\t\t0,\n\t\t\tMath.min(foregroundCapacity + backgroundCapacity, this.maxRetained - this.records.size - this.cleanups.size),\n\t\t);\n\t\tconst newest = new Map<string, TaskSnapshot>();\n\t\tfor (const value of records) {\n\t\t\tconst task = readVersionedTask(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 inline = isForeground(task);\n\t\t\tconst limit = inline ? foregroundCapacity : backgroundCapacity;\n\t\t\tif (limit === 0) continue;\n\t\t\tnewest.set(task.id, task);\n\t\t\tconst group = [...newest.values()].filter((candidate) => isForeground(candidate) === inline);\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 background results before foreground ones, which the transcript shows.\n\t\t\t\tconst inlineTasks = [...newest.values()].filter(isForeground);\n\t\t\t\tnewest.delete(oldestTask(inlineTasks.length ? inlineTasks : 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\tconst content = toolResults.get(task.toolCallId);\n\t\t\tif (!task.result && content) task.result = resultText({ content, details: undefined });\n\t\t\t// Logs never outlive the runtime that wrote them.\n\t\t\tconst expired = task.outputPath !== undefined;\n\t\t\ttask.outputPath = undefined;\n\t\t\tthis.records.set(task.id, {\n\t\t\t\ttask,\n\t\t\t\tsettled: true,\n\t\t\t\tvisible: true,\n\t\t\t\tdelivery: \"delivered\",\n\t\t\t\tpins: 0,\n\t\t\t\tdeliveryHolds: 0,\n\t\t\t\twaiters: new Set(),\n\t\t\t\treadError: expired ? EXPIRED_OUTPUT : undefined,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate cleanupOutput(record: TaskRecord): 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\tchanged(record);\n\t\trecord.readError = EXPIRED_OUTPUT;\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.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(): TaskRecord[] {\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\ttrim(): 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 inline of [false, true]) {\n\t\t\tconst group = history.filter((record) => record.visible && isForeground(record.task) === inline);\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"]}
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/core/tasks/store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,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,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;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport { readVersionedTask } from \"./codec.ts\";\nimport { errorText, resultText } from \"./output.ts\";\nimport { TaskRecord } from \"./record.ts\";\nimport type { TaskSnapshot } from \"./types.ts\";\n\nexport const EXPIRED_OUTPUT = \"Output has expired: the managed log was released; showing the stored result.\";\n\nfunction oldestTask(tasks: Iterable<TaskSnapshot>): TaskSnapshot | undefined {\n\tlet oldest: TaskSnapshot | undefined;\n\tfor (const task of tasks) {\n\t\tif (!oldest || task.endedAt! < oldest.endedAt!) oldest = task;\n\t}\n\treturn oldest;\n}\n\nconst isForeground = (task: TaskSnapshot) => task.mode === \"foreground\";\n\n/** Retained snapshots and output leases. This store never owns executable handles. */\nexport class TaskStore {\n\tprivate readonly records = new Map<string, TaskRecord>();\n\tprivate readonly cleanups = new Set<Promise<void>>();\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate readonly isClosed: () => boolean;\n\tprivate readonly onCleanupError?: (message: string) => void;\n\tconstructor(\n\t\tmaxHistory: number,\n\t\tmaxRetained: number,\n\t\tisClosed: () => boolean,\n\t\tonCleanupError?: (message: string) => void,\n\t) {\n\t\tthis.maxHistory = maxHistory;\n\t\tthis.maxRetained = maxRetained;\n\t\tthis.isClosed = isClosed;\n\t\tthis.onCleanupError = onCleanupError;\n\t}\n\tprivate get closed(): boolean {\n\t\treturn this.isClosed();\n\t}\n\n\tget(id: string): TaskRecord | undefined {\n\t\treturn this.records.get(id);\n\t}\n\n\t/** Records whose ID, or whose ID without its kind prefix, starts with `prefix`. */\n\tmatch(prefix: string): TaskRecord[] {\n\t\treturn this.all().filter(\n\t\t\t({ task }) => task.id.startsWith(prefix) || task.id.slice(task.kind.length + 1).startsWith(prefix),\n\t\t);\n\t}\n\n\tadd(record: TaskRecord): void {\n\t\tthis.records.set(record.task.id, record);\n\t}\n\n\tall(): TaskRecord[] {\n\t\treturn [...this.records.values()];\n\t}\n\n\t/** Records whose execution has not settled, queued or running. */\n\tunsettled(): TaskRecord[] {\n\t\treturn this.all().filter((record) => !record.settled);\n\t}\n\n\t/** Records on the selected branch. */\n\tvisible(): TaskRecord[] {\n\t\treturn this.all().filter((record) => record.visible);\n\t}\n\n\t/** Settled handoffs eligible for automatic delivery. */\n\tdeliverable(): TaskRecord[] {\n\t\treturn this.all().filter((record) => record.deliverable);\n\t}\n\n\t/** Records plus output cleanups still running; admission bounds this. */\n\tretainedCount(): number {\n\t\treturn this.records.size + this.cleanups.size;\n\t}\n\n\t/** Settles once every output cleanup started so far has finished. */\n\tcleanupsDone(): Promise<unknown> {\n\t\treturn Promise.all(this.cleanups);\n\t}\n\n\t/**\n\t * Foreground records save no output of their own: their tool result already holds it,\n\t * so `toolResults` maps each tool call ID on the branch to that content.\n\t */\n\trestoreHistory(\n\t\trecords: readonly unknown[],\n\t\ttoolResults: ReadonlyMap<string, AgentToolResult<unknown>[\"content\"]> = new Map(),\n\t): 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 foreground = history.filter((record) => isForeground(record.task)).length;\n\t\tconst foregroundCapacity = Math.max(0, this.maxHistory - foreground);\n\t\tconst backgroundCapacity = Math.max(0, this.maxHistory - (history.length - foreground));\n\t\tconst capacity = Math.max(\n\t\t\t0,\n\t\t\tMath.min(foregroundCapacity + backgroundCapacity, this.maxRetained - this.retainedCount()),\n\t\t);\n\t\tconst newest = new Map<string, TaskSnapshot>();\n\t\tfor (const value of records) {\n\t\t\tconst task = readVersionedTask(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 inline = isForeground(task);\n\t\t\tconst limit = inline ? foregroundCapacity : backgroundCapacity;\n\t\t\tif (limit === 0) continue;\n\t\t\tnewest.set(task.id, task);\n\t\t\tconst group = [...newest.values()].filter((candidate) => isForeground(candidate) === inline);\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 background results before foreground ones, which the transcript shows.\n\t\t\t\tconst inlineTasks = [...newest.values()].filter(isForeground);\n\t\t\t\tnewest.delete(oldestTask(inlineTasks.length ? inlineTasks : 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\tconst content = toolResults.get(task.toolCallId);\n\t\t\tif (!task.result && content) task.result = resultText({ content, details: undefined });\n\t\t\t// Logs never outlive the runtime that wrote them.\n\t\t\tconst expired = task.outputPath !== undefined;\n\t\t\ttask.outputPath = undefined;\n\t\t\tthis.add(TaskRecord.restored(task, expired ? EXPIRED_OUTPUT : undefined));\n\t\t}\n\t}\n\n\tprivate cleanupOutput(record: TaskRecord): 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.update((task) => {\n\t\t\ttask.outputPath = undefined;\n\t\t});\n\t\trecord.readError = EXPIRED_OUTPUT;\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.onCleanupError?.(errorText(error, \"Task cleanup failed\"));\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(): TaskRecord[] {\n\t\treturn this.all().filter((record) => record.inHistory);\n\t}\n\n\ttrim(): 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 inline of [false, true]) {\n\t\t\tconst group = history.filter((record) => record.visible && isForeground(record.task) === inline);\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"]}
|