pi-subagent-manager 1.10.0 → 1.11.0
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/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +836 -0
- package/dist/index.js.map +1 -0
- package/dist/orch/checklist-integration.d.ts +48 -0
- package/dist/orch/checklist-integration.d.ts.map +1 -0
- package/dist/orch/checklist-integration.js +204 -0
- package/dist/orch/checklist-integration.js.map +1 -0
- package/dist/orch/context-entries.d.ts +8 -0
- package/dist/orch/context-entries.d.ts.map +1 -0
- package/dist/orch/context-entries.js +8 -0
- package/dist/orch/context-entries.js.map +1 -0
- package/dist/orch/cost-ledger.d.ts +16 -0
- package/dist/orch/cost-ledger.d.ts.map +1 -0
- package/dist/orch/cost-ledger.js +43 -0
- package/dist/orch/cost-ledger.js.map +1 -0
- package/dist/orch/diagnostics.d.ts +13 -0
- package/dist/orch/diagnostics.d.ts.map +1 -0
- package/dist/orch/diagnostics.js +95 -0
- package/dist/orch/diagnostics.js.map +1 -0
- package/dist/orch/extensions.d.ts +15 -0
- package/dist/orch/extensions.d.ts.map +1 -0
- package/dist/orch/extensions.js +80 -0
- package/dist/orch/extensions.js.map +1 -0
- package/dist/orch/housekeeping-usage.d.ts +14 -0
- package/dist/orch/housekeeping-usage.d.ts.map +1 -0
- package/dist/orch/housekeeping-usage.js +27 -0
- package/dist/orch/housekeeping-usage.js.map +1 -0
- package/dist/orch/housekeeping.d.ts +89 -0
- package/dist/orch/housekeeping.d.ts.map +1 -0
- package/dist/orch/housekeeping.js +281 -0
- package/dist/orch/housekeeping.js.map +1 -0
- package/dist/orch/inherited-tools.d.ts +18 -0
- package/dist/orch/inherited-tools.d.ts.map +1 -0
- package/dist/orch/inherited-tools.js +71 -0
- package/dist/orch/inherited-tools.js.map +1 -0
- package/dist/orch/mailbox.d.ts +59 -0
- package/dist/orch/mailbox.d.ts.map +1 -0
- package/dist/orch/mailbox.js +196 -0
- package/dist/orch/mailbox.js.map +1 -0
- package/dist/orch/manager.d.ts +82 -0
- package/dist/orch/manager.d.ts.map +1 -0
- package/dist/orch/manager.js +1010 -0
- package/dist/orch/manager.js.map +1 -0
- package/dist/orch/paths.d.ts +7 -0
- package/dist/orch/paths.d.ts.map +1 -0
- package/dist/orch/paths.js +73 -0
- package/dist/orch/paths.js.map +1 -0
- package/dist/orch/prompt.d.ts +7 -0
- package/dist/orch/prompt.d.ts.map +1 -0
- package/dist/orch/prompt.js +34 -0
- package/dist/orch/prompt.js.map +1 -0
- package/dist/orch/registry.d.ts +49 -0
- package/dist/orch/registry.d.ts.map +1 -0
- package/dist/orch/registry.js +134 -0
- package/dist/orch/registry.js.map +1 -0
- package/dist/orch/runtime.d.ts +11 -0
- package/dist/orch/runtime.d.ts.map +1 -0
- package/dist/orch/runtime.js +882 -0
- package/dist/orch/runtime.js.map +1 -0
- package/dist/orch/tools.d.ts +6 -0
- package/dist/orch/tools.d.ts.map +1 -0
- package/dist/orch/tools.js +114 -0
- package/dist/orch/tools.js.map +1 -0
- package/dist/orch/transcript.d.ts +28 -0
- package/dist/orch/transcript.d.ts.map +1 -0
- package/dist/orch/transcript.js +176 -0
- package/dist/orch/transcript.js.map +1 -0
- package/dist/prefs/agent-import.d.ts +37 -0
- package/dist/prefs/agent-import.d.ts.map +1 -0
- package/dist/prefs/agent-import.js +196 -0
- package/dist/prefs/agent-import.js.map +1 -0
- package/dist/prefs/config.d.ts +108 -0
- package/dist/prefs/config.d.ts.map +1 -0
- package/dist/prefs/config.js +926 -0
- package/dist/prefs/config.js.map +1 -0
- package/dist/prefs/import-discovery.d.ts +28 -0
- package/dist/prefs/import-discovery.d.ts.map +1 -0
- package/dist/prefs/import-discovery.js +562 -0
- package/dist/prefs/import-discovery.js.map +1 -0
- package/dist/prefs/import-instructions.d.ts +3 -0
- package/dist/prefs/import-instructions.d.ts.map +1 -0
- package/{src/prefs/import-instructions.ts → dist/prefs/import-instructions.js} +1 -0
- package/dist/prefs/import-instructions.js.map +1 -0
- package/dist/prefs/models.d.ts +24 -0
- package/dist/prefs/models.d.ts.map +1 -0
- package/dist/prefs/models.js +57 -0
- package/dist/prefs/models.js.map +1 -0
- package/dist/prefs/settings.d.ts +89 -0
- package/dist/prefs/settings.d.ts.map +1 -0
- package/dist/prefs/settings.js +505 -0
- package/dist/prefs/settings.js.map +1 -0
- package/dist/types.d.ts +293 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/ui/agent-loader.d.ts +21 -0
- package/dist/ui/agent-loader.d.ts.map +1 -0
- package/dist/ui/agent-loader.js +73 -0
- package/dist/ui/agent-loader.js.map +1 -0
- package/dist/ui/agent-navigation-editor.d.ts +46 -0
- package/dist/ui/agent-navigation-editor.d.ts.map +1 -0
- package/dist/ui/agent-navigation-editor.js +189 -0
- package/dist/ui/agent-navigation-editor.js.map +1 -0
- package/dist/ui/cost-footer.d.ts +37 -0
- package/dist/ui/cost-footer.d.ts.map +1 -0
- package/dist/ui/cost-footer.js +215 -0
- package/dist/ui/cost-footer.js.map +1 -0
- package/dist/ui/dialog.d.ts +135 -0
- package/dist/ui/dialog.d.ts.map +1 -0
- package/dist/ui/dialog.js +533 -0
- package/dist/ui/dialog.js.map +1 -0
- package/dist/ui/import-picker.d.ts +38 -0
- package/dist/ui/import-picker.d.ts.map +1 -0
- package/dist/ui/import-picker.js +211 -0
- package/dist/ui/import-picker.js.map +1 -0
- package/dist/ui/live-agent-view.d.ts +82 -0
- package/dist/ui/live-agent-view.d.ts.map +1 -0
- package/dist/ui/live-agent-view.js +546 -0
- package/dist/ui/live-agent-view.js.map +1 -0
- package/dist/ui/model-picker.d.ts +109 -0
- package/dist/ui/model-picker.d.ts.map +1 -0
- package/dist/ui/model-picker.js +549 -0
- package/dist/ui/model-picker.js.map +1 -0
- package/dist/ui/settings-ui.d.ts +17 -0
- package/dist/ui/settings-ui.d.ts.map +1 -0
- package/dist/ui/settings-ui.js +679 -0
- package/dist/ui/settings-ui.js.map +1 -0
- package/dist/ui/status-ui.d.ts +67 -0
- package/dist/ui/status-ui.d.ts.map +1 -0
- package/dist/ui/status-ui.js +487 -0
- package/dist/ui/status-ui.js.map +1 -0
- package/dist/ui/thread-tree.d.ts +22 -0
- package/dist/ui/thread-tree.d.ts.map +1 -0
- package/dist/ui/thread-tree.js +153 -0
- package/dist/ui/thread-tree.js.map +1 -0
- package/dist/ui/tool-picker.d.ts +46 -0
- package/dist/ui/tool-picker.d.ts.map +1 -0
- package/dist/ui/tool-picker.js +334 -0
- package/dist/ui/tool-picker.js.map +1 -0
- package/dist/ui/transcript-tool.d.ts +2 -0
- package/dist/ui/transcript-tool.d.ts.map +1 -0
- package/dist/ui/transcript-tool.js +100 -0
- package/dist/ui/transcript-tool.js.map +1 -0
- package/dist/ui/ui.d.ts +41 -0
- package/dist/ui/ui.d.ts.map +1 -0
- package/dist/ui/ui.js +1047 -0
- package/dist/ui/ui.js.map +1 -0
- package/docs/development.md +2 -1
- package/package.json +16 -4
- package/src/index.ts +0 -920
- package/src/orch/checklist-integration.ts +0 -230
- package/src/orch/context-entries.ts +0 -15
- package/src/orch/cost-ledger.ts +0 -56
- package/src/orch/diagnostics.ts +0 -95
- package/src/orch/extensions.ts +0 -83
- package/src/orch/housekeeping-usage.ts +0 -47
- package/src/orch/housekeeping.ts +0 -348
- package/src/orch/inherited-tools.ts +0 -84
- package/src/orch/mailbox.ts +0 -261
- package/src/orch/manager.ts +0 -1084
- package/src/orch/paths.ts +0 -73
- package/src/orch/prompt.ts +0 -39
- package/src/orch/registry.ts +0 -168
- package/src/orch/runtime.ts +0 -1041
- package/src/orch/tools.ts +0 -190
- package/src/orch/transcript.ts +0 -186
- package/src/prefs/agent-import.ts +0 -245
- package/src/prefs/config.ts +0 -1017
- package/src/prefs/import-discovery.ts +0 -643
- package/src/prefs/models.ts +0 -74
- package/src/prefs/settings.ts +0 -614
- package/src/types.ts +0 -271
- package/src/ui/agent-loader.ts +0 -98
- package/src/ui/agent-navigation-editor.ts +0 -233
- package/src/ui/cost-footer.ts +0 -230
- package/src/ui/dialog.ts +0 -678
- package/src/ui/import-picker.ts +0 -231
- package/src/ui/live-agent-view.ts +0 -600
- package/src/ui/model-picker.ts +0 -701
- package/src/ui/settings-ui.ts +0 -830
- package/src/ui/status-ui.ts +0 -628
- package/src/ui/thread-tree.ts +0 -173
- package/src/ui/tool-picker.ts +0 -398
- package/src/ui/transcript-tool.ts +0 -142
- package/src/ui/ui.ts +0 -1407
|
@@ -0,0 +1,1010 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { immutableTranscriptValue } from "./transcript.js";
|
|
3
|
+
import { canonicalPath, inheritContext, isDescendant, parentPath } from "./paths.js";
|
|
4
|
+
import { DEFAULT_MANAGER_SETTINGS } from "../prefs/settings.js";
|
|
5
|
+
const RECENT_ACTIVITY_LIMIT = 12;
|
|
6
|
+
const active = (view) => view.state === "starting" || view.state === "running";
|
|
7
|
+
export const MIN_SPAWN_TIMEOUT_MS = 30_000;
|
|
8
|
+
export const MAX_SPAWN_TIMEOUT_MS = 300_000;
|
|
9
|
+
function assertSpawnTimeout(timeoutMs) {
|
|
10
|
+
if (!Number.isInteger(timeoutMs) ||
|
|
11
|
+
timeoutMs < MIN_SPAWN_TIMEOUT_MS ||
|
|
12
|
+
timeoutMs > MAX_SPAWN_TIMEOUT_MS)
|
|
13
|
+
throw new Error(`timeoutMs must be an integer between ${MIN_SPAWN_TIMEOUT_MS} (30s) and ${MAX_SPAWN_TIMEOUT_MS} (5min)`);
|
|
14
|
+
}
|
|
15
|
+
const errorText = (error) => (error instanceof Error ? error.message : String(error));
|
|
16
|
+
function abortable(work, signal) {
|
|
17
|
+
if (signal.aborted) {
|
|
18
|
+
void work.catch(() => { });
|
|
19
|
+
return Promise.reject(signal.reason);
|
|
20
|
+
}
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const cancel = () => reject(signal.reason ?? new Error("Startup cancelled"));
|
|
23
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
24
|
+
work.then((value) => {
|
|
25
|
+
signal.removeEventListener("abort", cancel);
|
|
26
|
+
resolve(value);
|
|
27
|
+
}, (error) => {
|
|
28
|
+
signal.removeEventListener("abort", cancel);
|
|
29
|
+
reject(error);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/** Runtime-neutral thread ownership, context inheritance, lifecycle and durable registry. */
|
|
34
|
+
export class ThreadManager {
|
|
35
|
+
options;
|
|
36
|
+
records = new Map();
|
|
37
|
+
disposed = false;
|
|
38
|
+
epoch = 0;
|
|
39
|
+
constructor(options) {
|
|
40
|
+
this.options = options;
|
|
41
|
+
}
|
|
42
|
+
/** New limits affect future launches/resumes, never cancel existing work. */
|
|
43
|
+
setLimits(limits) {
|
|
44
|
+
this.options = { ...this.options, ...limits };
|
|
45
|
+
}
|
|
46
|
+
list() {
|
|
47
|
+
return [...this.records.values()].map((record) => this.view(record));
|
|
48
|
+
}
|
|
49
|
+
/** Preview eligible completed sessions without changing retained records. */
|
|
50
|
+
reapCandidates(only) {
|
|
51
|
+
this.assertLive();
|
|
52
|
+
const records = [...this.records.values()];
|
|
53
|
+
const eligible = new Set(records
|
|
54
|
+
.filter((record) => !only || only.includes(record.view.path))
|
|
55
|
+
.filter((record) => record.view.state === "completed" && (!record.initializing || record.driver))
|
|
56
|
+
.filter((record) => !records.some((other) => active(other.view) && isDescendant(record.view.path, other.view.path)))
|
|
57
|
+
.map((record) => record.view.path));
|
|
58
|
+
// Any retained descendant still needs its lexical ancestors.
|
|
59
|
+
for (const record of records) {
|
|
60
|
+
if (eligible.has(record.view.path))
|
|
61
|
+
continue;
|
|
62
|
+
let parent = record.view.parent;
|
|
63
|
+
while (parent && parent !== "/root") {
|
|
64
|
+
eligible.delete(parent);
|
|
65
|
+
parent = this.records.get(parent)?.view.parent ?? null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return records
|
|
69
|
+
.filter((record) => eligible.has(record.view.path))
|
|
70
|
+
.sort((a, b) => a.view.createdAt - b.view.createdAt)
|
|
71
|
+
.map((record) => record.view.path);
|
|
72
|
+
}
|
|
73
|
+
/** Revalidate an optional confirmed snapshot before forgetting sessions. */
|
|
74
|
+
reap(only) {
|
|
75
|
+
const reaped = [];
|
|
76
|
+
for (const path of this.reapCandidates(only)) {
|
|
77
|
+
const record = this.records.get(path);
|
|
78
|
+
this.clearTimeout(record);
|
|
79
|
+
record.detachTranscript?.();
|
|
80
|
+
record.transcriptListeners?.clear();
|
|
81
|
+
record.driver?.dispose();
|
|
82
|
+
this.records.delete(record.view.path);
|
|
83
|
+
reaped.push(record.view.path);
|
|
84
|
+
}
|
|
85
|
+
return reaped;
|
|
86
|
+
}
|
|
87
|
+
/** Bind authority once; models and the user UI share this small composable service. */
|
|
88
|
+
scope(caller) {
|
|
89
|
+
caller = canonicalPath(caller);
|
|
90
|
+
return {
|
|
91
|
+
list: () => this.list().filter((thread) => caller === "/root" || thread.path === caller || isDescendant(thread.path, caller)),
|
|
92
|
+
get: (path) => this.get(path, caller),
|
|
93
|
+
output: (path) => this.output(path, caller),
|
|
94
|
+
transcript: (path) => this.transcript(caller, path),
|
|
95
|
+
observeTranscript: (path, listener) => this.observeTranscript(caller, path, listener),
|
|
96
|
+
spawn: (args, signal) => this.spawn(caller, args, signal),
|
|
97
|
+
steer: (path, message, timeoutMs) => this.steer(caller, path, message, timeoutMs),
|
|
98
|
+
wait: (path, timeoutMs, signal) => this.wait(caller, path, timeoutMs, signal),
|
|
99
|
+
update: (message) => this.update(caller, message),
|
|
100
|
+
pause: (reason) => this.pause(caller, reason),
|
|
101
|
+
stop: (path) => this.stop(caller, path),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
get(path, caller = "/root") {
|
|
105
|
+
path = canonicalPath(path, caller);
|
|
106
|
+
this.assertAccess(caller, path, true);
|
|
107
|
+
if (path === "/root")
|
|
108
|
+
return {
|
|
109
|
+
path,
|
|
110
|
+
parent: null,
|
|
111
|
+
owner: path,
|
|
112
|
+
type: "main",
|
|
113
|
+
state: "running",
|
|
114
|
+
task: "Main Pi session",
|
|
115
|
+
status: "main",
|
|
116
|
+
createdAt: 0,
|
|
117
|
+
updatedAt: Date.now(),
|
|
118
|
+
};
|
|
119
|
+
return this.view(this.record(path));
|
|
120
|
+
}
|
|
121
|
+
output(path, caller = "/root") {
|
|
122
|
+
const view = this.get(path, caller);
|
|
123
|
+
if (view.state === "paused")
|
|
124
|
+
return ""; // No answer handback from a paused turn.
|
|
125
|
+
return view.output ?? "";
|
|
126
|
+
}
|
|
127
|
+
saved() {
|
|
128
|
+
return [...this.records.values()].map((record) => {
|
|
129
|
+
const current = this.view(record);
|
|
130
|
+
// Explicit durable schema: adding UI fields must not silently change session storage.
|
|
131
|
+
const view = {
|
|
132
|
+
path: current.path,
|
|
133
|
+
parent: current.parent,
|
|
134
|
+
owner: current.owner,
|
|
135
|
+
type: current.type,
|
|
136
|
+
color: current.color,
|
|
137
|
+
icon: current.icon,
|
|
138
|
+
model: current.model,
|
|
139
|
+
thinkingLevel: current.thinkingLevel,
|
|
140
|
+
state: current.state,
|
|
141
|
+
task: current.task,
|
|
142
|
+
status: current.status,
|
|
143
|
+
output: current.output,
|
|
144
|
+
error: current.error,
|
|
145
|
+
createdAt: current.createdAt,
|
|
146
|
+
...(current.lastStartedAt !== undefined ? { lastStartedAt: current.lastStartedAt } : {}),
|
|
147
|
+
sessionFile: current.sessionFile,
|
|
148
|
+
// Settled totals only. startedAt and partial usage must not churn persistence.
|
|
149
|
+
elapsedMs: record.view.elapsedMs ?? 0,
|
|
150
|
+
inputTokens: record.view.inputTokens ?? 0,
|
|
151
|
+
outputTokens: record.view.outputTokens ?? 0,
|
|
152
|
+
costUsd: record.view.costUsd,
|
|
153
|
+
costId: record.view.costId,
|
|
154
|
+
};
|
|
155
|
+
const sessionLeafId = this.sessionLeafId(record);
|
|
156
|
+
if (sessionLeafId !== undefined)
|
|
157
|
+
view.sessionLeafId = sessionLeafId;
|
|
158
|
+
if (active(view))
|
|
159
|
+
view.status = view.state === "running" ? "Working" : "Starting";
|
|
160
|
+
return {
|
|
161
|
+
view,
|
|
162
|
+
definition: structuredClone(record.definition),
|
|
163
|
+
...(!view.sessionFile && !record.contextPending
|
|
164
|
+
? {
|
|
165
|
+
inherited: structuredClone(record.inherited),
|
|
166
|
+
inheritedContextEntries: structuredClone(record.inheritedContextEntries),
|
|
167
|
+
}
|
|
168
|
+
: {}),
|
|
169
|
+
};
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
restore(saved) {
|
|
173
|
+
if (this.records.size)
|
|
174
|
+
throw new Error("Restore requires an empty thread registry");
|
|
175
|
+
const restored = new Map();
|
|
176
|
+
for (const item of saved) {
|
|
177
|
+
const savedView = structuredClone(item.view);
|
|
178
|
+
const path = canonicalPath(savedView.path);
|
|
179
|
+
if (path === "/root" ||
|
|
180
|
+
restored.has(path) ||
|
|
181
|
+
!["starting", "running", "paused", "completed", "failed", "stopped"].includes(savedView.state))
|
|
182
|
+
throw new Error("Invalid saved thread registry");
|
|
183
|
+
const { sessionLeafId, ...storedView } = savedView;
|
|
184
|
+
const view = {
|
|
185
|
+
...storedView,
|
|
186
|
+
costId: storedView.costId ??
|
|
187
|
+
`legacy:${storedView.sessionFile ?? `${storedView.path}:${storedView.createdAt}`}`,
|
|
188
|
+
icon: storedView.icon ?? item.definition.icon,
|
|
189
|
+
updatedAt: Date.now(),
|
|
190
|
+
elapsedMs: storedView.elapsedMs ?? 0,
|
|
191
|
+
inputTokens: storedView.inputTokens ?? 0,
|
|
192
|
+
outputTokens: storedView.outputTokens ?? 0,
|
|
193
|
+
};
|
|
194
|
+
delete view.startedAt;
|
|
195
|
+
if (view.parent !== parentPath(path))
|
|
196
|
+
throw new Error(`Invalid saved parent for ${path}`);
|
|
197
|
+
if (active(view)) {
|
|
198
|
+
view.state = "paused";
|
|
199
|
+
view.status = "Interrupted by reload; send input to resume";
|
|
200
|
+
delete view.output;
|
|
201
|
+
}
|
|
202
|
+
restored.set(path, {
|
|
203
|
+
view,
|
|
204
|
+
definition: structuredClone(item.definition),
|
|
205
|
+
inherited: structuredClone(item.inherited ?? []),
|
|
206
|
+
inheritedContextEntries: structuredClone(item.inheritedContextEntries ?? []),
|
|
207
|
+
// A reservation saved before its lexical parent opened has no snapshot yet.
|
|
208
|
+
contextPending: !view.sessionFile && item.inherited === undefined && view.parent !== null,
|
|
209
|
+
startup: new AbortController(),
|
|
210
|
+
...(Object.prototype.hasOwnProperty.call(savedView, "sessionLeafId")
|
|
211
|
+
? { sessionLeafId }
|
|
212
|
+
: {}),
|
|
213
|
+
pauseRequested: false,
|
|
214
|
+
stopRequested: false,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
for (const record of restored.values()) {
|
|
218
|
+
if (record.view.parent && record.view.parent !== "/root" && !restored.has(record.view.parent))
|
|
219
|
+
throw new Error(`Missing saved parent ${record.view.parent}`);
|
|
220
|
+
}
|
|
221
|
+
this.records = restored;
|
|
222
|
+
}
|
|
223
|
+
async spawn(caller, args, signal) {
|
|
224
|
+
this.assertLive();
|
|
225
|
+
if (args.timeoutMs !== undefined)
|
|
226
|
+
assertSpawnTimeout(args.timeoutMs);
|
|
227
|
+
caller = canonicalPath(caller);
|
|
228
|
+
if (caller !== "/root" &&
|
|
229
|
+
(!active(this.record(caller).view) || this.record(caller).stopRequested))
|
|
230
|
+
throw new Error("Only a working agent may spawn children");
|
|
231
|
+
signal?.throwIfAborted();
|
|
232
|
+
const path = canonicalPath(args.path, caller);
|
|
233
|
+
this.assertAccess(caller, path);
|
|
234
|
+
if (path === "/root" || this.records.has(path))
|
|
235
|
+
throw new Error(`Thread ${path} already exists; use agent_steer to resume it`);
|
|
236
|
+
const parent = parentPath(path);
|
|
237
|
+
if (parent && parent !== "/root")
|
|
238
|
+
this.record(parent);
|
|
239
|
+
if (caller !== "/root" && parent !== caller)
|
|
240
|
+
throw new Error("An agent may spawn only its immediate children");
|
|
241
|
+
if (!args.task.trim())
|
|
242
|
+
throw new Error("Task must not be empty");
|
|
243
|
+
const segments = path.slice(1).split("/");
|
|
244
|
+
// Independent roots still represent agents launched by the main L1 conversation.
|
|
245
|
+
const level = segments.length + (segments[0] === "root" ? 0 : 1);
|
|
246
|
+
const maxLevels = this.options.maxLevels ?? DEFAULT_MANAGER_SETTINGS.maxLevels;
|
|
247
|
+
if (this.options.maxLevels === undefined && this.options.maxDepth !== undefined
|
|
248
|
+
? segments.length - 1 > this.options.maxDepth
|
|
249
|
+
: level > maxLevels)
|
|
250
|
+
throw new Error("Agent depth limit reached");
|
|
251
|
+
if (this.records.size >= (this.options.maxThreads ?? DEFAULT_MANAGER_SETTINGS.maxThreads))
|
|
252
|
+
throw new Error("Total thread limit reached");
|
|
253
|
+
this.assertCapacity();
|
|
254
|
+
const type = structuredClone(this.options.getType(args.type));
|
|
255
|
+
const parentRecord = parent && parent !== "/root" ? this.record(parent) : undefined;
|
|
256
|
+
this.assertStartableAncestors(path);
|
|
257
|
+
// Reservation is synchronous: subtree cancellation sees children even during lazy parent reopen.
|
|
258
|
+
const inherited = parent === "/root"
|
|
259
|
+
? inheritContext(this.options.rootSnapshot())
|
|
260
|
+
: parentRecord?.driver
|
|
261
|
+
? inheritContext(parentRecord.driver.snapshot())
|
|
262
|
+
: [];
|
|
263
|
+
const inheritedContextEntries = structuredClone(parent === "/root"
|
|
264
|
+
? (this.options.rootContextEntries?.() ?? [])
|
|
265
|
+
: (parentRecord?.driver?.contextEntries?.() ?? []));
|
|
266
|
+
const now = Date.now();
|
|
267
|
+
const record = {
|
|
268
|
+
view: {
|
|
269
|
+
path,
|
|
270
|
+
parent,
|
|
271
|
+
owner: parent ?? caller,
|
|
272
|
+
type: type.name,
|
|
273
|
+
color: type.color,
|
|
274
|
+
icon: type.icon,
|
|
275
|
+
state: "starting",
|
|
276
|
+
task: args.task,
|
|
277
|
+
status: "Starting",
|
|
278
|
+
createdAt: now,
|
|
279
|
+
costId: randomUUID(),
|
|
280
|
+
updatedAt: now,
|
|
281
|
+
elapsedMs: 0,
|
|
282
|
+
inputTokens: 0,
|
|
283
|
+
outputTokens: 0,
|
|
284
|
+
},
|
|
285
|
+
definition: type,
|
|
286
|
+
inherited,
|
|
287
|
+
inheritedContextEntries,
|
|
288
|
+
contextPending: !!(parentRecord && !parentRecord.driver),
|
|
289
|
+
startup: new AbortController(),
|
|
290
|
+
pauseRequested: false,
|
|
291
|
+
stopRequested: false,
|
|
292
|
+
};
|
|
293
|
+
this.records.set(path, record);
|
|
294
|
+
if (record.contextPending)
|
|
295
|
+
this.prepareInheritedContext(record);
|
|
296
|
+
record.async = args.wait === false;
|
|
297
|
+
this.start(record, args.task);
|
|
298
|
+
if (args.timeoutMs !== undefined)
|
|
299
|
+
this.armTimeout(record, args.timeoutMs);
|
|
300
|
+
return args.wait === false ? this.view(record) : this.wait(caller, path, undefined, signal);
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Steer/resume a thread and/or re-arm its report-only timeout.
|
|
304
|
+
* timeoutMs without message only re-arms (the child must be running); both does steer then re-arm.
|
|
305
|
+
*/
|
|
306
|
+
async steer(caller, path, message, timeoutMs) {
|
|
307
|
+
this.assertLive();
|
|
308
|
+
caller = canonicalPath(caller);
|
|
309
|
+
path = canonicalPath(path, caller);
|
|
310
|
+
this.assertAccess(caller, path);
|
|
311
|
+
if (message === undefined && timeoutMs === undefined)
|
|
312
|
+
throw new Error("Provide message, timeoutMs, or both");
|
|
313
|
+
if (timeoutMs !== undefined)
|
|
314
|
+
assertSpawnTimeout(timeoutMs);
|
|
315
|
+
if (message === undefined)
|
|
316
|
+
return this.extendTimeout(caller, path, timeoutMs);
|
|
317
|
+
if (!message.trim())
|
|
318
|
+
throw new Error("Steering message must not be empty");
|
|
319
|
+
const record = this.record(path);
|
|
320
|
+
const rearm = () => {
|
|
321
|
+
if (timeoutMs !== undefined && active(record.view) && !record.stopRequested)
|
|
322
|
+
this.armTimeout(record, timeoutMs);
|
|
323
|
+
return this.view(record);
|
|
324
|
+
};
|
|
325
|
+
for (;;) {
|
|
326
|
+
this.assertLive();
|
|
327
|
+
this.assertCallerMaySteer(caller);
|
|
328
|
+
if (!active(record.view))
|
|
329
|
+
this.assertStartableAncestors(path);
|
|
330
|
+
// A detached spawn reserves immediately, but its original task must reach prompt() before steering.
|
|
331
|
+
if (record.view.state === "starting") {
|
|
332
|
+
if (!record.started)
|
|
333
|
+
throw new Error("Thread start invariant violated");
|
|
334
|
+
await record.started;
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
if (record.stopRequested && active(record.view))
|
|
338
|
+
throw new Error("Thread is stopping; wait for stopped state before resuming");
|
|
339
|
+
if (record.view.state === "running") {
|
|
340
|
+
await record.driver.steer(message);
|
|
341
|
+
this.touch(record);
|
|
342
|
+
return rearm();
|
|
343
|
+
}
|
|
344
|
+
this.assertCapacity();
|
|
345
|
+
// Resumes return immediately, regardless of the original spawn mode or restored metadata.
|
|
346
|
+
record.async = true;
|
|
347
|
+
this.start(record, message);
|
|
348
|
+
return rearm();
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
async wait(caller, path, timeoutMs, signal) {
|
|
352
|
+
path = canonicalPath(path, caller);
|
|
353
|
+
this.assertAccess(caller, path);
|
|
354
|
+
const record = this.record(path);
|
|
355
|
+
if (!active(record.view))
|
|
356
|
+
return this.view(record);
|
|
357
|
+
if (timeoutMs !== undefined &&
|
|
358
|
+
(!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 3_600_000))
|
|
359
|
+
throw new Error("timeoutMs must be between 0 and 3600000");
|
|
360
|
+
if (signal?.aborted)
|
|
361
|
+
throw new Error("Waiting cancelled; thread remains running");
|
|
362
|
+
await new Promise((resolve, reject) => {
|
|
363
|
+
let timer;
|
|
364
|
+
const finish = (error) => {
|
|
365
|
+
if (timer)
|
|
366
|
+
clearTimeout(timer);
|
|
367
|
+
signal?.removeEventListener("abort", cancel);
|
|
368
|
+
error ? reject(error) : resolve();
|
|
369
|
+
};
|
|
370
|
+
const cancel = () => finish(new Error("Waiting cancelled; thread remains running"));
|
|
371
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
372
|
+
if (timeoutMs !== undefined)
|
|
373
|
+
timer = setTimeout(() => finish(), timeoutMs);
|
|
374
|
+
record.run.then(() => finish(), (error) => finish(new Error(errorText(error))));
|
|
375
|
+
});
|
|
376
|
+
return this.view(record);
|
|
377
|
+
}
|
|
378
|
+
update(caller, message) {
|
|
379
|
+
const record = this.record(caller);
|
|
380
|
+
if (!active(record.view))
|
|
381
|
+
throw new Error("Only a working child may report progress");
|
|
382
|
+
if (!message.trim() || message.length > 8000)
|
|
383
|
+
throw new Error("Progress message must contain 1–8000 characters");
|
|
384
|
+
record.view.status = message;
|
|
385
|
+
// An explicit progress report outranks a generated summary until fresh activity.
|
|
386
|
+
delete record.view.summary;
|
|
387
|
+
this.touch(record);
|
|
388
|
+
this.emit({
|
|
389
|
+
kind: "update",
|
|
390
|
+
thread: this.view(record),
|
|
391
|
+
message,
|
|
392
|
+
recipient: record.view.parent ?? record.view.owner,
|
|
393
|
+
});
|
|
394
|
+
return this.view(record);
|
|
395
|
+
}
|
|
396
|
+
pause(caller, reason) {
|
|
397
|
+
const record = this.record(caller);
|
|
398
|
+
if (!active(record.view))
|
|
399
|
+
throw new Error("Only a working child may pause itself");
|
|
400
|
+
record.pauseRequested = true;
|
|
401
|
+
record.view.status = reason.trim() || "Awaiting further input";
|
|
402
|
+
delete record.view.summary;
|
|
403
|
+
this.touch(record);
|
|
404
|
+
// Remains running until the SDK settles. No interim final answer leaks through wait().
|
|
405
|
+
return this.view(record);
|
|
406
|
+
}
|
|
407
|
+
async stop(caller, path) {
|
|
408
|
+
path = canonicalPath(path, caller);
|
|
409
|
+
this.assertAccess(caller, path);
|
|
410
|
+
const record = this.record(path);
|
|
411
|
+
const targets = [...this.records.values()].filter((item) => item === record || (isDescendant(item.view.path, path) && active(item.view)));
|
|
412
|
+
for (const item of targets) {
|
|
413
|
+
item.stopRequested = true;
|
|
414
|
+
item.startup.abort();
|
|
415
|
+
this.clearTimeout(item);
|
|
416
|
+
}
|
|
417
|
+
await Promise.all(targets.map(async (item) => {
|
|
418
|
+
if (item.driver)
|
|
419
|
+
await item.driver.abort();
|
|
420
|
+
await item.run;
|
|
421
|
+
item.view.state = "stopped";
|
|
422
|
+
item.view.status = "Stopped; session retained";
|
|
423
|
+
delete item.view.output;
|
|
424
|
+
this.touch(item);
|
|
425
|
+
}));
|
|
426
|
+
return this.view(record);
|
|
427
|
+
}
|
|
428
|
+
async transcript(caller, path) {
|
|
429
|
+
path = canonicalPath(path, caller);
|
|
430
|
+
this.assertAccess(caller, path, true);
|
|
431
|
+
const driver = await this.ensureDriver(this.record(path), true);
|
|
432
|
+
return JSON.stringify(driver.snapshot(), null, 2);
|
|
433
|
+
}
|
|
434
|
+
async observeTranscript(caller, path, listener) {
|
|
435
|
+
this.assertLive();
|
|
436
|
+
path = canonicalPath(path, caller);
|
|
437
|
+
this.assertAccess(caller, path, true);
|
|
438
|
+
if (path === "/root")
|
|
439
|
+
throw new Error("Main is not a child transcript observation target");
|
|
440
|
+
const record = this.record(path);
|
|
441
|
+
// Idle/restored history may be lazily loaded, but attachment never prompts/resumes a turn.
|
|
442
|
+
if (!active(record.view))
|
|
443
|
+
await this.ensureDriver(record, true);
|
|
444
|
+
this.assertLive();
|
|
445
|
+
const listeners = (record.transcriptListeners ??= new Set());
|
|
446
|
+
const registered = (snapshot) => listener(snapshot);
|
|
447
|
+
listeners.add(registered);
|
|
448
|
+
if (record.driver)
|
|
449
|
+
this.attachTranscript(record, record.driver);
|
|
450
|
+
else {
|
|
451
|
+
// A starting child gets a placeholder immediately; existing startup supplies the live source.
|
|
452
|
+
void this.ensureDriver(record, true).catch((error) => {
|
|
453
|
+
if (this.disposed || !listeners.has(registered))
|
|
454
|
+
return;
|
|
455
|
+
record.observationError = errorText(error);
|
|
456
|
+
this.publishTranscript(record);
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
return {
|
|
460
|
+
snapshot: this.transcriptSnapshot(record),
|
|
461
|
+
unsubscribe: () => {
|
|
462
|
+
listeners.delete(registered);
|
|
463
|
+
if (!listeners.size) {
|
|
464
|
+
record.detachTranscript?.();
|
|
465
|
+
record.detachTranscript = undefined;
|
|
466
|
+
record.transcriptSource = undefined;
|
|
467
|
+
}
|
|
468
|
+
},
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
/** Re-arm a running child's report-only timeout from now (replaces any pending timer). */
|
|
472
|
+
extendTimeout(caller, path, timeoutMs) {
|
|
473
|
+
this.assertLive();
|
|
474
|
+
path = canonicalPath(path, caller);
|
|
475
|
+
this.assertAccess(caller, path);
|
|
476
|
+
assertSpawnTimeout(timeoutMs);
|
|
477
|
+
const record = this.record(path);
|
|
478
|
+
if (!active(record.view) || record.stopRequested)
|
|
479
|
+
throw new Error("Only a working agent has a timeout to extend");
|
|
480
|
+
this.armTimeout(record, timeoutMs);
|
|
481
|
+
return this.view(record);
|
|
482
|
+
}
|
|
483
|
+
/** Number of detached agents still working; recap waits for this to reach zero. */
|
|
484
|
+
outstandingAsync() {
|
|
485
|
+
return [...this.records.values()].filter((r) => r.async && active(r.view)).length;
|
|
486
|
+
}
|
|
487
|
+
clearTimeout(record) {
|
|
488
|
+
if (record.timeoutTimer !== undefined)
|
|
489
|
+
clearTimeout(record.timeoutTimer);
|
|
490
|
+
record.timeoutTimer = undefined;
|
|
491
|
+
}
|
|
492
|
+
armTimeout(record, timeoutMs) {
|
|
493
|
+
this.clearTimeout(record);
|
|
494
|
+
record.timeoutTimer = setTimeout(() => {
|
|
495
|
+
record.timeoutTimer = undefined;
|
|
496
|
+
if (this.disposed || !active(record.view) || record.stopRequested)
|
|
497
|
+
return;
|
|
498
|
+
this.emit({
|
|
499
|
+
kind: "timeout",
|
|
500
|
+
thread: this.view(record),
|
|
501
|
+
recipient: record.view.parent ?? record.view.owner,
|
|
502
|
+
timeoutMs,
|
|
503
|
+
recentOutput: this.recentOutput(record),
|
|
504
|
+
});
|
|
505
|
+
}, timeoutMs);
|
|
506
|
+
record.timeoutTimer.unref?.();
|
|
507
|
+
}
|
|
508
|
+
recentOutput(record) {
|
|
509
|
+
const parts = [];
|
|
510
|
+
try {
|
|
511
|
+
const messages = record.driver?.snapshot() ?? [];
|
|
512
|
+
for (const message of messages.slice(-6)) {
|
|
513
|
+
if (message.role !== "assistant")
|
|
514
|
+
continue;
|
|
515
|
+
const content = message.content;
|
|
516
|
+
const text = Array.isArray(content)
|
|
517
|
+
? content
|
|
518
|
+
.filter((c) => c?.type === "text" && typeof c.text === "string")
|
|
519
|
+
.map((c) => c.text)
|
|
520
|
+
.join("\n")
|
|
521
|
+
: typeof content === "string"
|
|
522
|
+
? content
|
|
523
|
+
: "";
|
|
524
|
+
if (text.trim())
|
|
525
|
+
parts.push(text.trim());
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
/* best effort */
|
|
530
|
+
}
|
|
531
|
+
return parts.slice(-2).join("\n---\n").slice(-2000);
|
|
532
|
+
}
|
|
533
|
+
async deliver(path, content) {
|
|
534
|
+
// Restored parents may be idle and unopened; reports still belong in their retained transcript.
|
|
535
|
+
const driver = await this.ensureDriver(this.record(path), true);
|
|
536
|
+
await driver.sendUpdate(content);
|
|
537
|
+
}
|
|
538
|
+
async shutdown() {
|
|
539
|
+
this.disposed = true;
|
|
540
|
+
this.epoch++;
|
|
541
|
+
const records = [...this.records.values()];
|
|
542
|
+
for (const record of records) {
|
|
543
|
+
record.detachTranscript?.();
|
|
544
|
+
record.detachTranscript = undefined;
|
|
545
|
+
record.transcriptSource = undefined;
|
|
546
|
+
record.transcriptListeners?.clear();
|
|
547
|
+
record.stopRequested = true;
|
|
548
|
+
record.startup.abort();
|
|
549
|
+
this.clearTimeout(record);
|
|
550
|
+
}
|
|
551
|
+
await Promise.all(records.map(async (record) => {
|
|
552
|
+
await record.driver?.abort();
|
|
553
|
+
await record.initializing?.catch(() => { });
|
|
554
|
+
await record.run;
|
|
555
|
+
await record.driver?.dispose();
|
|
556
|
+
}));
|
|
557
|
+
}
|
|
558
|
+
start(record, message) {
|
|
559
|
+
this.freezeElapsed(record);
|
|
560
|
+
record.pauseRequested = false;
|
|
561
|
+
record.stopRequested = false;
|
|
562
|
+
record.startup = new AbortController();
|
|
563
|
+
record.view.state = "starting";
|
|
564
|
+
record.view.status = "Starting";
|
|
565
|
+
record.view.startedAt = Date.now();
|
|
566
|
+
record.view.lastStartedAt = record.view.startedAt;
|
|
567
|
+
delete record.view.output;
|
|
568
|
+
delete record.view.error;
|
|
569
|
+
delete record.view.summary;
|
|
570
|
+
record.runId = (record.runId ?? 0) + 1;
|
|
571
|
+
record.recentActivity = [];
|
|
572
|
+
const epoch = this.epoch;
|
|
573
|
+
let markStarted;
|
|
574
|
+
record.started = new Promise((resolve) => {
|
|
575
|
+
markStarted = resolve;
|
|
576
|
+
});
|
|
577
|
+
record.run = Promise.resolve().then(async () => {
|
|
578
|
+
try {
|
|
579
|
+
const contextReady = this.prepareInheritedContext(record);
|
|
580
|
+
if (contextReady)
|
|
581
|
+
await abortable(contextReady, record.startup.signal);
|
|
582
|
+
record.startup.signal.throwIfAborted();
|
|
583
|
+
const driver = await this.ensureDriver(record);
|
|
584
|
+
if (record.stopRequested || this.disposed) {
|
|
585
|
+
record.view.state = "stopped";
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
const task = driver.prompt(message);
|
|
589
|
+
record.view.state = "running";
|
|
590
|
+
record.view.status = "Working";
|
|
591
|
+
this.touch(record);
|
|
592
|
+
markStarted();
|
|
593
|
+
await task;
|
|
594
|
+
record.view.state = record.stopRequested
|
|
595
|
+
? "stopped"
|
|
596
|
+
: record.pauseRequested
|
|
597
|
+
? "paused"
|
|
598
|
+
: "completed";
|
|
599
|
+
if (record.view.state === "completed") {
|
|
600
|
+
record.view.output = driver.output();
|
|
601
|
+
record.view.status = "Completed; session retained";
|
|
602
|
+
}
|
|
603
|
+
else if (record.view.state === "stopped")
|
|
604
|
+
record.view.status = "Stopped; session retained";
|
|
605
|
+
}
|
|
606
|
+
catch (error) {
|
|
607
|
+
record.view.state = record.stopRequested ? "stopped" : "failed";
|
|
608
|
+
record.view.error = errorText(error);
|
|
609
|
+
record.view.status = record.stopRequested ? "Stopped; session retained" : record.view.error;
|
|
610
|
+
}
|
|
611
|
+
finally {
|
|
612
|
+
this.clearTimeout(record);
|
|
613
|
+
this.freezeElapsed(record);
|
|
614
|
+
// A settled agent shows its real status; summaries describe active work only.
|
|
615
|
+
delete record.view.summary;
|
|
616
|
+
record.liveInputTokens = 0;
|
|
617
|
+
record.liveOutputTokens = 0;
|
|
618
|
+
record.liveCostUsd = undefined;
|
|
619
|
+
markStarted(); // Failed/cancelled initialization must also release callers waiting to steer.
|
|
620
|
+
this.touch(record);
|
|
621
|
+
if (!this.disposed && epoch === this.epoch)
|
|
622
|
+
this.emit({
|
|
623
|
+
kind: "settled",
|
|
624
|
+
thread: this.view(record),
|
|
625
|
+
recipient: record.view.parent ?? record.view.owner,
|
|
626
|
+
async: record.async === true,
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
});
|
|
630
|
+
this.touch(record);
|
|
631
|
+
}
|
|
632
|
+
ensureDriver(record, readOnly = false) {
|
|
633
|
+
this.assertLive();
|
|
634
|
+
if (record.driver)
|
|
635
|
+
return Promise.resolve(record.driver);
|
|
636
|
+
if (!record.initializing) {
|
|
637
|
+
const signal = readOnly && !active(record.view) ? new AbortController().signal : record.startup.signal;
|
|
638
|
+
let diagnosticDriver;
|
|
639
|
+
const creation = Promise.resolve()
|
|
640
|
+
.then(async () => {
|
|
641
|
+
// Inspection and delivery can initialize a reserved child before start().
|
|
642
|
+
const contextReady = this.prepareInheritedContext(record, readOnly);
|
|
643
|
+
if (contextReady)
|
|
644
|
+
await abortable(contextReady, signal);
|
|
645
|
+
if (!record.view.sessionFile && record.view.parent && record.view.parent !== "/root") {
|
|
646
|
+
const parentRecord = this.record(record.view.parent);
|
|
647
|
+
if (!parentRecord.driver)
|
|
648
|
+
await this.ensureDriver(parentRecord, readOnly);
|
|
649
|
+
}
|
|
650
|
+
const parentSessionFile = this.lexicalParentSessionFile(record);
|
|
651
|
+
const segments = record.view.path.slice(1).split("/");
|
|
652
|
+
const level = segments.length + (segments[0] === "root" ? 0 : 1);
|
|
653
|
+
const canSpawnChildren = this.options.maxLevels === undefined && this.options.maxDepth !== undefined
|
|
654
|
+
? segments.length - 1 < this.options.maxDepth
|
|
655
|
+
: level < (this.options.maxLevels ?? DEFAULT_MANAGER_SETTINGS.maxLevels);
|
|
656
|
+
const options = {
|
|
657
|
+
path: record.view.path,
|
|
658
|
+
canSpawnChildren,
|
|
659
|
+
type: record.definition,
|
|
660
|
+
inherited: record.inherited,
|
|
661
|
+
inheritedContextEntries: record.inheritedContextEntries,
|
|
662
|
+
tools: this.options.toolsFor(record.view.path),
|
|
663
|
+
parentPath: record.view.parent,
|
|
664
|
+
sessionFile: record.view.sessionFile,
|
|
665
|
+
signal,
|
|
666
|
+
shouldPause: () => record.pauseRequested,
|
|
667
|
+
onEvent: (event) => {
|
|
668
|
+
if (event.kind === "diagnostic") {
|
|
669
|
+
if (this.disposed ||
|
|
670
|
+
this.records.get(record.view.path) !== record ||
|
|
671
|
+
(diagnosticDriver ? record.driver !== diagnosticDriver : signal.aborted))
|
|
672
|
+
return;
|
|
673
|
+
record.view.diagnostics = [
|
|
674
|
+
...(record.view.diagnostics ?? []),
|
|
675
|
+
event.diagnostic,
|
|
676
|
+
].slice(-20);
|
|
677
|
+
this.emit({
|
|
678
|
+
kind: "diagnostic",
|
|
679
|
+
thread: this.view(record),
|
|
680
|
+
diagnostic: event.diagnostic,
|
|
681
|
+
recipient: record.view.parent ?? record.view.owner,
|
|
682
|
+
});
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
if (event.kind === "settings") {
|
|
686
|
+
if (record.view.model !== event.model ||
|
|
687
|
+
record.view.thinkingLevel !== event.thinkingLevel) {
|
|
688
|
+
record.view.model = event.model;
|
|
689
|
+
record.view.thinkingLevel = event.thinkingLevel;
|
|
690
|
+
this.touch(record);
|
|
691
|
+
}
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
if (event.kind === "usage") {
|
|
695
|
+
this.applyUsage(record, event);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (event.kind === "checkpoint") {
|
|
699
|
+
this.touch(record);
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
if (active(record.view) && !record.pauseRequested) {
|
|
703
|
+
record.view.status = event.text;
|
|
704
|
+
this.touch(record);
|
|
705
|
+
this.recordActivity(record, event.detail ? `${event.text} ${event.detail}` : event.text);
|
|
706
|
+
}
|
|
707
|
+
},
|
|
708
|
+
...(parentSessionFile ? { parentSessionFile } : {}),
|
|
709
|
+
...(record.sessionLeafId !== undefined ? { sessionLeafId: record.sessionLeafId } : {}),
|
|
710
|
+
};
|
|
711
|
+
return this.options.createDriver(options);
|
|
712
|
+
})
|
|
713
|
+
.then(async (driver) => {
|
|
714
|
+
if (this.disposed || signal.aborted) {
|
|
715
|
+
await driver.abort();
|
|
716
|
+
await driver.dispose();
|
|
717
|
+
throw new Error("Driver startup cancelled");
|
|
718
|
+
}
|
|
719
|
+
record.driver = driver;
|
|
720
|
+
diagnosticDriver = driver;
|
|
721
|
+
record.driverGeneration = (record.driverGeneration ?? 0) + 1;
|
|
722
|
+
record.observationError = undefined;
|
|
723
|
+
if (record.transcriptListeners?.size)
|
|
724
|
+
this.attachTranscript(record, driver);
|
|
725
|
+
record.usageCursor = { input: 0, output: 0 };
|
|
726
|
+
record.liveInputTokens = 0;
|
|
727
|
+
record.liveOutputTokens = 0;
|
|
728
|
+
record.liveCostUsd = undefined;
|
|
729
|
+
record.view.sessionFile = driver.sessionFile;
|
|
730
|
+
if (driver.sessionLeafId !== undefined)
|
|
731
|
+
record.sessionLeafId = driver.sessionLeafId;
|
|
732
|
+
this.touch(record);
|
|
733
|
+
return driver;
|
|
734
|
+
});
|
|
735
|
+
let initializing;
|
|
736
|
+
initializing = abortable(creation, signal).catch((error) => {
|
|
737
|
+
if (record.initializing === initializing)
|
|
738
|
+
record.initializing = undefined;
|
|
739
|
+
throw error;
|
|
740
|
+
});
|
|
741
|
+
record.initializing = initializing;
|
|
742
|
+
}
|
|
743
|
+
return record.initializing;
|
|
744
|
+
}
|
|
745
|
+
attachTranscript(record, driver) {
|
|
746
|
+
if (record.detachTranscript || !record.transcriptListeners?.size)
|
|
747
|
+
return;
|
|
748
|
+
const observation = driver.observeTranscript?.((snapshot) => {
|
|
749
|
+
if (this.disposed || record.driver !== driver || !record.transcriptListeners?.size)
|
|
750
|
+
return;
|
|
751
|
+
record.transcriptSource = snapshot;
|
|
752
|
+
this.publishTranscript(record);
|
|
753
|
+
});
|
|
754
|
+
if (observation) {
|
|
755
|
+
record.transcriptSource = observation.snapshot;
|
|
756
|
+
record.detachTranscript = observation.unsubscribe;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
transcriptSnapshot(record) {
|
|
760
|
+
const source = record.transcriptSource;
|
|
761
|
+
return Object.freeze({
|
|
762
|
+
revision: record.observationRevision ?? 0,
|
|
763
|
+
generation: record.driverGeneration ?? 0,
|
|
764
|
+
messages: source?.messages ?? immutableTranscriptValue(record.driver?.snapshot() ?? record.inherited),
|
|
765
|
+
assistant: source?.assistant ?? null,
|
|
766
|
+
tools: source?.tools ?? Object.freeze([]),
|
|
767
|
+
inheritedCount: source?.inheritedCount ?? record.inherited.length,
|
|
768
|
+
thread: immutableTranscriptValue(this.view(record)),
|
|
769
|
+
...(record.observationError || source?.error
|
|
770
|
+
? { error: record.observationError ?? source?.error }
|
|
771
|
+
: {}),
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
publishTranscript(record) {
|
|
775
|
+
if (this.disposed || !record.transcriptListeners?.size)
|
|
776
|
+
return;
|
|
777
|
+
record.observationRevision = (record.observationRevision ?? 0) + 1;
|
|
778
|
+
const snapshot = this.transcriptSnapshot(record);
|
|
779
|
+
for (const listener of record.transcriptListeners) {
|
|
780
|
+
try {
|
|
781
|
+
listener(snapshot);
|
|
782
|
+
}
|
|
783
|
+
catch {
|
|
784
|
+
/* UI failure must not affect execution. */
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
/** Bounded activity context for the housekeeping summarizer; never affects lifecycle. */
|
|
789
|
+
recordActivity(record, line) {
|
|
790
|
+
const recent = (record.recentActivity ??= []);
|
|
791
|
+
recent.push(line.slice(0, 600));
|
|
792
|
+
if (recent.length > RECENT_ACTIVITY_LIMIT)
|
|
793
|
+
recent.splice(0, recent.length - RECENT_ACTIVITY_LIMIT);
|
|
794
|
+
if (!this.options.onActivity || this.disposed)
|
|
795
|
+
return;
|
|
796
|
+
try {
|
|
797
|
+
this.options.onActivity({
|
|
798
|
+
path: record.view.path,
|
|
799
|
+
type: record.view.type,
|
|
800
|
+
task: record.view.task,
|
|
801
|
+
run: record.runId ?? 0,
|
|
802
|
+
recent: [...recent],
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
catch {
|
|
806
|
+
/* Optional labs feature: never interrupt a runner. */
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
/** [labs] Apply a generated one-line summary; false when stale (run changed, settled, paused or gone). */
|
|
810
|
+
setSummary(path, run, summary) {
|
|
811
|
+
const record = this.records.get(path);
|
|
812
|
+
const text = summary.replace(/\s+/g, " ").trim();
|
|
813
|
+
if (this.disposed ||
|
|
814
|
+
!record ||
|
|
815
|
+
!text ||
|
|
816
|
+
record.runId !== run ||
|
|
817
|
+
!active(record.view) ||
|
|
818
|
+
record.pauseRequested ||
|
|
819
|
+
record.stopRequested)
|
|
820
|
+
return false;
|
|
821
|
+
if (record.view.summary === text)
|
|
822
|
+
return true;
|
|
823
|
+
record.view.summary = text;
|
|
824
|
+
// Display-only: a metrics event refreshes UI without rewriting persisted registry/cost state.
|
|
825
|
+
if (!this.disposed)
|
|
826
|
+
this.emit({ kind: "metrics", thread: this.view(record) });
|
|
827
|
+
return true;
|
|
828
|
+
}
|
|
829
|
+
/** [labs] Remove one run's summary (stale refresh failed/unavailable); no-op for other runs or none. */
|
|
830
|
+
clearSummary(path, run) {
|
|
831
|
+
const record = this.records.get(path);
|
|
832
|
+
if (this.disposed || !record || record.runId !== run || record.view.summary === undefined)
|
|
833
|
+
return false;
|
|
834
|
+
delete record.view.summary;
|
|
835
|
+
this.emit({ kind: "metrics", thread: this.view(record) });
|
|
836
|
+
return true;
|
|
837
|
+
}
|
|
838
|
+
/** Drop every generated summary (feature disabled or model changed). */
|
|
839
|
+
clearSummaries() {
|
|
840
|
+
for (const record of this.records.values()) {
|
|
841
|
+
if (record.view.summary === undefined)
|
|
842
|
+
continue;
|
|
843
|
+
delete record.view.summary;
|
|
844
|
+
if (!this.disposed)
|
|
845
|
+
this.emit({ kind: "metrics", thread: this.view(record) });
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
emit(event) {
|
|
849
|
+
try {
|
|
850
|
+
this.options.onEvent?.(event);
|
|
851
|
+
}
|
|
852
|
+
catch (error) {
|
|
853
|
+
// Widgets/persistence/delivery run on the runner's event path. An exception
|
|
854
|
+
// here must not orphan a prompt promise or reject detached settlement.
|
|
855
|
+
try {
|
|
856
|
+
if (this.options.onEventError)
|
|
857
|
+
this.options.onEventError(error, event);
|
|
858
|
+
else
|
|
859
|
+
console.warn(`Subagent ${event.kind} notification failed: ${errorText(error)}`);
|
|
860
|
+
}
|
|
861
|
+
catch {
|
|
862
|
+
/* A failing diagnostic sink must not turn a notification into a crash. */
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
touch(record) {
|
|
867
|
+
record.view.updatedAt = Date.now();
|
|
868
|
+
this.publishTranscript(record);
|
|
869
|
+
if (!this.disposed)
|
|
870
|
+
this.emit({ kind: "change", thread: this.view(record) });
|
|
871
|
+
}
|
|
872
|
+
/** Fold driver-cumulative usage into persisted totals. Partials only refresh the live view. */
|
|
873
|
+
applyUsage(record, event) {
|
|
874
|
+
const cursor = record.usageCursor ?? { input: 0, output: 0 };
|
|
875
|
+
const costUsd = event.costUsd !== undefined && Number.isFinite(event.costUsd) && event.costUsd >= 0
|
|
876
|
+
? Math.max(0, event.costUsd - (cursor.costUsd ?? 0))
|
|
877
|
+
: undefined;
|
|
878
|
+
if (event.partial) {
|
|
879
|
+
const input = Math.max(0, event.inputTokens - cursor.input);
|
|
880
|
+
const output = Math.max(0, event.outputTokens - cursor.output);
|
|
881
|
+
if (input === record.liveInputTokens &&
|
|
882
|
+
output === record.liveOutputTokens &&
|
|
883
|
+
costUsd === record.liveCostUsd)
|
|
884
|
+
return;
|
|
885
|
+
record.liveInputTokens = input;
|
|
886
|
+
record.liveOutputTokens = output;
|
|
887
|
+
record.liveCostUsd = costUsd;
|
|
888
|
+
if (!this.disposed)
|
|
889
|
+
this.emit({ kind: "metrics", thread: this.view(record) });
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
record.view.inputTokens =
|
|
893
|
+
(record.view.inputTokens ?? 0) + Math.max(0, event.inputTokens - cursor.input);
|
|
894
|
+
record.view.outputTokens =
|
|
895
|
+
(record.view.outputTokens ?? 0) + Math.max(0, event.outputTokens - cursor.output);
|
|
896
|
+
if (costUsd !== undefined)
|
|
897
|
+
record.view.costUsd = (record.view.costUsd ?? 0) + costUsd;
|
|
898
|
+
record.usageCursor = {
|
|
899
|
+
input: event.inputTokens,
|
|
900
|
+
output: event.outputTokens,
|
|
901
|
+
costUsd: event.costUsd ?? cursor.costUsd,
|
|
902
|
+
};
|
|
903
|
+
record.liveInputTokens = 0;
|
|
904
|
+
record.liveOutputTokens = 0;
|
|
905
|
+
record.liveCostUsd = undefined;
|
|
906
|
+
this.touch(record);
|
|
907
|
+
}
|
|
908
|
+
freezeElapsed(record) {
|
|
909
|
+
const startedAt = record.view.startedAt;
|
|
910
|
+
if (startedAt === undefined)
|
|
911
|
+
return;
|
|
912
|
+
record.view.elapsedMs = (record.view.elapsedMs ?? 0) + Math.max(0, Date.now() - startedAt);
|
|
913
|
+
delete record.view.startedAt;
|
|
914
|
+
}
|
|
915
|
+
prepareInheritedContext(record, readOnly = false) {
|
|
916
|
+
if (!record.contextPending)
|
|
917
|
+
return record.contextReady;
|
|
918
|
+
if (record.contextReady)
|
|
919
|
+
return record.contextReady;
|
|
920
|
+
if (!record.view.parent || record.view.parent === "/root") {
|
|
921
|
+
record.inherited = inheritContext(this.options.rootSnapshot());
|
|
922
|
+
record.inheritedContextEntries = structuredClone(this.options.rootContextEntries?.() ?? []);
|
|
923
|
+
record.contextPending = false;
|
|
924
|
+
return undefined;
|
|
925
|
+
}
|
|
926
|
+
const parentRecord = this.record(record.view.parent);
|
|
927
|
+
let ready;
|
|
928
|
+
ready = this.ensureDriver(parentRecord, readOnly)
|
|
929
|
+
.then((driver) => {
|
|
930
|
+
record.inherited = inheritContext(driver.snapshot());
|
|
931
|
+
record.inheritedContextEntries = structuredClone(driver.contextEntries?.() ?? []);
|
|
932
|
+
record.contextPending = false;
|
|
933
|
+
if (record.contextReady === ready)
|
|
934
|
+
record.contextReady = undefined;
|
|
935
|
+
this.touch(record);
|
|
936
|
+
})
|
|
937
|
+
.catch((error) => {
|
|
938
|
+
if (record.contextReady === ready)
|
|
939
|
+
record.contextReady = undefined;
|
|
940
|
+
throw error;
|
|
941
|
+
});
|
|
942
|
+
record.contextReady = ready;
|
|
943
|
+
void ready.catch(() => { });
|
|
944
|
+
return ready;
|
|
945
|
+
}
|
|
946
|
+
sessionLeafId(record) {
|
|
947
|
+
const leaf = record.driver?.sessionLeafId;
|
|
948
|
+
return leaf !== undefined ? leaf : record.sessionLeafId;
|
|
949
|
+
}
|
|
950
|
+
/** Live persisted file, else the saved file of a restored parent that has not been opened. */
|
|
951
|
+
lexicalParentSessionFile(record) {
|
|
952
|
+
const parent = record.view.parent;
|
|
953
|
+
if (!parent || parent === "/root")
|
|
954
|
+
return undefined;
|
|
955
|
+
const parentRecord = this.records.get(parent);
|
|
956
|
+
if (!parentRecord)
|
|
957
|
+
return undefined;
|
|
958
|
+
return parentRecord.driver?.sessionFile ?? parentRecord.view.sessionFile;
|
|
959
|
+
}
|
|
960
|
+
view(record) {
|
|
961
|
+
const view = structuredClone({
|
|
962
|
+
...record.view,
|
|
963
|
+
sessionFile: record.driver ? record.driver.sessionFile : record.view.sessionFile,
|
|
964
|
+
});
|
|
965
|
+
if (record.liveInputTokens)
|
|
966
|
+
view.inputTokens = (view.inputTokens ?? 0) + record.liveInputTokens;
|
|
967
|
+
if (record.liveOutputTokens)
|
|
968
|
+
view.outputTokens = (view.outputTokens ?? 0) + record.liveOutputTokens;
|
|
969
|
+
if (record.liveCostUsd !== undefined)
|
|
970
|
+
view.costUsd = (view.costUsd ?? 0) + record.liveCostUsd;
|
|
971
|
+
return view;
|
|
972
|
+
}
|
|
973
|
+
record(path) {
|
|
974
|
+
const record = this.records.get(path);
|
|
975
|
+
if (!record)
|
|
976
|
+
throw new Error(`Unknown thread ${path}`);
|
|
977
|
+
return record;
|
|
978
|
+
}
|
|
979
|
+
assertLive() {
|
|
980
|
+
if (this.disposed)
|
|
981
|
+
throw new Error("Thread manager has shut down");
|
|
982
|
+
}
|
|
983
|
+
assertCallerMaySteer(caller) {
|
|
984
|
+
if (caller !== "/root" && this.record(caller).stopRequested)
|
|
985
|
+
throw new Error("Stopping agents may not steer descendants");
|
|
986
|
+
}
|
|
987
|
+
assertStartableAncestors(path) {
|
|
988
|
+
for (let ancestor = parentPath(path); ancestor && ancestor !== "/root"; ancestor = parentPath(ancestor)) {
|
|
989
|
+
const record = this.record(ancestor);
|
|
990
|
+
if (record.stopRequested || record.view.state === "stopped") {
|
|
991
|
+
throw new Error(`Cannot continue under stopped ancestor ${ancestor}; resume it first`);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
assertCapacity() {
|
|
996
|
+
if ([...this.records.values()].filter((record) => active(record.view)).length >=
|
|
997
|
+
(this.options.maxConcurrent ?? DEFAULT_MANAGER_SETTINGS.maxConcurrent))
|
|
998
|
+
throw new Error("Concurrent thread limit reached; wait for a thread to settle");
|
|
999
|
+
}
|
|
1000
|
+
assertAccess(caller, path, self = false) {
|
|
1001
|
+
caller = canonicalPath(caller);
|
|
1002
|
+
if (caller === "/root" && path !== "/root")
|
|
1003
|
+
return;
|
|
1004
|
+
if (self && path === caller)
|
|
1005
|
+
return;
|
|
1006
|
+
if (!isDescendant(path, caller))
|
|
1007
|
+
throw new Error(`${caller} may address only its descendants (not siblings, unrelated trees or ancestors)`);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
//# sourceMappingURL=manager.js.map
|