@restranger/repi-subagents 0.0.0-stage → 0.0.1-ca9b82c
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/README.md +277 -2
- package/package.json +40 -5
- package/src/agent-file.ts +297 -0
- package/src/agent-schema.ts +90 -0
- package/src/child-guard.ts +151 -0
- package/src/command.ts +256 -0
- package/src/default-agents.ts +409 -0
- package/src/discovery.ts +354 -0
- package/src/extensions.ts +119 -0
- package/src/fleet-ui.ts +472 -0
- package/src/format.ts +974 -0
- package/src/frontmatter.ts +302 -0
- package/src/index.ts +112 -0
- package/src/manager.ts +1192 -0
- package/src/model-resolver.ts +58 -0
- package/src/overrides.ts +693 -0
- package/src/plugin.ts +568 -0
- package/src/prompt.ts +184 -0
- package/src/registry.ts +71 -0
- package/src/session.ts +304 -0
- package/src/status-widget.ts +65 -0
- package/src/tool-policy.ts +77 -0
- package/src/tools.ts +554 -0
- package/src/types.ts +163 -0
package/src/manager.ts
ADDED
|
@@ -0,0 +1,1192 @@
|
|
|
1
|
+
import type { PermissionService } from "@restranger/repi-lib";
|
|
2
|
+
import type { SubagentConfirmationRequest } from "./child-guard.js";
|
|
3
|
+
import type { ChildBuiltinExtension, ChildExtensionSources } from "./extensions.js";
|
|
4
|
+
import { resolveModel } from "./model-resolver.js";
|
|
5
|
+
import type { AgentRegistry } from "./registry.js";
|
|
6
|
+
import type { ChildSession, ChildSessionFactory } from "./session.js";
|
|
7
|
+
import { SUBAGENT_TOOL_NAMES, resolveToolAllowlist } from "./tool-policy.js";
|
|
8
|
+
import type {
|
|
9
|
+
AgentDefinition,
|
|
10
|
+
SpawnSubagentRequest,
|
|
11
|
+
SubagentActivity,
|
|
12
|
+
SubagentRunSnapshot,
|
|
13
|
+
SubagentRunStatus,
|
|
14
|
+
SubagentStep,
|
|
15
|
+
SubagentUsage,
|
|
16
|
+
} from "./types.js";
|
|
17
|
+
|
|
18
|
+
/** Retained tool steps per run; a long child would otherwise grow the snapshot without limit. */
|
|
19
|
+
const MAX_RECORDED_STEPS = 200;
|
|
20
|
+
/** Finished runs kept for status/wait lookups before the oldest are dropped. */
|
|
21
|
+
const MAX_FINISHED_RUNS = 200;
|
|
22
|
+
|
|
23
|
+
export class UnknownAgentError extends Error {
|
|
24
|
+
constructor(
|
|
25
|
+
readonly requested: string,
|
|
26
|
+
readonly available: readonly string[],
|
|
27
|
+
) {
|
|
28
|
+
super(
|
|
29
|
+
`Unknown agent "${requested}".${available.length > 0 ? ` Available: ${available.join(", ")}.` : " No declarative agents are installed."}`,
|
|
30
|
+
);
|
|
31
|
+
this.name = "UnknownAgentError";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface SubagentManagerOptions {
|
|
36
|
+
readonly createSession: ChildSessionFactory;
|
|
37
|
+
readonly agents: AgentRegistry;
|
|
38
|
+
readonly listParentTools: () => readonly string[];
|
|
39
|
+
/** Resolve the extensions that registered the child's requested tools. */
|
|
40
|
+
readonly resolveChildExtensions?: (tools: readonly string[] | undefined) => ChildExtensionSources | undefined;
|
|
41
|
+
readonly resolvePermission?: (sessionId: string) => PermissionService | undefined;
|
|
42
|
+
/** Parent-side approval for `ask` decisions raised by a child tool call. */
|
|
43
|
+
readonly requestPermission?: (request: SubagentConfirmationRequest) => Promise<boolean>;
|
|
44
|
+
readonly maxConcurrent?: number;
|
|
45
|
+
readonly now?: () => number;
|
|
46
|
+
readonly createId?: () => string;
|
|
47
|
+
readonly onChange?: (sessionId: string) => void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface MutableUsage {
|
|
51
|
+
input?: number;
|
|
52
|
+
output?: number;
|
|
53
|
+
total?: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface RunRecord {
|
|
57
|
+
readonly id: string;
|
|
58
|
+
readonly agent: AgentDefinition;
|
|
59
|
+
readonly agentName: string;
|
|
60
|
+
readonly task: string;
|
|
61
|
+
readonly description: string;
|
|
62
|
+
readonly parentSessionId: string;
|
|
63
|
+
readonly cwd: string;
|
|
64
|
+
readonly background: boolean;
|
|
65
|
+
readonly maxTurns?: number;
|
|
66
|
+
readonly tools?: readonly string[];
|
|
67
|
+
readonly extensionPaths?: readonly string[];
|
|
68
|
+
readonly builtinExtensions?: readonly ChildBuiltinExtension[];
|
|
69
|
+
readonly extensionLabels?: readonly string[];
|
|
70
|
+
readonly modelRuntime?: unknown;
|
|
71
|
+
readonly controller: AbortController;
|
|
72
|
+
readonly createdAt: number;
|
|
73
|
+
readonly settled: Promise<void>;
|
|
74
|
+
resolveSettled: () => void;
|
|
75
|
+
startedAt?: number;
|
|
76
|
+
finishedAt?: number;
|
|
77
|
+
/** Set once the parent has read the result; drives the prompt's "not collected" nudge. */
|
|
78
|
+
collected?: boolean;
|
|
79
|
+
status: SubagentRunStatus;
|
|
80
|
+
phase?: "running" | "compacting" | "auto-compacting";
|
|
81
|
+
result?: string;
|
|
82
|
+
error?: string;
|
|
83
|
+
turns: number;
|
|
84
|
+
toolCalls: number;
|
|
85
|
+
usage?: MutableUsage;
|
|
86
|
+
turnLimitReached?: boolean;
|
|
87
|
+
diagnostics: string[];
|
|
88
|
+
session?: ChildSession;
|
|
89
|
+
unsubscribe?: () => void;
|
|
90
|
+
streamingText: string;
|
|
91
|
+
lastAssistantText?: string;
|
|
92
|
+
providerError?: string;
|
|
93
|
+
/** Stop reason of the last assistant message, e.g. `stop`, `length` or `error`. */
|
|
94
|
+
stopReason?: string;
|
|
95
|
+
modelError?: string;
|
|
96
|
+
thinking?: string;
|
|
97
|
+
abortRequested: boolean;
|
|
98
|
+
parentSignalCleanup?: () => void;
|
|
99
|
+
activity?: SubagentActivity;
|
|
100
|
+
recentActivity: SubagentActivity[];
|
|
101
|
+
color?: string;
|
|
102
|
+
modelName?: string;
|
|
103
|
+
/** 1-based index of the current model attempt. */
|
|
104
|
+
attempt: number;
|
|
105
|
+
/** Total model candidates for this run. */
|
|
106
|
+
readonly attempts: number;
|
|
107
|
+
steps: SubagentStep[];
|
|
108
|
+
readonly candidateInputs: readonly (string | undefined)[];
|
|
109
|
+
readonly parentModel?: unknown;
|
|
110
|
+
readonly parentModelRegistry?: {
|
|
111
|
+
find(provider: string, modelId: string): unknown;
|
|
112
|
+
getAll(): readonly unknown[];
|
|
113
|
+
getAvailable?(): readonly unknown[];
|
|
114
|
+
};
|
|
115
|
+
/** Foreground progress sink; the plugin forwards it to the tool's `onUpdate`. */
|
|
116
|
+
onUpdate?: (snapshot: SubagentRunSnapshot) => void;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
interface QueuedRun {
|
|
120
|
+
readonly runId: string;
|
|
121
|
+
readonly start: () => Promise<void>;
|
|
122
|
+
readonly resolve: () => void;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Owns the run table, scheduling and the foreground/background contract.
|
|
127
|
+
*
|
|
128
|
+
* It knows nothing about Pi's UI or tool registration; the plugin passes a flat `onChange` callback
|
|
129
|
+
* so the widget stays a presentation concern and the manager stays testable with a fake child
|
|
130
|
+
* session factory.
|
|
131
|
+
*/
|
|
132
|
+
export class SubagentManager {
|
|
133
|
+
private readonly runs = new Map<string, RunRecord>();
|
|
134
|
+
private readonly queue: QueuedRun[] = [];
|
|
135
|
+
private maxConcurrent: number;
|
|
136
|
+
private readonly now: () => number;
|
|
137
|
+
private readonly nextId: () => string;
|
|
138
|
+
private active = 0;
|
|
139
|
+
private disposed = false;
|
|
140
|
+
|
|
141
|
+
constructor(private readonly options: SubagentManagerOptions) {
|
|
142
|
+
this.maxConcurrent = Math.max(1, options.maxConcurrent ?? 4);
|
|
143
|
+
this.now = options.now ?? (() => Date.now());
|
|
144
|
+
this.nextId = options.createId ?? createRunId;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
getMaxConcurrent(): number {
|
|
148
|
+
return this.maxConcurrent;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
setMaxConcurrent(maxConcurrent: number): void {
|
|
152
|
+
this.maxConcurrent = Math.max(1, Math.floor(maxConcurrent));
|
|
153
|
+
this.pump();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async spawn(request: SpawnSubagentRequest): Promise<SubagentRunSnapshot> {
|
|
157
|
+
if (this.disposed) {
|
|
158
|
+
throw new Error("Subagent manager is disposed.");
|
|
159
|
+
}
|
|
160
|
+
const agent = this.options.agents.get(request.agent);
|
|
161
|
+
if (!agent) {
|
|
162
|
+
throw new UnknownAgentError(
|
|
163
|
+
request.agent,
|
|
164
|
+
this.options.agents.list().map((entry) => entry.name),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
let resolveSettled: (() => void) | undefined;
|
|
170
|
+
const settled = new Promise<void>((resolve) => {
|
|
171
|
+
resolveSettled = resolve;
|
|
172
|
+
});
|
|
173
|
+
const diagnostics: string[] = [];
|
|
174
|
+
const parentTools = this.options.listParentTools();
|
|
175
|
+
const toolResolution = resolveToolAllowlist(agent, parentTools);
|
|
176
|
+
if (toolResolution.unavailable.length > 0) {
|
|
177
|
+
diagnostics.push(
|
|
178
|
+
`Agent "${agent.name}" requests tools the parent does not expose: ${toolResolution.unavailable.join(", ")}.`,
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const extensionResolution = toolResolution.tools
|
|
183
|
+
? safeResolveChildExtensions(this.options.resolveChildExtensions, toolResolution.tools)
|
|
184
|
+
: undefined;
|
|
185
|
+
if (extensionResolution) {
|
|
186
|
+
diagnostics.push(...extensionResolution.diagnostics);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const thinking = agent.thinking ?? request.parentThinkingLevel;
|
|
190
|
+
const modelInput = request.model ?? agent.model;
|
|
191
|
+
const fallbackInputs = request.fallbackModels ?? agent.fallbackModels ?? [];
|
|
192
|
+
const candidateInputs = dedupeCandidates([modelInput, ...fallbackInputs]);
|
|
193
|
+
|
|
194
|
+
let initialModelTarget = request.parentModel;
|
|
195
|
+
const firstCandidate = candidateInputs[0];
|
|
196
|
+
if (firstCandidate && !isInheritModel(firstCandidate)) {
|
|
197
|
+
const initialResolution = resolveModel(firstCandidate, request.parentModelRegistry);
|
|
198
|
+
initialModelTarget = initialResolution.model ?? firstCandidate;
|
|
199
|
+
}
|
|
200
|
+
const modelName = extractModelName(initialModelTarget);
|
|
201
|
+
|
|
202
|
+
const run: RunRecord = {
|
|
203
|
+
id: this.nextId(),
|
|
204
|
+
agent,
|
|
205
|
+
agentName: agent.name,
|
|
206
|
+
task: request.task,
|
|
207
|
+
description: request.description?.trim() || defaultDescription(request.task),
|
|
208
|
+
parentSessionId: request.parentSessionId,
|
|
209
|
+
cwd: request.cwd,
|
|
210
|
+
background: request.background ?? agent.background ?? false,
|
|
211
|
+
maxTurns: normalizeMaxTurns(request.maxTurns ?? agent.maxTurns),
|
|
212
|
+
controller,
|
|
213
|
+
createdAt: this.now(),
|
|
214
|
+
settled,
|
|
215
|
+
resolveSettled: () => resolveSettled?.(),
|
|
216
|
+
status: "queued",
|
|
217
|
+
turns: 0,
|
|
218
|
+
toolCalls: 0,
|
|
219
|
+
attempt: 1,
|
|
220
|
+
attempts: Math.max(1, candidateInputs.length),
|
|
221
|
+
diagnostics,
|
|
222
|
+
streamingText: "",
|
|
223
|
+
abortRequested: false,
|
|
224
|
+
recentActivity: [],
|
|
225
|
+
steps: [],
|
|
226
|
+
candidateInputs,
|
|
227
|
+
...(request.parentModel !== undefined ? { parentModel: request.parentModel } : {}),
|
|
228
|
+
...(request.parentModelRegistry ? { parentModelRegistry: request.parentModelRegistry } : {}),
|
|
229
|
+
...(agent.color ? { color: agent.color } : {}),
|
|
230
|
+
...(modelName ? { modelName } : {}),
|
|
231
|
+
...(toolResolution.tools ? { tools: toolResolution.tools } : {}),
|
|
232
|
+
...(extensionResolution?.paths.length ? { extensionPaths: extensionResolution.paths } : {}),
|
|
233
|
+
...(extensionResolution?.builtins.length ? { builtinExtensions: extensionResolution.builtins } : {}),
|
|
234
|
+
...(extensionResolution?.labels.length ? { extensionLabels: extensionResolution.labels } : {}),
|
|
235
|
+
...(request.parentModelRuntime !== undefined ? { modelRuntime: request.parentModelRuntime } : {}),
|
|
236
|
+
...(thinking ? { thinking } : {}),
|
|
237
|
+
...(request.onUpdate ? { onUpdate: request.onUpdate } : {}),
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
const parentSignal = request.signal;
|
|
241
|
+
if (parentSignal) {
|
|
242
|
+
if (parentSignal.aborted) {
|
|
243
|
+
run.abortRequested = true;
|
|
244
|
+
controller.abort();
|
|
245
|
+
} else {
|
|
246
|
+
const onAbort = (): void => {
|
|
247
|
+
// Take the run out of the queue as well: only setting the flag left a queued task
|
|
248
|
+
// that later started and could not be stopped (`/subagents stop` returned false).
|
|
249
|
+
if (!this.abort(run.id)) {
|
|
250
|
+
run.abortRequested = true;
|
|
251
|
+
controller.abort();
|
|
252
|
+
abortQuietly(run.session);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
parentSignal.addEventListener("abort", onAbort, { once: true });
|
|
256
|
+
run.parentSignalCleanup = () => parentSignal.removeEventListener("abort", onAbort);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
this.pruneFinished();
|
|
261
|
+
this.runs.set(run.id, run);
|
|
262
|
+
this.report(run);
|
|
263
|
+
|
|
264
|
+
if (run.background) {
|
|
265
|
+
void this.enqueue(run.id, () => this.execute(run));
|
|
266
|
+
return this.snapshot(run);
|
|
267
|
+
}
|
|
268
|
+
await this.enqueue(run.id, () => this.execute(run));
|
|
269
|
+
return this.snapshot(run);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
get(id: string, parentSessionId?: string): SubagentRunSnapshot | undefined {
|
|
273
|
+
const run = this.runs.get(id);
|
|
274
|
+
if (!run || (parentSessionId && run.parentSessionId !== parentSessionId)) {
|
|
275
|
+
return undefined;
|
|
276
|
+
}
|
|
277
|
+
return this.snapshot(run);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
list(parentSessionId?: string): SubagentRunSnapshot[] {
|
|
281
|
+
return [...this.runs.values()]
|
|
282
|
+
.filter((run) => !parentSessionId || run.parentSessionId === parentSessionId)
|
|
283
|
+
.sort((left, right) => left.createdAt - right.createdAt)
|
|
284
|
+
.map((run) => this.snapshot(run));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
activeCount(parentSessionId?: string): number {
|
|
288
|
+
return this.list(parentSessionId).filter((run) => run.status === "queued" || run.status === "running").length;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async wait(ids: readonly string[], timeoutMs = 120_000, signal?: AbortSignal): Promise<SubagentRunSnapshot[]> {
|
|
292
|
+
const targets = [...new Set(ids)]
|
|
293
|
+
.map((id) => this.runs.get(id))
|
|
294
|
+
.filter((run): run is RunRecord => run !== undefined);
|
|
295
|
+
if (targets.length === 0) {
|
|
296
|
+
return [];
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const pending = targets
|
|
300
|
+
.filter((run) => run.status === "queued" || run.status === "running")
|
|
301
|
+
.map((run) => run.settled);
|
|
302
|
+
if (pending.length > 0) {
|
|
303
|
+
await raceWithTimeout(
|
|
304
|
+
Promise.allSettled(pending).then(() => undefined),
|
|
305
|
+
timeoutMs,
|
|
306
|
+
signal,
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
// Whatever settled by now has just been handed to the caller, so the prompt section must
|
|
310
|
+
// stop listing it. Runs that timed out are still active and stay visible.
|
|
311
|
+
this.markCollected(
|
|
312
|
+
targets.filter((run) => run.status !== "queued" && run.status !== "running").map((run) => run.id),
|
|
313
|
+
);
|
|
314
|
+
return targets.map((run) => this.snapshot(run));
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Record that the parent has seen these runs' results.
|
|
319
|
+
*
|
|
320
|
+
* `formatActiveRunsPromptSection` keeps finished-but-uncollected runs in the prompt so a
|
|
321
|
+
* background verdict cannot scroll out of view; clearing the flag is what makes that reminder
|
|
322
|
+
* disappear. Active runs are skipped because they have no result to read yet.
|
|
323
|
+
*/
|
|
324
|
+
markCollected(ids: readonly string[]): void {
|
|
325
|
+
for (const id of ids) {
|
|
326
|
+
const run = this.runs.get(id);
|
|
327
|
+
if (!run || run.collected) {
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (run.status === "queued" || run.status === "running") {
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
run.collected = true;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
abort(id: string, parentSessionId?: string): boolean {
|
|
338
|
+
const run = this.runs.get(id);
|
|
339
|
+
if (!run || (parentSessionId && run.parentSessionId !== parentSessionId)) {
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
if (run.status === "completed" || run.status === "failed" || run.status === "aborted" || run.abortRequested) {
|
|
343
|
+
return false;
|
|
344
|
+
}
|
|
345
|
+
run.abortRequested = true;
|
|
346
|
+
run.controller.abort();
|
|
347
|
+
abortQuietly(run.session);
|
|
348
|
+
if (run.status === "queued") {
|
|
349
|
+
this.finish(run, "aborted", { error: "Aborted before the subagent started." });
|
|
350
|
+
// Release the caller waiting on the queue instead of leaving its promise pending.
|
|
351
|
+
this.dequeue(run.id);
|
|
352
|
+
}
|
|
353
|
+
return true;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
abortSession(parentSessionId: string): string[] {
|
|
357
|
+
const aborted: string[] = [];
|
|
358
|
+
for (const run of Array.from(this.runs.values())) {
|
|
359
|
+
if (run.parentSessionId === parentSessionId && this.abort(run.id, parentSessionId)) {
|
|
360
|
+
aborted.push(run.id);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return aborted;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
dispose(): void {
|
|
367
|
+
if (this.disposed) {
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
this.disposed = true;
|
|
371
|
+
for (const run of this.runs.values()) {
|
|
372
|
+
// One child whose temp directory cannot be removed (EBUSY on Windows, open log files) must
|
|
373
|
+
// not stop the remaining children from being unsubscribed and disposed.
|
|
374
|
+
try {
|
|
375
|
+
run.abortRequested = true;
|
|
376
|
+
run.controller.abort();
|
|
377
|
+
abortQuietly(run.session);
|
|
378
|
+
run.parentSignalCleanup?.();
|
|
379
|
+
run.unsubscribe?.();
|
|
380
|
+
run.session?.dispose();
|
|
381
|
+
run.session = undefined;
|
|
382
|
+
} catch {
|
|
383
|
+
// Keep releasing the rest of the table.
|
|
384
|
+
}
|
|
385
|
+
if (run.status === "queued" || run.status === "running") {
|
|
386
|
+
this.finish(run, "aborted", { error: "Subagent manager disposed." });
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
// Resolve queued spawns so a foreground tool call never hangs on shutdown.
|
|
390
|
+
for (const entry of this.queue.splice(0)) {
|
|
391
|
+
entry.resolve();
|
|
392
|
+
}
|
|
393
|
+
this.runs.clear();
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Runs a queued child.
|
|
398
|
+
*
|
|
399
|
+
* Everything is inside one root `try`: a rejection escaping a background `void this.enqueue(...)`
|
|
400
|
+
* is an unhandled rejection, which terminates the host process and leaves `run.settled` pending,
|
|
401
|
+
* so the run also stuck in the UI forever.
|
|
402
|
+
*/
|
|
403
|
+
private async execute(run: RunRecord): Promise<void> {
|
|
404
|
+
try {
|
|
405
|
+
await this.executeAttempts(run);
|
|
406
|
+
} catch (err) {
|
|
407
|
+
if (run.status === "queued" || run.status === "running") {
|
|
408
|
+
this.finish(run, "failed", { error: errorMessage(err) });
|
|
409
|
+
}
|
|
410
|
+
} finally {
|
|
411
|
+
try {
|
|
412
|
+
run.unsubscribe?.();
|
|
413
|
+
run.unsubscribe = undefined;
|
|
414
|
+
run.session?.dispose();
|
|
415
|
+
run.session = undefined;
|
|
416
|
+
} catch {
|
|
417
|
+
// Disposal is best-effort; the run outcome is already decided.
|
|
418
|
+
}
|
|
419
|
+
if (run.status === "queued" || run.status === "running") {
|
|
420
|
+
this.finish(run, "failed", { error: "Subagent run ended without a result." });
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
private async executeAttempts(run: RunRecord): Promise<void> {
|
|
426
|
+
if (run.status !== "queued") {
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (run.controller.signal.aborted) {
|
|
430
|
+
this.finish(run, "aborted", { error: "Aborted before the subagent started." });
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
run.status = "running";
|
|
435
|
+
run.startedAt = this.now();
|
|
436
|
+
this.report(run);
|
|
437
|
+
|
|
438
|
+
const candidates = run.candidateInputs.length > 0 ? run.candidateInputs : [undefined];
|
|
439
|
+
let lastError: unknown;
|
|
440
|
+
|
|
441
|
+
for (let index = 0; index < candidates.length; index++) {
|
|
442
|
+
if (run.abortRequested || run.controller.signal.aborted) {
|
|
443
|
+
this.finish(run, "aborted", { error: "Subagent run was aborted." });
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
this.resetAttemptState(run, index);
|
|
448
|
+
const candidateInput = candidates[index];
|
|
449
|
+
const isInherit = isInheritModel(candidateInput);
|
|
450
|
+
let resolvedModel: unknown;
|
|
451
|
+
|
|
452
|
+
if (!candidateInput || isInherit) {
|
|
453
|
+
resolvedModel = run.parentModel;
|
|
454
|
+
} else {
|
|
455
|
+
const resolution = resolveModel(candidateInput, run.parentModelRegistry);
|
|
456
|
+
if (resolution.error) {
|
|
457
|
+
const hasNext = index + 1 < candidates.length;
|
|
458
|
+
const diagnosticMsg = `Model resolution failed for "${candidateInput}": ${resolution.error}`;
|
|
459
|
+
run.diagnostics.push(diagnosticMsg);
|
|
460
|
+
if (hasNext) {
|
|
461
|
+
this.report(run);
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
this.finish(run, "failed", { error: resolution.error });
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
resolvedModel = resolution.model;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const currentModelName =
|
|
471
|
+
extractModelName(resolvedModel) ??
|
|
472
|
+
(candidateInput && !isInherit ? candidateInput : undefined) ??
|
|
473
|
+
(extractModelName(run.parentModel) || "parent model");
|
|
474
|
+
run.modelName = currentModelName;
|
|
475
|
+
this.report(run);
|
|
476
|
+
|
|
477
|
+
const hasNextCandidate = index + 1 < candidates.length;
|
|
478
|
+
|
|
479
|
+
try {
|
|
480
|
+
const permission = this.options.resolvePermission?.(run.parentSessionId);
|
|
481
|
+
const tools = run.tools;
|
|
482
|
+
let session: ChildSession;
|
|
483
|
+
try {
|
|
484
|
+
session = await this.options.createSession.create({
|
|
485
|
+
runId: run.id,
|
|
486
|
+
agent: run.agent,
|
|
487
|
+
cwd: run.cwd,
|
|
488
|
+
parentSessionId: run.parentSessionId,
|
|
489
|
+
...(permission ? { permission } : {}),
|
|
490
|
+
...(this.options.requestPermission ? { requestConfirmation: this.options.requestPermission } : {}),
|
|
491
|
+
...(tools ? { tools } : {}),
|
|
492
|
+
excludeTools: SUBAGENT_TOOL_NAMES,
|
|
493
|
+
...(run.extensionPaths ? { extensionPaths: run.extensionPaths } : {}),
|
|
494
|
+
...(run.builtinExtensions ? { builtinExtensions: run.builtinExtensions } : {}),
|
|
495
|
+
...(run.modelRuntime !== undefined ? { modelRuntime: run.modelRuntime } : {}),
|
|
496
|
+
...(resolvedModel !== undefined ? { model: resolvedModel } : {}),
|
|
497
|
+
...(run.thinking ? { thinking: run.thinking } : {}),
|
|
498
|
+
signal: run.controller.signal,
|
|
499
|
+
onDiagnostic: (message) => {
|
|
500
|
+
run.diagnostics.push(message);
|
|
501
|
+
this.report(run);
|
|
502
|
+
},
|
|
503
|
+
});
|
|
504
|
+
} catch (err) {
|
|
505
|
+
// A session-construction failure is not a model failure: burning the remaining
|
|
506
|
+
// candidates would hide the real cause behind "All model candidates failed".
|
|
507
|
+
if (run.abortRequested || run.controller.signal.aborted) {
|
|
508
|
+
this.finish(run, "aborted", { error: "Subagent run was aborted." });
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
this.finish(run, "failed", { error: `Could not start the child session: ${errorMessage(err)}` });
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
run.session = session;
|
|
515
|
+
run.unsubscribe = session.subscribe((event) => this.consumeEvent(run, event));
|
|
516
|
+
|
|
517
|
+
if (run.controller.signal.aborted) {
|
|
518
|
+
await session.abort();
|
|
519
|
+
this.finish(run, "aborted", { error: "Subagent run was aborted." });
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
await session.prompt(run.task);
|
|
523
|
+
|
|
524
|
+
if (run.providerError && !run.turnLimitReached) {
|
|
525
|
+
throw new Error(run.providerError);
|
|
526
|
+
}
|
|
527
|
+
let result = (run.lastAssistantText ?? run.streamingText).trim();
|
|
528
|
+
if (!result) {
|
|
529
|
+
result = session.getLastAssistantText?.()?.trim() ?? "";
|
|
530
|
+
}
|
|
531
|
+
if (!result) {
|
|
532
|
+
result = extractLastAssistantText(session.messages);
|
|
533
|
+
}
|
|
534
|
+
if (result) {
|
|
535
|
+
run.result = result;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
if (run.turnLimitReached) {
|
|
539
|
+
const note = `Turn limit of ${run.maxTurns} reached before the subagent produced a final answer.`;
|
|
540
|
+
run.result = run.result ? `${run.result}\n\n[${note}]` : note;
|
|
541
|
+
// A truncated answer is not a successful deliverable: the parent must see a
|
|
542
|
+
// failure instead of treating the partial report as final.
|
|
543
|
+
this.finish(run, "failed", { error: note });
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
if (run.stopReason === "length") {
|
|
547
|
+
const note = "The model stopped at its length limit; the answer is truncated.";
|
|
548
|
+
run.result = run.result ? `${run.result}\n\n[${note}]` : note;
|
|
549
|
+
this.finish(run, "failed", { error: note });
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
if (!run.result) {
|
|
553
|
+
throw new Error("Subagent finished without a final text response.");
|
|
554
|
+
}
|
|
555
|
+
this.finish(run, "completed");
|
|
556
|
+
return;
|
|
557
|
+
} catch (err) {
|
|
558
|
+
lastError = err;
|
|
559
|
+
if (run.turnLimitReached) {
|
|
560
|
+
const note = `Turn limit of ${run.maxTurns} reached before the subagent produced a final answer.`;
|
|
561
|
+
run.result ??= note;
|
|
562
|
+
this.finish(run, "failed", { error: note });
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
if (run.abortRequested || run.controller.signal.aborted) {
|
|
566
|
+
this.finish(run, "aborted", { error: "Subagent run was aborted." });
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
if (hasNextCandidate) {
|
|
570
|
+
const nextCandidate = candidates[index + 1];
|
|
571
|
+
const nextLabel = !nextCandidate || isInheritModel(nextCandidate) ? "parent model" : nextCandidate;
|
|
572
|
+
run.diagnostics.push(
|
|
573
|
+
`Model "${currentModelName}" failed: ${errorMessage(err)}. Falling back to "${nextLabel}"...`,
|
|
574
|
+
);
|
|
575
|
+
run.streamingText = "";
|
|
576
|
+
run.lastAssistantText = undefined;
|
|
577
|
+
run.providerError = undefined;
|
|
578
|
+
this.report(run);
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
this.finish(run, "failed", { error: errorMessage(err) });
|
|
582
|
+
return;
|
|
583
|
+
} finally {
|
|
584
|
+
run.unsubscribe?.();
|
|
585
|
+
run.unsubscribe = undefined;
|
|
586
|
+
run.session?.dispose();
|
|
587
|
+
run.session = undefined;
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (run.status === "running") {
|
|
592
|
+
this.finish(run, "failed", { error: errorMessage(lastError ?? "All model candidates failed.") });
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Start a model attempt with a clean display/limit state.
|
|
598
|
+
*
|
|
599
|
+
* `maxTurns`, the widget and the run snapshot all describe one attempt; leaving the previous
|
|
600
|
+
* attempt's counters in place made a fallback model inherit a spent turn budget and mixed two
|
|
601
|
+
* different runs in one step list. Usage is intentionally cumulative: the tokens were spent.
|
|
602
|
+
*/
|
|
603
|
+
private resetAttemptState(run: RunRecord, index: number): void {
|
|
604
|
+
run.attempt = index + 1;
|
|
605
|
+
run.turns = 0;
|
|
606
|
+
run.toolCalls = 0;
|
|
607
|
+
run.steps = [];
|
|
608
|
+
run.recentActivity = [];
|
|
609
|
+
run.activity = undefined;
|
|
610
|
+
run.phase = undefined;
|
|
611
|
+
run.turnLimitReached = undefined;
|
|
612
|
+
run.streamingText = "";
|
|
613
|
+
run.lastAssistantText = undefined;
|
|
614
|
+
run.providerError = undefined;
|
|
615
|
+
run.stopReason = undefined;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** Drop the oldest finished runs so a long session keeps a bounded run table. */
|
|
619
|
+
private pruneFinished(): void {
|
|
620
|
+
const finished = [...this.runs.values()].filter(
|
|
621
|
+
(entry) => entry.status === "completed" || entry.status === "failed" || entry.status === "aborted",
|
|
622
|
+
);
|
|
623
|
+
if (finished.length <= MAX_FINISHED_RUNS) {
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
finished.sort((left, right) => left.createdAt - right.createdAt);
|
|
627
|
+
for (const entry of finished.slice(0, finished.length - MAX_FINISHED_RUNS)) {
|
|
628
|
+
this.runs.delete(entry.id);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
private consumeEvent(run: RunRecord, event: unknown): void {
|
|
633
|
+
if (!isRecord(event)) {
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
const type = event.type;
|
|
637
|
+
if (type === "message_start") {
|
|
638
|
+
if (isAssistantMessage(event.message)) {
|
|
639
|
+
run.streamingText = "";
|
|
640
|
+
run.activity = { tool: "thinking", at: this.now() };
|
|
641
|
+
this.report(run);
|
|
642
|
+
}
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
if (type === "message_update") {
|
|
646
|
+
const delta = readTextDelta(event);
|
|
647
|
+
if (delta) {
|
|
648
|
+
run.streamingText += delta;
|
|
649
|
+
}
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
if (type === "tool_execution_start") {
|
|
653
|
+
const tool = stringValue(event.toolName);
|
|
654
|
+
if (tool) {
|
|
655
|
+
const detail = describeToolInput(tool, event.args);
|
|
656
|
+
const activity: SubagentActivity = {
|
|
657
|
+
tool,
|
|
658
|
+
...(detail ? { detail } : {}),
|
|
659
|
+
at: this.now(),
|
|
660
|
+
};
|
|
661
|
+
run.activity = activity;
|
|
662
|
+
run.recentActivity.push(activity);
|
|
663
|
+
if (run.recentActivity.length > 6) {
|
|
664
|
+
run.recentActivity.shift();
|
|
665
|
+
}
|
|
666
|
+
const stepId = stringValue(event.toolCallId) ?? `step-${run.steps.length + 1}`;
|
|
667
|
+
run.steps.push({
|
|
668
|
+
id: stepId,
|
|
669
|
+
tool,
|
|
670
|
+
...(detail ? { detail } : {}),
|
|
671
|
+
startedAt: this.now(),
|
|
672
|
+
});
|
|
673
|
+
if (run.steps.length > MAX_RECORDED_STEPS) {
|
|
674
|
+
run.steps.splice(0, run.steps.length - MAX_RECORDED_STEPS);
|
|
675
|
+
}
|
|
676
|
+
this.report(run);
|
|
677
|
+
}
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
if (type === "tool_execution_end") {
|
|
681
|
+
if (run.activity) {
|
|
682
|
+
run.activity = {
|
|
683
|
+
...run.activity,
|
|
684
|
+
...(event.isError === true ? { error: true } : {}),
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
// Match by tool call id: a child may run several tools in one turn, and a single
|
|
688
|
+
// `currentStep` field attached every completion to the last started step.
|
|
689
|
+
const callId = stringValue(event.toolCallId);
|
|
690
|
+
const index = this.pendingStepIndex(run, callId);
|
|
691
|
+
const pending = index === -1 ? undefined : run.steps[index];
|
|
692
|
+
if (pending) {
|
|
693
|
+
const finishedAt = this.now();
|
|
694
|
+
run.steps[index] = {
|
|
695
|
+
...pending,
|
|
696
|
+
finishedAt,
|
|
697
|
+
durationMs: Math.max(0, finishedAt - pending.startedAt),
|
|
698
|
+
...(event.isError === true ? { isError: true } : {}),
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
this.report(run);
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
if (type === "message_end") {
|
|
705
|
+
const message = event.message;
|
|
706
|
+
if (!isAssistantMessage(message)) {
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
const text = extractMessageText(message) || run.streamingText;
|
|
710
|
+
if (text.trim()) {
|
|
711
|
+
run.lastAssistantText = text;
|
|
712
|
+
}
|
|
713
|
+
run.streamingText = "";
|
|
714
|
+
const stopReason = stringValue(message.stopReason);
|
|
715
|
+
run.stopReason = stopReason;
|
|
716
|
+
if (stopReason === "error") {
|
|
717
|
+
run.providerError = stringValue(message.errorMessage) ?? "Provider error";
|
|
718
|
+
} else {
|
|
719
|
+
// Pi retries a 429/503 automatically. Keeping the first error marked a recovered run as
|
|
720
|
+
// failed and threw away the answer the retry had produced.
|
|
721
|
+
run.providerError = undefined;
|
|
722
|
+
}
|
|
723
|
+
const usage = readUsage(message);
|
|
724
|
+
if (usage) {
|
|
725
|
+
run.usage = mergeUsage(run.usage, usage);
|
|
726
|
+
}
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (type === "turn_end") {
|
|
730
|
+
run.turns++;
|
|
731
|
+
const toolResults = Array.isArray(event.toolResults) ? event.toolResults.length : 0;
|
|
732
|
+
run.toolCalls += toolResults;
|
|
733
|
+
if (run.maxTurns !== undefined && run.turns >= run.maxTurns && toolResults > 0) {
|
|
734
|
+
run.turnLimitReached = true;
|
|
735
|
+
abortQuietly(run.session);
|
|
736
|
+
}
|
|
737
|
+
this.report(run);
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
if (type === "auto_retry_start" || type === "retry_start") {
|
|
741
|
+
run.providerError = undefined;
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
if (type === "compaction_start") {
|
|
745
|
+
const reason = stringValue(event.reason);
|
|
746
|
+
const isAuto = reason === "overflow" || reason === "threshold";
|
|
747
|
+
const phase = isAuto ? "auto-compacting" : "compacting";
|
|
748
|
+
run.phase = phase;
|
|
749
|
+
const detail = reason === "overflow" ? "context overflow" : "context";
|
|
750
|
+
const activity: SubagentActivity = {
|
|
751
|
+
tool: phase,
|
|
752
|
+
detail,
|
|
753
|
+
at: this.now(),
|
|
754
|
+
};
|
|
755
|
+
run.activity = activity;
|
|
756
|
+
run.recentActivity.push(activity);
|
|
757
|
+
if (run.recentActivity.length > 6) {
|
|
758
|
+
run.recentActivity.shift();
|
|
759
|
+
}
|
|
760
|
+
this.report(run);
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
if (type === "compaction_end") {
|
|
764
|
+
const wasCompacting = run.phase === "compacting" || run.phase === "auto-compacting";
|
|
765
|
+
const phaseTool = run.phase ?? "compacting";
|
|
766
|
+
run.phase = undefined;
|
|
767
|
+
const finishedAt = this.now();
|
|
768
|
+
const startedAt = run.activity?.at ?? finishedAt;
|
|
769
|
+
const durationMs = Math.max(0, finishedAt - startedAt);
|
|
770
|
+
const isError = Boolean(event.errorMessage) || event.aborted === true;
|
|
771
|
+
if (wasCompacting) {
|
|
772
|
+
run.steps.push({
|
|
773
|
+
id: `compact-${run.steps.length + 1}`,
|
|
774
|
+
tool: phaseTool,
|
|
775
|
+
detail: event.aborted ? "cancelled" : isError ? "failed" : "context",
|
|
776
|
+
startedAt,
|
|
777
|
+
finishedAt,
|
|
778
|
+
durationMs,
|
|
779
|
+
...(isError ? { isError: true } : {}),
|
|
780
|
+
});
|
|
781
|
+
if (run.steps.length > MAX_RECORDED_STEPS) {
|
|
782
|
+
run.steps.splice(0, run.steps.length - MAX_RECORDED_STEPS);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
if (run.activity?.tool === "compacting" || run.activity?.tool === "auto-compacting") {
|
|
786
|
+
run.activity = { tool: "thinking", at: this.now() };
|
|
787
|
+
}
|
|
788
|
+
this.report(run);
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/** Index of the step this completion closes: by call id when the host reports one, else the newest open step. */
|
|
794
|
+
private pendingStepIndex(run: RunRecord, callId: string | undefined): number {
|
|
795
|
+
if (callId) {
|
|
796
|
+
return run.steps.findIndex((step) => step.id === callId && step.finishedAt === undefined);
|
|
797
|
+
}
|
|
798
|
+
for (let index = run.steps.length - 1; index >= 0; index--) {
|
|
799
|
+
if (run.steps[index]?.finishedAt === undefined) {
|
|
800
|
+
return index;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return -1;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
private finish(
|
|
807
|
+
run: RunRecord,
|
|
808
|
+
status: Extract<SubagentRunStatus, "completed" | "failed" | "aborted">,
|
|
809
|
+
options: { result?: string; error?: string } = {},
|
|
810
|
+
): void {
|
|
811
|
+
if (run.status === "completed" || run.status === "failed" || run.status === "aborted") {
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
run.status = status;
|
|
815
|
+
run.finishedAt = this.now();
|
|
816
|
+
if (options.result !== undefined) {
|
|
817
|
+
run.result = options.result;
|
|
818
|
+
}
|
|
819
|
+
if (options.error !== undefined) {
|
|
820
|
+
run.error = options.error;
|
|
821
|
+
}
|
|
822
|
+
run.parentSignalCleanup?.();
|
|
823
|
+
run.parentSignalCleanup = undefined;
|
|
824
|
+
run.resolveSettled();
|
|
825
|
+
this.report(run);
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
private snapshot(run: RunRecord): SubagentRunSnapshot {
|
|
829
|
+
return {
|
|
830
|
+
id: run.id,
|
|
831
|
+
agent: run.agentName,
|
|
832
|
+
description: run.description,
|
|
833
|
+
task: run.task,
|
|
834
|
+
parentSessionId: run.parentSessionId,
|
|
835
|
+
cwd: run.cwd,
|
|
836
|
+
status: run.status,
|
|
837
|
+
...(run.phase ? { phase: run.phase } : {}),
|
|
838
|
+
background: run.background,
|
|
839
|
+
createdAt: run.createdAt,
|
|
840
|
+
...(run.startedAt !== undefined ? { startedAt: run.startedAt } : {}),
|
|
841
|
+
...(run.finishedAt !== undefined ? { finishedAt: run.finishedAt } : {}),
|
|
842
|
+
...(run.collected ? { collected: true } : {}),
|
|
843
|
+
...(run.result !== undefined ? { result: run.result } : {}),
|
|
844
|
+
...(run.error !== undefined ? { error: run.error } : {}),
|
|
845
|
+
turns: run.turns,
|
|
846
|
+
toolCalls: run.toolCalls,
|
|
847
|
+
...(run.usage ? { usage: run.usage } : {}),
|
|
848
|
+
...(run.maxTurns !== undefined ? { maxTurns: run.maxTurns } : {}),
|
|
849
|
+
...(run.color ? { color: run.color } : {}),
|
|
850
|
+
...(run.modelName ? { model: run.modelName } : {}),
|
|
851
|
+
...{ attempt: run.attempt, attempts: run.attempts },
|
|
852
|
+
...(run.turnLimitReached ? { turnLimitReached: true } : {}),
|
|
853
|
+
...(run.diagnostics.length > 0 ? { diagnostics: [...run.diagnostics] } : {}),
|
|
854
|
+
...(run.activity ? { activity: run.activity } : {}),
|
|
855
|
+
...(run.recentActivity.length > 0 ? { recentActivity: [...run.recentActivity] } : {}),
|
|
856
|
+
...(run.steps.length > 0 ? { steps: [...run.steps] } : {}),
|
|
857
|
+
...(run.extensionLabels ? { extensions: [...run.extensionLabels] } : {}),
|
|
858
|
+
...(run.stopReason !== undefined ? { stopReason: run.stopReason } : {}),
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
private enqueue(runId: string, task: () => Promise<void>): Promise<void> {
|
|
863
|
+
if (this.active < this.maxConcurrent) {
|
|
864
|
+
this.active++;
|
|
865
|
+
return Promise.resolve()
|
|
866
|
+
.then(task)
|
|
867
|
+
.finally(() => {
|
|
868
|
+
this.active--;
|
|
869
|
+
this.pump();
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
return new Promise<void>((resolve) => {
|
|
873
|
+
this.queue.push({
|
|
874
|
+
runId,
|
|
875
|
+
resolve,
|
|
876
|
+
start: async () => {
|
|
877
|
+
try {
|
|
878
|
+
await task();
|
|
879
|
+
} finally {
|
|
880
|
+
resolve();
|
|
881
|
+
}
|
|
882
|
+
},
|
|
883
|
+
});
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/** Drop a queued run and release whoever is awaiting its turn. */
|
|
888
|
+
private dequeue(runId: string): boolean {
|
|
889
|
+
const index = this.queue.findIndex((entry) => entry.runId === runId);
|
|
890
|
+
if (index < 0) {
|
|
891
|
+
return false;
|
|
892
|
+
}
|
|
893
|
+
const [entry] = this.queue.splice(index, 1);
|
|
894
|
+
entry?.resolve();
|
|
895
|
+
return true;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
private pump(): void {
|
|
899
|
+
while (this.active < this.maxConcurrent && this.queue.length > 0) {
|
|
900
|
+
const next = this.queue.shift();
|
|
901
|
+
if (!next) {
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
this.active++;
|
|
905
|
+
void next.start().finally(() => {
|
|
906
|
+
this.active--;
|
|
907
|
+
this.pump();
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
private notify(parentSessionId: string): void {
|
|
913
|
+
try {
|
|
914
|
+
this.options.onChange?.(parentSessionId);
|
|
915
|
+
} catch {
|
|
916
|
+
// UI failures must not break a run.
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/** Broadcast a run change to the session widget and, for foreground runs, the tool's stream. */
|
|
921
|
+
private report(run: RunRecord): void {
|
|
922
|
+
this.notify(run.parentSessionId);
|
|
923
|
+
if (!run.onUpdate) {
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
try {
|
|
927
|
+
run.onUpdate(this.snapshot(run));
|
|
928
|
+
} catch {
|
|
929
|
+
// A rejecting progress sink must not fail the run.
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function safeResolveChildExtensions(
|
|
935
|
+
resolver: SubagentManagerOptions["resolveChildExtensions"],
|
|
936
|
+
tools: readonly string[],
|
|
937
|
+
): ChildExtensionSources | undefined {
|
|
938
|
+
if (!resolver) {
|
|
939
|
+
return undefined;
|
|
940
|
+
}
|
|
941
|
+
try {
|
|
942
|
+
return resolver(tools);
|
|
943
|
+
} catch {
|
|
944
|
+
return undefined;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
const TOOL_ARGUMENT_KEYS = [
|
|
949
|
+
"command",
|
|
950
|
+
"path",
|
|
951
|
+
"file_path",
|
|
952
|
+
"pattern",
|
|
953
|
+
"query",
|
|
954
|
+
"url",
|
|
955
|
+
"prompt",
|
|
956
|
+
"description",
|
|
957
|
+
"glob",
|
|
958
|
+
] as const;
|
|
959
|
+
|
|
960
|
+
function describeToolInput(tool: string, input: unknown): string | undefined {
|
|
961
|
+
if (!isRecord(input)) {
|
|
962
|
+
return undefined;
|
|
963
|
+
}
|
|
964
|
+
if (tool === "grep" && typeof input.pattern === "string") {
|
|
965
|
+
const pattern = truncateText(input.pattern, 40);
|
|
966
|
+
const path = typeof input.path === "string" ? truncateText(input.path, 30) : undefined;
|
|
967
|
+
return path ? `"${pattern}" · ${path}` : `"${pattern}"`;
|
|
968
|
+
}
|
|
969
|
+
for (const key of TOOL_ARGUMENT_KEYS) {
|
|
970
|
+
const value = input[key];
|
|
971
|
+
if (typeof value === "string" && value.trim().length > 0) {
|
|
972
|
+
return truncateText(value.trim(), 70);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
return undefined;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
function truncateText(value: string, max: number): string {
|
|
979
|
+
const singleLine = value.replace(/\s+/g, " ");
|
|
980
|
+
return singleLine.length <= max ? singleLine : `${singleLine.slice(0, max - 1).trimEnd()}…`;
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
function abortQuietly(session: ChildSession | undefined): void {
|
|
984
|
+
try {
|
|
985
|
+
void Promise.resolve(session?.abort()).catch(() => undefined);
|
|
986
|
+
} catch {
|
|
987
|
+
// A host session that throws synchronously on abort must not break the manager.
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
function createRunId(): string {
|
|
992
|
+
return `sub-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
function defaultDescription(task: string): string {
|
|
996
|
+
const firstLine = task.trim().split("\n")[0]?.trim() ?? "subagent task";
|
|
997
|
+
return firstLine.length > 60 ? `${firstLine.slice(0, 59).trimEnd()}…` : firstLine;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
function normalizeMaxTurns(value: number | undefined): number | undefined {
|
|
1001
|
+
if (value === undefined || !Number.isFinite(value) || value <= 0) {
|
|
1002
|
+
return undefined;
|
|
1003
|
+
}
|
|
1004
|
+
return Math.max(2, Math.floor(value));
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
1008
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
function isAssistantMessage(value: unknown): value is Record<string, unknown> {
|
|
1012
|
+
return isRecord(value) && value.role === "assistant";
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function stringValue(value: unknown): string | undefined {
|
|
1016
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
function readTextDelta(event: Record<string, unknown>): string | undefined {
|
|
1020
|
+
const assistantEvent = isRecord(event.assistantMessageEvent) ? event.assistantMessageEvent : undefined;
|
|
1021
|
+
if (assistantEvent?.type === "text_delta" && typeof assistantEvent.delta === "string") {
|
|
1022
|
+
return assistantEvent.delta;
|
|
1023
|
+
}
|
|
1024
|
+
if (typeof event.delta === "string") {
|
|
1025
|
+
return event.delta;
|
|
1026
|
+
}
|
|
1027
|
+
return undefined;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
function extractMessageText(message: unknown): string {
|
|
1031
|
+
if (!isRecord(message)) {
|
|
1032
|
+
return "";
|
|
1033
|
+
}
|
|
1034
|
+
return extractContentText(message.content);
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
function extractContentText(content: unknown): string {
|
|
1038
|
+
if (typeof content === "string") {
|
|
1039
|
+
return content;
|
|
1040
|
+
}
|
|
1041
|
+
if (!Array.isArray(content)) {
|
|
1042
|
+
return "";
|
|
1043
|
+
}
|
|
1044
|
+
return content
|
|
1045
|
+
.map((part) => {
|
|
1046
|
+
if (typeof part === "string") {
|
|
1047
|
+
return part;
|
|
1048
|
+
}
|
|
1049
|
+
if (isRecord(part) && typeof part.text === "string") {
|
|
1050
|
+
return part.text;
|
|
1051
|
+
}
|
|
1052
|
+
return "";
|
|
1053
|
+
})
|
|
1054
|
+
.join("");
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
function extractLastAssistantText(messages: readonly unknown[] | undefined): string {
|
|
1058
|
+
if (!messages) {
|
|
1059
|
+
return "";
|
|
1060
|
+
}
|
|
1061
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
1062
|
+
const message = messages[index];
|
|
1063
|
+
if (!isAssistantMessage(message)) {
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
const text = extractMessageText(message).trim();
|
|
1067
|
+
if (text) {
|
|
1068
|
+
return text;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
return "";
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function readUsage(message: Record<string, unknown>): SubagentUsage | undefined {
|
|
1075
|
+
const usage = isRecord(message.usage) ? message.usage : undefined;
|
|
1076
|
+
if (!usage) {
|
|
1077
|
+
return undefined;
|
|
1078
|
+
}
|
|
1079
|
+
const input = numberValue(usage.input ?? usage.inputTokens ?? usage.promptTokens);
|
|
1080
|
+
const output = numberValue(usage.output ?? usage.outputTokens ?? usage.completionTokens);
|
|
1081
|
+
const total =
|
|
1082
|
+
numberValue(usage.total ?? usage.totalTokens) ??
|
|
1083
|
+
(input !== undefined || output !== undefined ? (input ?? 0) + (output ?? 0) : undefined);
|
|
1084
|
+
if (input === undefined && output === undefined && total === undefined) {
|
|
1085
|
+
return undefined;
|
|
1086
|
+
}
|
|
1087
|
+
return {
|
|
1088
|
+
...(input !== undefined ? { input } : {}),
|
|
1089
|
+
...(output !== undefined ? { output } : {}),
|
|
1090
|
+
...(total !== undefined ? { total } : {}),
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
function mergeUsage(previous: MutableUsage | undefined, next: SubagentUsage): MutableUsage {
|
|
1095
|
+
return {
|
|
1096
|
+
...(previous?.input !== undefined || next.input !== undefined
|
|
1097
|
+
? { input: (previous?.input ?? 0) + (next.input ?? 0) }
|
|
1098
|
+
: {}),
|
|
1099
|
+
...(previous?.output !== undefined || next.output !== undefined
|
|
1100
|
+
? { output: (previous?.output ?? 0) + (next.output ?? 0) }
|
|
1101
|
+
: {}),
|
|
1102
|
+
...(previous?.total !== undefined || next.total !== undefined
|
|
1103
|
+
? { total: (previous?.total ?? 0) + (next.total ?? 0) }
|
|
1104
|
+
: {}),
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function extractModelName(model: unknown): string | undefined {
|
|
1109
|
+
if (typeof model === "string" && model.trim()) {
|
|
1110
|
+
return model.trim();
|
|
1111
|
+
}
|
|
1112
|
+
if (isRecord(model)) {
|
|
1113
|
+
const id = stringValue(model.id);
|
|
1114
|
+
const provider = stringValue(model.provider);
|
|
1115
|
+
if (provider && id) {
|
|
1116
|
+
return `${provider}/${id}`;
|
|
1117
|
+
}
|
|
1118
|
+
if (id) {
|
|
1119
|
+
return id;
|
|
1120
|
+
}
|
|
1121
|
+
const name = stringValue(model.name);
|
|
1122
|
+
if (name) {
|
|
1123
|
+
return name;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
return undefined;
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
function numberValue(value: unknown): number | undefined {
|
|
1130
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
function errorMessage(error: unknown): string {
|
|
1134
|
+
return error instanceof Error ? error.message : String(error);
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
async function raceWithTimeout(promise: Promise<void>, timeoutMs: number, signal?: AbortSignal): Promise<void> {
|
|
1138
|
+
if (timeoutMs <= 0) {
|
|
1139
|
+
// `/subagent_wait { timeoutMs: 0 }` asks for the current state, not an unbounded wait.
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1143
|
+
let abortHandler: (() => void) | undefined;
|
|
1144
|
+
try {
|
|
1145
|
+
await Promise.race([
|
|
1146
|
+
promise,
|
|
1147
|
+
new Promise<void>((resolve) => {
|
|
1148
|
+
timer = setTimeout(resolve, timeoutMs);
|
|
1149
|
+
timer.unref?.();
|
|
1150
|
+
}),
|
|
1151
|
+
new Promise<void>((resolve) => {
|
|
1152
|
+
if (!signal) {
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
if (signal.aborted) {
|
|
1156
|
+
resolve();
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
abortHandler = resolve;
|
|
1160
|
+
signal.addEventListener("abort", abortHandler, { once: true });
|
|
1161
|
+
}),
|
|
1162
|
+
]);
|
|
1163
|
+
} finally {
|
|
1164
|
+
if (timer) {
|
|
1165
|
+
clearTimeout(timer);
|
|
1166
|
+
}
|
|
1167
|
+
if (signal && abortHandler) {
|
|
1168
|
+
signal.removeEventListener("abort", abortHandler);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
function isInheritModel(value: string | undefined): boolean {
|
|
1174
|
+
if (!value) {
|
|
1175
|
+
return true;
|
|
1176
|
+
}
|
|
1177
|
+
const normalized = value.trim().toLowerCase();
|
|
1178
|
+
return normalized === "inherit" || normalized === "default";
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
function dedupeCandidates(inputs: readonly (string | undefined)[]): (string | undefined)[] {
|
|
1182
|
+
const result: (string | undefined)[] = [];
|
|
1183
|
+
const seen = new Set<string>();
|
|
1184
|
+
for (const input of inputs) {
|
|
1185
|
+
const key = isInheritModel(input) ? "__inherit__" : (input?.trim().toLowerCase() ?? "__inherit__");
|
|
1186
|
+
if (!seen.has(key)) {
|
|
1187
|
+
seen.add(key);
|
|
1188
|
+
result.push(isInheritModel(input) ? undefined : input?.trim());
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
return result.length > 0 ? result : [undefined];
|
|
1192
|
+
}
|