@astralyn/pi 1.4.5 → 1.4.6
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 +20 -0
- package/dist/bundle/chunks/{chunk-I5S7H7GA.js → chunk-EYKC6ESU.js} +1 -1
- package/dist/bundle/chunks/chunk-KDO6L76C.js +230 -0
- package/dist/bundle/chunks/chunk-RBTJBQWX.js +1500 -0
- package/dist/bundle/chunks/{execute-GMFGC27P.js → execute-5ZQUS52M.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-6FUV7ZDV.js → virtual-modules-KCQU7LOC.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/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/isolated-session.d.ts +23 -0
- package/dist/core/isolated-session.d.ts.map +1 -0
- package/dist/core/isolated-session.js +55 -0
- package/dist/core/isolated-session.js.map +1 -0
- package/dist/core/tasks/codec.d.ts +12 -0
- package/dist/core/tasks/codec.d.ts.map +1 -0
- package/dist/core/tasks/codec.js +139 -0
- package/dist/core/tasks/codec.js.map +1 -0
- package/dist/core/tasks/execution.d.ts +64 -0
- package/dist/core/tasks/execution.d.ts.map +1 -0
- package/dist/core/tasks/execution.js +272 -0
- package/dist/core/tasks/execution.js.map +1 -0
- package/dist/core/tasks/output.d.ts +12 -6
- package/dist/core/tasks/output.d.ts.map +1 -1
- package/dist/core/tasks/output.js +38 -38
- package/dist/core/tasks/output.js.map +1 -1
- package/dist/core/tasks/presentation.d.ts +14 -5
- package/dist/core/tasks/presentation.d.ts.map +1 -1
- package/dist/core/tasks/presentation.js +56 -185
- package/dist/core/tasks/presentation.js.map +1 -1
- package/dist/core/tasks/runtime.d.ts +9 -9
- package/dist/core/tasks/runtime.d.ts.map +1 -1
- package/dist/core/tasks/runtime.js +63 -254
- package/dist/core/tasks/runtime.js.map +1 -1
- package/dist/core/tasks/scheduler.d.ts +16 -0
- package/dist/core/tasks/scheduler.d.ts.map +1 -0
- package/dist/core/tasks/scheduler.js +42 -0
- package/dist/core/tasks/scheduler.js.map +1 -0
- package/dist/core/tasks/session.d.ts +1 -0
- package/dist/core/tasks/session.d.ts.map +1 -1
- package/dist/core/tasks/session.js +15 -27
- package/dist/core/tasks/session.js.map +1 -1
- package/dist/core/tasks/store.js +4 -4
- package/dist/core/tasks/store.js.map +1 -1
- package/dist/core/tasks/types.d.ts +63 -53
- package/dist/core/tasks/types.d.ts.map +1 -1
- package/dist/core/tasks/types.js +3 -9
- package/dist/core/tasks/types.js.map +1 -1
- package/dist/core/tools/shell-execution.js +4 -4
- 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 +23 -30
- package/dist/core/tools/shell-tool.js.map +1 -1
- package/dist/core/usage-totals.d.ts +1 -3
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +17 -8
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/agent/activity.d.ts +4 -4
- package/dist/extensions/agent/activity.d.ts.map +1 -1
- package/dist/extensions/agent/activity.js +15 -24
- package/dist/extensions/agent/activity.js.map +1 -1
- package/dist/extensions/agent/index.d.ts +2 -11
- package/dist/extensions/agent/index.d.ts.map +1 -1
- package/dist/extensions/agent/index.js +3 -88
- package/dist/extensions/agent/index.js.map +1 -1
- package/dist/extensions/agent/progress.d.ts +31 -0
- package/dist/extensions/agent/progress.d.ts.map +1 -0
- package/dist/extensions/agent/progress.js +145 -0
- package/dist/extensions/agent/progress.js.map +1 -0
- package/dist/extensions/agent/render.d.ts.map +1 -1
- package/dist/extensions/agent/render.js +8 -17
- package/dist/extensions/agent/render.js.map +1 -1
- package/dist/extensions/agent/report.d.ts +9 -0
- package/dist/extensions/agent/report.d.ts.map +1 -0
- package/dist/extensions/agent/report.js +40 -0
- package/dist/extensions/agent/report.js.map +1 -0
- package/dist/extensions/agent/settings-panel.d.ts +43 -0
- package/dist/extensions/agent/settings-panel.d.ts.map +1 -0
- package/dist/extensions/agent/settings-panel.js +125 -0
- package/dist/extensions/agent/settings-panel.js.map +1 -0
- package/dist/extensions/agent/settings.d.ts +1 -1
- package/dist/extensions/agent/settings.d.ts.map +1 -1
- package/dist/extensions/agent/settings.js +101 -83
- package/dist/extensions/agent/settings.js.map +1 -1
- package/dist/extensions/agent/tool.d.ts +13 -0
- package/dist/extensions/agent/tool.d.ts.map +1 -0
- package/dist/extensions/agent/tool.js +84 -0
- package/dist/extensions/agent/tool.js.map +1 -0
- package/dist/extensions/agent/types.d.ts +19 -21
- package/dist/extensions/agent/types.d.ts.map +1 -1
- package/dist/extensions/agent/types.js +2 -10
- package/dist/extensions/agent/types.js.map +1 -1
- package/dist/extensions/agent/worker.d.ts +16 -0
- package/dist/extensions/agent/worker.d.ts.map +1 -0
- package/dist/extensions/agent/worker.js +68 -0
- package/dist/extensions/agent/worker.js.map +1 -0
- package/dist/extensions/tasks/tool/actions.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/actions.js +1 -9
- package/dist/extensions/tasks/tool/actions.js.map +1 -1
- package/dist/extensions/tasks/tool/schema.js +1 -1
- package/dist/extensions/tasks/tool/schema.js.map +1 -1
- package/dist/extensions/tasks/tool/types.d.ts +2 -8
- package/dist/extensions/tasks/tool/types.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/types.js +0 -2
- package/dist/extensions/tasks/tool/types.js.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.js +27 -26
- package/dist/extensions/tasks/ui/completion-render.js.map +1 -1
- package/dist/extensions/tasks/ui/inspector.d.ts +5 -3
- package/dist/extensions/tasks/ui/inspector.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/inspector.js +18 -6
- package/dist/extensions/tasks/ui/inspector.js.map +1 -1
- package/dist/extensions/tasks/ui/layout.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/layout.js +111 -75
- 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 +43 -28
- package/dist/extensions/tasks/ui/list.js.map +1 -1
- package/dist/extensions/tasks/ui/manager.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/manager.js +8 -2
- package/dist/extensions/tasks/ui/manager.js.map +1 -1
- package/dist/extensions/tasks/ui/model.d.ts +4 -0
- package/dist/extensions/tasks/ui/model.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/model.js +12 -1
- package/dist/extensions/tasks/ui/model.js.map +1 -1
- package/dist/extensions/tasks/ui/render.js +3 -4
- package/dist/extensions/tasks/ui/render.js.map +1 -1
- package/dist/extensions/tasks/ui/task-view.d.ts +0 -5
- package/dist/extensions/tasks/ui/task-view.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/task-view.js +0 -7
- package/dist/extensions/tasks/ui/task-view.js.map +1 -1
- package/dist/extensions/tasks/ui/tree.js +1 -1
- package/dist/extensions/tasks/ui/tree.js.map +1 -1
- package/dist/extensions/tasks/ui/views.d.ts +10 -5
- package/dist/extensions/tasks/ui/views.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/views.js +61 -36
- package/dist/extensions/tasks/ui/views.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +2 -1
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +7 -4
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +10 -3
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/docs/bundled/extensions/agent.md +12 -10
- package/docs/bundled/extensions/statusline.md +1 -1
- package/docs/bundled/tasks.md +15 -14
- package/docs/extensions.md +22 -6
- package/docs/sdk.md +2 -2
- package/docs/session-format.md +27 -23
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/bundle/chunks/chunk-FSJ45CRP.js +0 -229
- package/dist/bundle/chunks/chunk-W3FIUMGM.js +0 -1501
- package/dist/core/tasks/history.d.ts +0 -4
- package/dist/core/tasks/history.d.ts.map +0 -1
- package/dist/core/tasks/history.js +0 -131
- package/dist/core/tasks/history.js.map +0 -1
- package/dist/extensions/agent/runner.d.ts +0 -24
- package/dist/extensions/agent/runner.d.ts.map +0 -1
- package/dist/extensions/agent/runner.js +0 -274
- package/dist/extensions/agent/runner.js.map +0 -1
|
@@ -1,40 +1,49 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Execution, errorText } from "./execution.js";
|
|
2
3
|
import { TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS } from "./limits.js";
|
|
3
|
-
import { boundText, finiteLimit, readOutputSlice,
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
try {
|
|
8
|
-
return boundText(error instanceof Error ? error.message : String(error), 4096);
|
|
9
|
-
}
|
|
10
|
-
catch {
|
|
11
|
-
return "Task execution failed (unprintable error)";
|
|
12
|
-
}
|
|
13
|
-
}
|
|
4
|
+
import { boundFacts, boundInput, boundText, finiteLimit, readOutputSlice, sliceText, TASK_LABEL_BYTES, TASK_TITLE_BYTES, } from "./output.js";
|
|
5
|
+
import { TaskScheduler } from "./scheduler.js";
|
|
6
|
+
import { snapshotOf, TaskStore } from "./store.js";
|
|
7
|
+
import { TASK_BACKGROUND_REJECTION, TASK_KIND_PATTERN, TaskLookupError, } from "./types.js";
|
|
14
8
|
/** Session-local supervision. Executors own their processes, items and output files. */
|
|
15
9
|
export class TaskRuntime {
|
|
16
|
-
get closed() {
|
|
17
|
-
return this._closed;
|
|
18
|
-
}
|
|
19
|
-
get session() {
|
|
20
|
-
return this.options.session;
|
|
21
|
-
}
|
|
22
10
|
constructor(options = {}) {
|
|
23
11
|
this.executions = new Map();
|
|
12
|
+
this.scheduler = new TaskScheduler();
|
|
24
13
|
this.listeners = new Set();
|
|
25
14
|
this._closed = false;
|
|
26
15
|
this.pauses = 0;
|
|
27
16
|
this.options = options;
|
|
28
17
|
this.configuredEnabled = options.enabled ?? false;
|
|
29
|
-
this.
|
|
18
|
+
this.maxBackground = Math.max(1, finiteLimit(options.maxBackground, 8, 128));
|
|
30
19
|
this.maxHistory = finiteLimit(options.maxHistory, 32, 1024);
|
|
31
20
|
// Separate foreground and background histories, plus the protected-record allowance.
|
|
32
|
-
this.maxRetained = this.
|
|
21
|
+
this.maxRetained = this.maxBackground + 2 * Math.max(1, this.maxHistory) + this.maxHistory;
|
|
33
22
|
this.store = new TaskStore(this.maxHistory, this.maxRetained, () => this.closed, options.onCleanupError);
|
|
23
|
+
const runtime = this;
|
|
24
|
+
this.host = {
|
|
25
|
+
get closed() {
|
|
26
|
+
return runtime.closed;
|
|
27
|
+
},
|
|
28
|
+
emit: () => this.emit(),
|
|
29
|
+
settle: (task, usage) => this.options.onSettled?.(task, usage),
|
|
30
|
+
released: (execution) => {
|
|
31
|
+
this.executions.delete(execution.task.id);
|
|
32
|
+
this.scheduler.release(execution);
|
|
33
|
+
this.store.trim();
|
|
34
|
+
this.emit();
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
get closed() {
|
|
39
|
+
return this._closed;
|
|
40
|
+
}
|
|
41
|
+
get session() {
|
|
42
|
+
return this.options.session;
|
|
34
43
|
}
|
|
35
44
|
/**
|
|
36
|
-
* Rehydrate terminal
|
|
37
|
-
*
|
|
45
|
+
* Rehydrate terminal snapshots only, newest endedAt in each history (later input wins
|
|
46
|
+
* ties). Existing runtime records win ID collisions. No execution, accounting,
|
|
38
47
|
* notification, or deletion ownership is restored. Foreground records take their output
|
|
39
48
|
* from the branch's tool results. The host supplies the current branch; closed services
|
|
40
49
|
* ignore restoration.
|
|
@@ -49,7 +58,7 @@ export class TaskRuntime {
|
|
|
49
58
|
this.configuredEnabled = enabled;
|
|
50
59
|
this.emit();
|
|
51
60
|
}
|
|
52
|
-
/** Foreground work is bounded by its caller; only background work holds a slot. */
|
|
61
|
+
/** Foreground work is bounded by its caller; only background work, queued or running, holds a slot. */
|
|
53
62
|
backgroundActive() {
|
|
54
63
|
let count = 0;
|
|
55
64
|
for (const record of this.store.records.values())
|
|
@@ -58,7 +67,7 @@ export class TaskRuntime {
|
|
|
58
67
|
return count;
|
|
59
68
|
}
|
|
60
69
|
limitError() {
|
|
61
|
-
return new Error(`Background task limit reached (${this.
|
|
70
|
+
return new Error(`Background task limit reached (${this.maxBackground}); stop or wait for a background task, or run in the foreground.`);
|
|
62
71
|
}
|
|
63
72
|
async execute(execution) {
|
|
64
73
|
// Admission and registration happen synchronously, before invoking user code or awaiting anything.
|
|
@@ -69,7 +78,7 @@ export class TaskRuntime {
|
|
|
69
78
|
if (execution.background) {
|
|
70
79
|
if (!this.enabled)
|
|
71
80
|
throw new Error("Background execution is not available in this host");
|
|
72
|
-
if (this.backgroundActive() >= this.
|
|
81
|
+
if (this.backgroundActive() >= this.maxBackground)
|
|
73
82
|
throw this.limitError();
|
|
74
83
|
if (this.store.records.size + this.store.cleanups.size >= this.maxRetained) {
|
|
75
84
|
throw new Error("Task history retention limit reached; deliver pending notifications or release pinned or claimed records");
|
|
@@ -77,33 +86,28 @@ export class TaskRuntime {
|
|
|
77
86
|
}
|
|
78
87
|
if (execution.signal?.aborted)
|
|
79
88
|
throw execution.signal.reason ?? new Error("Execution aborted");
|
|
80
|
-
if (
|
|
89
|
+
if (!TASK_KIND_PATTERN.test(execution.kind))
|
|
81
90
|
throw new Error("Invalid task source");
|
|
91
|
+
const concurrency = execution.concurrency;
|
|
92
|
+
if (concurrency && (!concurrency.key || !Number.isSafeInteger(concurrency.limit) || concurrency.limit < 1))
|
|
93
|
+
throw new Error("Invalid task concurrency");
|
|
82
94
|
const anchorId = this.options.anchor?.() ?? null;
|
|
83
95
|
if (anchorId !== null && Buffer.byteLength(anchorId) > 8192)
|
|
84
96
|
throw new Error("Task branch anchor is too large");
|
|
85
|
-
const info = execution.info === undefined ? undefined : boundText(execution.info, TASK_INFO_BYTES);
|
|
86
97
|
const task = {
|
|
87
98
|
id: `${execution.kind}-${randomUUID()}`,
|
|
88
99
|
kind: execution.kind,
|
|
100
|
+
label: boundText(execution.label ?? execution.kind, TASK_LABEL_BYTES),
|
|
89
101
|
title: boundText(execution.title, TASK_TITLE_BYTES),
|
|
102
|
+
output: execution.output ?? "log",
|
|
103
|
+
...(execution.input ? { input: boundInput(execution.input) } : {}),
|
|
104
|
+
...(execution.facts?.length ? { facts: boundFacts(execution.facts) } : {}),
|
|
90
105
|
toolCallId: boundText(execution.toolCallId, 512),
|
|
91
106
|
anchorId,
|
|
92
107
|
mode: execution.background ? "background" : "foreground",
|
|
93
108
|
status: "queued",
|
|
94
109
|
startedAt: Date.now(),
|
|
95
|
-
command: execution.command === undefined ? undefined : boundText(execution.command, 8192),
|
|
96
|
-
commandTruncated: execution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,
|
|
97
|
-
cwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),
|
|
98
|
-
info: info === undefined ? undefined : { text: info, truncated: info !== execution.info },
|
|
99
110
|
};
|
|
100
|
-
let resolveCaller;
|
|
101
|
-
let rejectCaller;
|
|
102
|
-
const caller = new Promise((resolve, reject) => {
|
|
103
|
-
resolveCaller = resolve;
|
|
104
|
-
rejectCaller = reject;
|
|
105
|
-
});
|
|
106
|
-
let resolveDone;
|
|
107
111
|
const record = {
|
|
108
112
|
task,
|
|
109
113
|
settled: false,
|
|
@@ -113,182 +117,18 @@ export class TaskRuntime {
|
|
|
113
117
|
deliveryHolds: 0,
|
|
114
118
|
waiters: new Set(),
|
|
115
119
|
};
|
|
116
|
-
const active =
|
|
117
|
-
controller: new AbortController(),
|
|
118
|
-
accepted: false,
|
|
119
|
-
handedOff: false,
|
|
120
|
-
detachRequested: execution.background ?? false,
|
|
121
|
-
modeListeners: new Set(),
|
|
122
|
-
removeParent: () => { },
|
|
123
|
-
handoff: () => {
|
|
124
|
-
if (!active.accepted ||
|
|
125
|
-
!active.detachRequested ||
|
|
126
|
-
record.settled ||
|
|
127
|
-
active.handedOff ||
|
|
128
|
-
this.closed ||
|
|
129
|
-
!record.visible ||
|
|
130
|
-
active.controller.signal.aborted)
|
|
131
|
-
return;
|
|
132
|
-
active.handedOff = true;
|
|
133
|
-
task.mode = "background";
|
|
134
|
-
changed(record);
|
|
135
|
-
active.removeParent();
|
|
136
|
-
resolveCaller({ kind: "background", task: snapshotOf(record) });
|
|
137
|
-
this.emit();
|
|
138
|
-
},
|
|
139
|
-
done: new Promise((resolve) => {
|
|
140
|
-
resolveDone = resolve;
|
|
141
|
-
}),
|
|
142
|
-
};
|
|
143
|
-
const parentSignal = execution.signal;
|
|
144
|
-
let onUpdate = execution.background ? undefined : execution.onUpdate;
|
|
145
|
-
const parentAbort = () => {
|
|
146
|
-
if (!active.detachRequested || !active.accepted)
|
|
147
|
-
this.cancel(record);
|
|
148
|
-
};
|
|
149
|
-
parentSignal?.addEventListener("abort", parentAbort, { once: true });
|
|
150
|
-
active.removeParent = () => {
|
|
151
|
-
parentSignal?.removeEventListener("abort", parentAbort);
|
|
152
|
-
onUpdate = undefined;
|
|
153
|
-
};
|
|
120
|
+
const active = new Execution(this.host, record, execution);
|
|
154
121
|
this.store.records.set(task.id, record);
|
|
155
122
|
this.executions.set(task.id, active);
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
return task.mode;
|
|
161
|
-
},
|
|
162
|
-
onModeChange: (listener) => {
|
|
163
|
-
if (record.settled || this.closed)
|
|
164
|
-
return () => { };
|
|
165
|
-
active.modeListeners.add(listener);
|
|
166
|
-
return () => {
|
|
167
|
-
active.modeListeners.delete(listener);
|
|
168
|
-
};
|
|
169
|
-
},
|
|
170
|
-
requestCancel: () => this.cancel(record),
|
|
171
|
-
accept: () => {
|
|
172
|
-
if (record.settled || active.accepted || this.closed || active.controller.signal.aborted)
|
|
173
|
-
return;
|
|
174
|
-
active.accepted = true;
|
|
175
|
-
if (task.status === "queued")
|
|
176
|
-
task.status = "running";
|
|
177
|
-
changed(record);
|
|
178
|
-
if (active.detachRequested)
|
|
179
|
-
active.removeParent();
|
|
180
|
-
// Let an already available final result win over a handoff.
|
|
181
|
-
queueMicrotask(() => queueMicrotask(active.handoff));
|
|
182
|
-
this.emit();
|
|
183
|
-
},
|
|
184
|
-
publish: (result) => {
|
|
185
|
-
if (record.settled || this.closed)
|
|
186
|
-
return;
|
|
187
|
-
retainResult(task, result);
|
|
188
|
-
changed(record);
|
|
189
|
-
if (result.usage !== undefined)
|
|
190
|
-
active.publishedUsage = structuredClone(result.usage);
|
|
191
|
-
if (!active.detachRequested && !active.handedOff) {
|
|
192
|
-
try {
|
|
193
|
-
onUpdate?.(result);
|
|
194
|
-
}
|
|
195
|
-
catch {
|
|
196
|
-
/* UI observers cannot stop execution. */
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
this.emit();
|
|
200
|
-
},
|
|
201
|
-
setOutputPath: (path, cleanup) => {
|
|
202
|
-
if (record.settled) {
|
|
203
|
-
if (cleanup)
|
|
204
|
-
throw new Error("Task execution has settled");
|
|
205
|
-
return;
|
|
206
|
-
}
|
|
207
|
-
if (record.cleanup)
|
|
208
|
-
throw new Error("Managed output is already registered");
|
|
209
|
-
// Never truncate a real filesystem path into a different path.
|
|
210
|
-
if (Buffer.byteLength(path) > 8192)
|
|
211
|
-
throw new Error("Task output path is too large");
|
|
212
|
-
record.cleanup = cleanup;
|
|
213
|
-
task.outputPath = path;
|
|
214
|
-
changed(record);
|
|
215
|
-
this.emit();
|
|
216
|
-
},
|
|
217
|
-
};
|
|
218
|
-
const finish = (completion, error) => {
|
|
219
|
-
if (record.settled)
|
|
220
|
-
return;
|
|
221
|
-
record.settled = true;
|
|
222
|
-
active.modeListeners.clear();
|
|
223
|
-
active.removeParent();
|
|
224
|
-
task.endedAt = Date.now();
|
|
225
|
-
const failed = completion === undefined;
|
|
226
|
-
task.status =
|
|
227
|
-
completion?.status ??
|
|
228
|
-
(error instanceof TaskExecutionError
|
|
229
|
-
? error.status
|
|
230
|
-
: active.controller.signal.aborted
|
|
231
|
-
? "cancelled"
|
|
232
|
-
: failed
|
|
233
|
-
? "failed"
|
|
234
|
-
: "completed");
|
|
235
|
-
if (completion) {
|
|
236
|
-
retainResult(task, completion.result);
|
|
237
|
-
if (completion.error !== undefined)
|
|
238
|
-
task.error = boundText(completion.error, 4096);
|
|
239
|
-
if (completion.exitCode !== undefined)
|
|
240
|
-
task.exitCode = completion.exitCode;
|
|
241
|
-
}
|
|
242
|
-
if (failed) {
|
|
243
|
-
task.error = errorText(error);
|
|
244
|
-
retainResult(task, { content: [{ type: "text", text: task.error }, ...(task.result?.content ?? [])], details: undefined }, task.resultTruncated);
|
|
245
|
-
}
|
|
246
|
-
changed(record);
|
|
247
|
-
let settlementWarning;
|
|
248
|
-
try {
|
|
249
|
-
this.options.onSettled?.(snapshotOf(record), completion?.usage ?? completion?.result.usage ?? active.publishedUsage);
|
|
250
|
-
}
|
|
251
|
-
catch (accountingError) {
|
|
252
|
-
const warning = `Usage settlement failed: ${errorText(accountingError)}`;
|
|
253
|
-
settlementWarning = warning;
|
|
254
|
-
task.error = boundText([task.error, warning].filter(Boolean).join("\n"), 8192);
|
|
255
|
-
retainResult(task, { content: [{ type: "text", text: warning }, ...(task.result?.content ?? [])], details: undefined }, task.resultTruncated);
|
|
256
|
-
changed(record);
|
|
257
|
-
}
|
|
258
|
-
active.publishedUsage = undefined;
|
|
259
|
-
// Delivery becomes eligible only after settlement is persisted.
|
|
260
|
-
record.delivery = active.handedOff ? "pending" : "delivered";
|
|
261
|
-
if (!active.handedOff) {
|
|
262
|
-
if (failed)
|
|
263
|
-
rejectCaller(error);
|
|
264
|
-
else {
|
|
265
|
-
const { usage: _usage, ...result } = completion.result;
|
|
266
|
-
if (settlementWarning)
|
|
267
|
-
result.content = [{ type: "text", text: settlementWarning }, ...result.content];
|
|
268
|
-
resolveCaller({ kind: "result", result, status: task.status, error: task.error });
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
for (const waiter of [...record.waiters])
|
|
272
|
-
waiter();
|
|
273
|
-
resolveDone();
|
|
274
|
-
this.executions.delete(task.id);
|
|
275
|
-
this.store.trim();
|
|
276
|
-
this.emit();
|
|
277
|
-
};
|
|
278
|
-
// The rejection handler is installed immediately, including for synchronous preflight throws.
|
|
279
|
-
try {
|
|
280
|
-
const running = execution.run(control);
|
|
281
|
-
void Promise.resolve(running).then((result) => finish(result), (error) => finish(undefined, error));
|
|
282
|
-
}
|
|
283
|
-
catch (error) {
|
|
284
|
-
finish(undefined, error);
|
|
285
|
-
}
|
|
123
|
+
this.scheduler.schedule(active);
|
|
124
|
+
// Queued background work returns at once; started work hands off after its own accept().
|
|
125
|
+
if (active.queued)
|
|
126
|
+
active.handoff();
|
|
286
127
|
this.emit();
|
|
287
|
-
return caller;
|
|
128
|
+
return active.caller;
|
|
288
129
|
}
|
|
289
130
|
detachable(record) {
|
|
290
|
-
|
|
291
|
-
return !!active && !record.settled && !active.detachRequested && !active.controller.signal.aborted;
|
|
131
|
+
return this.executions.get(record.task.id)?.detachable ?? false;
|
|
292
132
|
}
|
|
293
133
|
detachForeground() {
|
|
294
134
|
if (!this.enabled)
|
|
@@ -298,52 +138,33 @@ export class TaskRuntime {
|
|
|
298
138
|
.sort((left, right) => left.task.startedAt - right.task.startedAt);
|
|
299
139
|
if (!eligible.length)
|
|
300
140
|
return 0;
|
|
301
|
-
const free = this.
|
|
141
|
+
const free = this.maxBackground - this.backgroundActive();
|
|
302
142
|
if (free <= 0)
|
|
303
143
|
throw this.limitError();
|
|
304
|
-
const
|
|
305
|
-
for (const
|
|
306
|
-
|
|
307
|
-
for (const
|
|
308
|
-
|
|
144
|
+
const executions = eligible.slice(0, free).map((record) => this.executions.get(record.task.id));
|
|
145
|
+
for (const execution of executions)
|
|
146
|
+
execution.requestDetach();
|
|
147
|
+
for (const execution of executions)
|
|
148
|
+
execution.completeDetach();
|
|
309
149
|
this.emit();
|
|
310
|
-
return
|
|
150
|
+
return executions.length;
|
|
311
151
|
}
|
|
312
152
|
canDetach(id) {
|
|
313
153
|
const record = this.lookup(id);
|
|
314
|
-
return this.enabled && this.backgroundActive() < this.
|
|
154
|
+
return this.enabled && this.backgroundActive() < this.maxBackground && this.detachable(record);
|
|
315
155
|
}
|
|
316
156
|
detach(id) {
|
|
317
157
|
const record = this.lookup(id);
|
|
318
158
|
if (!this.enabled || !this.detachable(record))
|
|
319
159
|
return false;
|
|
320
|
-
if (this.backgroundActive() >= this.
|
|
160
|
+
if (this.backgroundActive() >= this.maxBackground)
|
|
321
161
|
throw this.limitError();
|
|
322
|
-
this.
|
|
323
|
-
|
|
162
|
+
const execution = this.executions.get(record.task.id);
|
|
163
|
+
execution.requestDetach();
|
|
164
|
+
execution.completeDetach();
|
|
324
165
|
this.emit();
|
|
325
166
|
return true;
|
|
326
167
|
}
|
|
327
|
-
prepareDetach(record) {
|
|
328
|
-
const active = this.executions.get(record.task.id);
|
|
329
|
-
active.detachRequested = true;
|
|
330
|
-
record.task.mode = "background";
|
|
331
|
-
changed(record);
|
|
332
|
-
if (active.accepted)
|
|
333
|
-
active.removeParent();
|
|
334
|
-
}
|
|
335
|
-
finishDetach(record) {
|
|
336
|
-
const active = this.executions.get(record.task.id);
|
|
337
|
-
active.handoff();
|
|
338
|
-
for (const listener of active.modeListeners) {
|
|
339
|
-
try {
|
|
340
|
-
listener(record.task.mode);
|
|
341
|
-
}
|
|
342
|
-
catch {
|
|
343
|
-
/* Executors own their diagnostics. */
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
168
|
list() {
|
|
348
169
|
return [...this.store.records.values()].filter((record) => record.visible).map(snapshotOf);
|
|
349
170
|
}
|
|
@@ -384,12 +205,7 @@ export class TaskRuntime {
|
|
|
384
205
|
}
|
|
385
206
|
}
|
|
386
207
|
resultText(task) {
|
|
387
|
-
return
|
|
388
|
-
.filter((block) => block.type === "text")
|
|
389
|
-
.map((block) => block.text)
|
|
390
|
-
.join("\n") ||
|
|
391
|
-
task.error ||
|
|
392
|
-
"No output yet.");
|
|
208
|
+
return task.result?.text || task.error || "No output yet.";
|
|
393
209
|
}
|
|
394
210
|
/** One event-driven waiter can observe a whole waitAny cohort without per-task timers. */
|
|
395
211
|
waitForRecords(records, timeoutMs, signal, interruptSignal) {
|
|
@@ -455,14 +271,7 @@ export class TaskRuntime {
|
|
|
455
271
|
return this.cancel(this.lookup(id));
|
|
456
272
|
}
|
|
457
273
|
cancel(record) {
|
|
458
|
-
|
|
459
|
-
if (!active || record.settled || active.controller.signal.aborted)
|
|
460
|
-
return false;
|
|
461
|
-
record.task.status = "stopping";
|
|
462
|
-
changed(record);
|
|
463
|
-
active.controller.abort();
|
|
464
|
-
this.emit();
|
|
465
|
-
return true;
|
|
274
|
+
return this.executions.get(record.task.id)?.cancel() ?? false;
|
|
466
275
|
}
|
|
467
276
|
subscribe(listener) {
|
|
468
277
|
if (this.closed)
|
|
@@ -552,7 +361,7 @@ export class TaskRuntime {
|
|
|
552
361
|
this._closed = true;
|
|
553
362
|
this.listeners.clear();
|
|
554
363
|
for (const record of this.store.records.values()) {
|
|
555
|
-
this.executions.get(record.task.id)?.
|
|
364
|
+
this.executions.get(record.task.id)?.releaseParent();
|
|
556
365
|
this.cancel(record);
|
|
557
366
|
for (const waiter of [...record.waiters])
|
|
558
367
|
waiter();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/core/tasks/run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,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 type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport { TASKS_WAIT_DEFAULT_MS, TASKS_WAIT_MAX_MS } from \"./limits.ts\";\nimport {\n\tboundText,\n\tfiniteLimit,\n\treadOutputSlice,\n\tretainResult,\n\tsliceText,\n\tTASK_INFO_BYTES,\n\tTASK_TITLE_BYTES,\n} from \"./output.ts\";\nimport { changed, snapshotOf, type TaskRecord, TaskStore } from \"./store.ts\";\nimport {\n\tTASK_BACKGROUND_REJECTION,\n\ttype TaskCompletion,\n\ttype TaskControl,\n\ttype TaskExecution,\n\tTaskExecutionError,\n\tTaskLookupError,\n\ttype TaskMode,\n\ttype TaskRead,\n\ttype TaskRuntimeOptions,\n\ttype TaskSnapshot,\n\ttype TasksContext,\n\ttype TaskToolOutcome,\n} from \"./types.ts\";\n\ninterface ActiveTask {\n\tcontroller: AbortController;\n\taccepted: boolean;\n\thandedOff: boolean;\n\tdetachRequested: boolean;\n\tpublishedUsage?: Usage;\n\tmodeListeners: Set<(mode: TaskMode) => void>;\n\tremoveParent(): void;\n\thandoff(): void;\n\tdone: Promise<void>;\n}\n\nfunction errorText(error: unknown): string {\n\ttry {\n\t\treturn boundText(error instanceof Error ? error.message : String(error), 4096);\n\t} catch {\n\t\treturn \"Task execution failed (unprintable error)\";\n\t}\n}\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, ActiveTask>();\n\tprivate readonly listeners = new Set<() => void>();\n\tprivate readonly maxActive: number;\n\tprivate readonly maxHistory: number;\n\tprivate readonly maxRetained: number;\n\tprivate configuredEnabled: boolean;\n\tprivate _closed = false;\n\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\tprivate pauses = 0;\n\n\tprivate readonly options: TaskRuntimeOptions;\n\n\tconstructor(options: TaskRuntimeOptions = {}) {\n\t\tthis.options = options;\n\t\tthis.configuredEnabled = options.enabled ?? false;\n\t\tthis.maxActive = Math.max(1, finiteLimit(options.maxActive, 8, 128));\n\t\tthis.maxHistory = finiteLimit(options.maxHistory, 32, 1024);\n\t\t// Separate foreground and background histories, plus the protected-record allowance.\n\t\tthis.maxRetained = this.maxActive + 2 * Math.max(1, this.maxHistory) + this.maxHistory;\n\t\tthis.store = new TaskStore(this.maxHistory, this.maxRetained, () => this.closed, options.onCleanupError);\n\t}\n\n\t/**\n\t * Rehydrate terminal version-2 custom data only, newest endedAt in each history\n\t * (later input wins ties). Existing runtime records win ID collisions. No execution, accounting,\n\t * notification, or deletion ownership is restored. 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 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.maxActive}); 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.maxActive) 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 (!/^[a-z][a-z0-9-]{0,63}$/.test(execution.kind)) throw new Error(\"Invalid task source\");\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 info = execution.info === undefined ? undefined : boundText(execution.info, TASK_INFO_BYTES);\n\t\tconst task: TaskSnapshot = {\n\t\t\tid: `${execution.kind}-${randomUUID()}`,\n\t\t\tkind: execution.kind,\n\t\t\ttitle: boundText(execution.title, TASK_TITLE_BYTES),\n\t\t\ttoolCallId: boundText(execution.toolCallId, 512),\n\t\t\tanchorId,\n\t\t\tmode: execution.background ? \"background\" : \"foreground\",\n\t\t\tstatus: \"queued\",\n\t\t\tstartedAt: Date.now(),\n\t\t\tcommand: execution.command === undefined ? undefined : boundText(execution.command, 8192),\n\t\t\tcommandTruncated:\n\t\t\t\texecution.command === undefined ? undefined : boundText(execution.command, 8192) !== execution.command,\n\t\t\tcwd: execution.cwd === undefined ? undefined : boundText(execution.cwd, 4096),\n\t\t\tinfo: info === undefined ? undefined : { text: info, truncated: info !== execution.info },\n\t\t};\n\t\tlet resolveCaller!: (outcome: TaskToolOutcome<T>) => void;\n\t\tlet rejectCaller!: (error: unknown) => void;\n\t\tconst caller = new Promise<TaskToolOutcome<T>>((resolve, reject) => {\n\t\t\tresolveCaller = resolve;\n\t\t\trejectCaller = reject;\n\t\t});\n\t\tlet resolveDone!: () => void;\n\t\tconst record: 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: ActiveTask = {\n\t\t\tcontroller: new AbortController(),\n\t\t\taccepted: false,\n\t\t\thandedOff: false,\n\t\t\tdetachRequested: execution.background ?? false,\n\t\t\tmodeListeners: new Set(),\n\t\t\tremoveParent: () => {},\n\t\t\thandoff: () => {\n\t\t\t\tif (\n\t\t\t\t\t!active.accepted ||\n\t\t\t\t\t!active.detachRequested ||\n\t\t\t\t\trecord.settled ||\n\t\t\t\t\tactive.handedOff ||\n\t\t\t\t\tthis.closed ||\n\t\t\t\t\t!record.visible ||\n\t\t\t\t\tactive.controller.signal.aborted\n\t\t\t\t)\n\t\t\t\t\treturn;\n\t\t\t\tactive.handedOff = true;\n\t\t\t\ttask.mode = \"background\";\n\t\t\t\tchanged(record);\n\t\t\t\tactive.removeParent();\n\t\t\t\tresolveCaller({ kind: \"background\", task: snapshotOf(record) });\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tdone: new Promise<void>((resolve) => {\n\t\t\t\tresolveDone = resolve;\n\t\t\t}),\n\t\t};\n\t\tconst parentSignal = execution.signal;\n\t\tlet onUpdate = execution.background ? undefined : execution.onUpdate;\n\t\tconst parentAbort = () => {\n\t\t\tif (!active.detachRequested || !active.accepted) this.cancel(record);\n\t\t};\n\t\tparentSignal?.addEventListener(\"abort\", parentAbort, { once: true });\n\t\tactive.removeParent = () => {\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbort);\n\t\t\tonUpdate = undefined;\n\t\t};\n\t\tthis.store.records.set(task.id, record);\n\t\tthis.executions.set(task.id, active);\n\t\tconst control: TaskControl<T> = {\n\t\t\tid: task.id,\n\t\t\tsignal: active.controller.signal,\n\t\t\tget mode() {\n\t\t\t\treturn task.mode;\n\t\t\t},\n\t\t\tonModeChange: (listener) => {\n\t\t\t\tif (record.settled || this.closed) return () => {};\n\t\t\t\tactive.modeListeners.add(listener);\n\t\t\t\treturn () => {\n\t\t\t\t\tactive.modeListeners.delete(listener);\n\t\t\t\t};\n\t\t\t},\n\t\t\trequestCancel: () => this.cancel(record),\n\t\t\taccept: () => {\n\t\t\t\tif (record.settled || active.accepted || this.closed || active.controller.signal.aborted) return;\n\t\t\t\tactive.accepted = true;\n\t\t\t\tif (task.status === \"queued\") task.status = \"running\";\n\t\t\t\tchanged(record);\n\t\t\t\tif (active.detachRequested) active.removeParent();\n\t\t\t\t// Let an already available final result win over a handoff.\n\t\t\t\tqueueMicrotask(() => queueMicrotask(active.handoff));\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tpublish: (result) => {\n\t\t\t\tif (record.settled || this.closed) return;\n\t\t\t\tretainResult(task, result);\n\t\t\t\tchanged(record);\n\t\t\t\tif (result.usage !== undefined) active.publishedUsage = structuredClone(result.usage);\n\t\t\t\tif (!active.detachRequested && !active.handedOff) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tonUpdate?.(result);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* UI observers cannot stop execution. */\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t\tsetOutputPath: (path, cleanup) => {\n\t\t\t\tif (record.settled) {\n\t\t\t\t\tif (cleanup) throw new Error(\"Task execution has settled\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (record.cleanup) throw new Error(\"Managed output is already registered\");\n\t\t\t\t// Never truncate a real filesystem path into a different path.\n\t\t\t\tif (Buffer.byteLength(path) > 8192) throw new Error(\"Task output path is too large\");\n\t\t\t\trecord.cleanup = cleanup;\n\t\t\t\ttask.outputPath = path;\n\t\t\t\tchanged(record);\n\t\t\t\tthis.emit();\n\t\t\t},\n\t\t};\n\t\tconst finish = (completion: TaskCompletion<T> | undefined, error?: unknown) => {\n\t\t\tif (record.settled) return;\n\t\t\trecord.settled = true;\n\t\t\tactive.modeListeners.clear();\n\t\t\tactive.removeParent();\n\t\t\ttask.endedAt = Date.now();\n\t\t\tconst failed = completion === undefined;\n\t\t\ttask.status =\n\t\t\t\tcompletion?.status ??\n\t\t\t\t(error instanceof TaskExecutionError\n\t\t\t\t\t? error.status\n\t\t\t\t\t: active.controller.signal.aborted\n\t\t\t\t\t\t? \"cancelled\"\n\t\t\t\t\t\t: failed\n\t\t\t\t\t\t\t? \"failed\"\n\t\t\t\t\t\t\t: \"completed\");\n\t\t\tif (completion) {\n\t\t\t\tretainResult(task, completion.result);\n\t\t\t\tif (completion.error !== undefined) task.error = boundText(completion.error, 4096);\n\t\t\t\tif (completion.exitCode !== undefined) task.exitCode = completion.exitCode;\n\t\t\t}\n\t\t\tif (failed) {\n\t\t\t\ttask.error = errorText(error);\n\t\t\t\tretainResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{ content: [{ type: \"text\", text: task.error }, ...(task.result?.content ?? [])], details: undefined },\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t}\n\t\t\tchanged(record);\n\t\t\tlet settlementWarning: string | undefined;\n\t\t\ttry {\n\t\t\t\tthis.options.onSettled?.(\n\t\t\t\t\tsnapshotOf(record),\n\t\t\t\t\tcompletion?.usage ?? completion?.result.usage ?? active.publishedUsage,\n\t\t\t\t);\n\t\t\t} catch (accountingError) {\n\t\t\t\tconst warning = `Usage settlement failed: ${errorText(accountingError)}`;\n\t\t\t\tsettlementWarning = warning;\n\t\t\t\ttask.error = boundText([task.error, warning].filter(Boolean).join(\"\\n\"), 8192);\n\t\t\t\tretainResult(\n\t\t\t\t\ttask,\n\t\t\t\t\t{ content: [{ type: \"text\", text: warning }, ...(task.result?.content ?? [])], details: undefined },\n\t\t\t\t\ttask.resultTruncated,\n\t\t\t\t);\n\t\t\t\tchanged(record);\n\t\t\t}\n\t\t\tactive.publishedUsage = undefined;\n\t\t\t// Delivery becomes eligible only after settlement is persisted.\n\t\t\trecord.delivery = active.handedOff ? \"pending\" : \"delivered\";\n\t\t\tif (!active.handedOff) {\n\t\t\t\tif (failed) rejectCaller(error);\n\t\t\t\telse {\n\t\t\t\t\tconst { usage: _usage, ...result } = completion.result;\n\t\t\t\t\tif (settlementWarning) result.content = [{ type: \"text\", text: settlementWarning }, ...result.content];\n\t\t\t\t\tresolveCaller({ kind: \"result\", result, status: task.status, error: task.error });\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const waiter of [...record.waiters]) waiter();\n\t\t\tresolveDone();\n\t\t\tthis.executions.delete(task.id);\n\t\t\tthis.store.trim();\n\t\t\tthis.emit();\n\t\t};\n\t\t// The rejection handler is installed immediately, including for synchronous preflight throws.\n\t\ttry {\n\t\t\tconst running = execution.run(control);\n\t\t\tvoid Promise.resolve(running).then(\n\t\t\t\t(result) => finish(result),\n\t\t\t\t(error: unknown) => finish(undefined, error),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tfinish(undefined, error);\n\t\t}\n\t\tthis.emit();\n\t\treturn caller;\n\t}\n\n\tprivate detachable(record: TaskRecord): boolean {\n\t\tconst active = this.executions.get(record.task.id);\n\t\treturn !!active && !record.settled && !active.detachRequested && !active.controller.signal.aborted;\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.maxActive - this.backgroundActive();\n\t\tif (free <= 0) throw this.limitError();\n\t\tconst records = eligible.slice(0, free);\n\t\tfor (const record of records) this.prepareDetach(record);\n\t\tfor (const record of records) this.finishDetach(record);\n\t\tthis.emit();\n\t\treturn records.length;\n\t}\n\n\tcanDetach(id: string): boolean {\n\t\tconst record = this.lookup(id);\n\t\treturn this.enabled && this.backgroundActive() < this.maxActive && 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.maxActive) throw this.limitError();\n\t\tthis.prepareDetach(record);\n\t\tthis.finishDetach(record);\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tprivate prepareDetach(record: TaskRecord): void {\n\t\tconst active = this.executions.get(record.task.id)!;\n\t\tactive.detachRequested = true;\n\t\trecord.task.mode = \"background\";\n\t\tchanged(record);\n\t\tif (active.accepted) active.removeParent();\n\t}\n\n\tprivate finishDetach(record: TaskRecord): void {\n\t\tconst active = this.executions.get(record.task.id)!;\n\t\tactive.handoff();\n\t\tfor (const listener of active.modeListeners) {\n\t\t\ttry {\n\t\t\t\tlistener(record.task.mode);\n\t\t\t} catch {\n\t\t\t\t/* Executors own their diagnostics. */\n\t\t\t}\n\t\t}\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 boundText(\n\t\t\ttask.result?.content\n\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t.map((block) => block.text)\n\t\t\t\t.join(\"\\n\") ||\n\t\t\t\ttask.error ||\n\t\t\t\t\"No output yet.\",\n\t\t);\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\tconst active = this.executions.get(record.task.id);\n\t\tif (!active || record.settled || active.controller.signal.aborted) return false;\n\t\trecord.task.status = \"stopping\";\n\t\tchanged(record);\n\t\tactive.controller.abort();\n\t\tthis.emit();\n\t\treturn true;\n\t}\n\n\tsubscribe(listener: () => void): () => void {\n\t\tif (this.closed) return () => {};\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\t/**\n\t * 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)?.removeParent();\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,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ClB,IAAI,CAAC,IAAI,EAAE,CAAC;QACZ,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACjC,CAAC;IAEO,KAAK,CAAC,KAAK,CAAC,OAAqB,EAAE,OAAe;QACzD,IAAI,KAAgD,CAAC;QACrD,IAAI,CAAC;YACJ,MAAM,OAAO,CAAC,IAAI,CAAC;gBAClB,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,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"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Per-key concurrency lanes. Executions without a concurrency key start immediately. */
|
|
2
|
+
export interface Schedulable {
|
|
3
|
+
readonly concurrency?: {
|
|
4
|
+
key: string;
|
|
5
|
+
limit: number;
|
|
6
|
+
};
|
|
7
|
+
start(): void;
|
|
8
|
+
}
|
|
9
|
+
export declare class TaskScheduler {
|
|
10
|
+
private readonly lanes;
|
|
11
|
+
schedule(execution: Schedulable): void;
|
|
12
|
+
/** A settled execution frees its slot or leaves the queue; the next waiting one starts. */
|
|
13
|
+
release(execution: Schedulable): void;
|
|
14
|
+
private pump;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=scheduler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/scheduler.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,MAAM,WAAW,WAAW;IAC3B,QAAQ,CAAC,WAAW,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;IACtD,KAAK,IAAI,IAAI,CAAC;CACd;AAOD,qBAAa,aAAa;IACzB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA2B;IAEjD,QAAQ,CAAC,SAAS,EAAE,WAAW,GAAG,IAAI;IAetC,2FAA2F;IAC3F,OAAO,CAAC,SAAS,EAAE,WAAW,GAAG,IAAI;IAUrC,OAAO,CAAC,IAAI;CASZ"}
|