killeros 1.4.8 → 1.5.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/subagents.ts CHANGED
@@ -1,1556 +1 @@
1
- import { spawn } from "node:child_process";
2
- import { closeSync, openSync, readSync, readdirSync, statSync } from "node:fs";
3
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { getSupportedThinkingLevels, StringEnum, type Model, type ModelThinkingLevel } from "@earendil-works/pi-ai";
8
- import {
9
- CONFIG_DIR_NAME,
10
- getAgentDir,
11
- getMarkdownTheme,
12
- parseFrontmatter,
13
- type ExtensionAPI,
14
- type ExtensionContext,
15
- } from "@earendil-works/pi-coding-agent";
16
- import { Container, Markdown, Spacer, Text } from "@earendil-works/pi-tui";
17
- import { Type } from "typebox";
18
- import { SubagentThreadRegistry, type SubagentThread, type SubagentThreadId, type SubagentThreadState } from "./subagent-lifecycle.ts";
19
- import { runSubagentProcess, type SubagentProcessHandle, type SubagentProcessResult } from "./subagent-process.ts";
20
- import { formatThreadBoard, formatThreadInspection, type ThreadRecord as ThreadBoardRecord } from "./subagent-ui.ts";
21
-
22
- export const SUBAGENT_LIMITS = {
23
- maxTasks: 10,
24
- maxReadConcurrency: 4,
25
- toolOutputBytes: 50 * 1024,
26
- traceRetentionBytes: 8 * 1024 * 1024,
27
- stderrRetentionBytes: 1 * 1024 * 1024,
28
- taskOutputRetentionBytes: 1 * 1024 * 1024,
29
- roleFileBytes: 64 * 1024,
30
- taskCharacters: 20_000,
31
- killGraceMs: 5_000,
32
- } as const;
33
-
34
- const WEB_TOOLS = new Set(["web_search", "source_check", "fetch_content", "get_search_content"]);
35
- const READ_TOOLS = new Set(["read", "grep", "find", "ls", ...WEB_TOOLS]);
36
- const WRITE_TOOLS = new Set(["bash", "edit", "write"]);
37
- const KNOWN_TOOLS = new Set([...READ_TOOLS, ...WRITE_TOOLS]);
38
- const SUBAGENT_WEB_EXTENSION = "npm:pi-web-access";
39
- const INHERIT_SETTING = "inherit";
40
- const MAX_RUNTIME_STEERING_MESSAGES = 20;
41
- const ROLE_FIELDS = new Set(["name", "description", "access", "tools", "model", "thinking", "timeoutMs"]);
42
-
43
- type ThinkingLevel = ModelThinkingLevel;
44
- export type AgentAccess = "read" | "write";
45
- export type AgentSource = "bundled" | "personal" | "project";
46
- export type AgentScope = "user" | "project" | "both";
47
- export type SubagentStatus = "queued" | "running" | "complete" | "failed" | "cancelled" | "limited";
48
-
49
- export interface AgentRole {
50
- name: string;
51
- description: string;
52
- access: AgentAccess;
53
- tools: string[];
54
- model?: string;
55
- thinking?: string;
56
- timeoutMs?: number;
57
- prompt: string;
58
- source: AgentSource;
59
- filePath: string;
60
- }
61
-
62
- export interface AgentDiscoveryResult {
63
- agents: AgentRole[];
64
- projectAgentsDir: string | null;
65
- }
66
-
67
- export interface SubagentUsage {
68
- input: number;
69
- output: number;
70
- cacheRead: number;
71
- cacheWrite: number;
72
- totalTokens: number;
73
- cost: {
74
- input: number;
75
- output: number;
76
- cacheRead: number;
77
- cacheWrite: number;
78
- total: number;
79
- };
80
- turns: number;
81
- }
82
-
83
- export interface SubagentTaskResult {
84
- id: string;
85
- agent: string;
86
- agentSource: AgentSource | "unknown";
87
- sourcePath?: string;
88
- task: string;
89
- access?: AgentAccess;
90
- status: SubagentStatus;
91
- model?: string;
92
- thinking?: ThinkingLevel;
93
- tools: string[];
94
- trace: string[];
95
- traceBytes: number;
96
- traceTruncatedBytes: number;
97
- stderr: string;
98
- stderrBytes: number;
99
- stderrTruncatedBytes: number;
100
- output: string;
101
- outputBytes: number;
102
- outputTruncatedBytes: number;
103
- toolCallCount: number;
104
- usage: SubagentUsage;
105
- durationMs: number;
106
- exitCode: number | null;
107
- terminationReason?: string;
108
- errorMessage?: string;
109
- step?: number;
110
- }
111
-
112
- export interface SubagentDetails {
113
- mode: "single" | "parallel" | "chain";
114
- agentScope: AgentScope;
115
- projectAgentsDir: string | null;
116
- executionNote?: string;
117
- results: SubagentTaskResult[];
118
- aggregateUsage: SubagentUsage;
119
- parentId?: string;
120
- threads?: SubagentThread[];
121
- activeThreads?: SubagentThread[];
122
- doneThreads?: SubagentThread[];
123
- selectedThreadId?: string;
124
- }
125
-
126
- interface ModelContext {
127
- model?: Model<any>;
128
- thinkingLevel?: ThinkingLevel;
129
- modelRegistry: {
130
- getAvailable(): Model<any>[];
131
- };
132
- }
133
-
134
- interface ResolvedModel {
135
- model: string;
136
- thinking: ThinkingLevel;
137
- definition: Model<any>;
138
- }
139
-
140
- interface SpawnedProcess {
141
- stdout: NodeJS.ReadableStream;
142
- stderr: NodeJS.ReadableStream;
143
- pid?: number;
144
- kill(signal?: NodeJS.Signals | number): boolean;
145
- on(event: "error", listener: (error: Error) => void): this;
146
- once(event: "close", listener: (code: number | null) => void): this;
147
- }
148
-
149
- type SubagentLimits = { [Key in keyof typeof SUBAGENT_LIMITS]: number } & {
150
- wallTimeMs?: number;
151
- jsonlLineBytes?: number;
152
- traceBytes?: number;
153
- stderrBytes?: number;
154
- taskOutputBytes?: number;
155
- quotaTokens?: number;
156
- quotaUsd?: number;
157
- };
158
-
159
- export interface SubagentRuntimeOptions {
160
- bundledAgentsDir?: string;
161
- userAgentsDir?: string;
162
- webExtension?: string;
163
- spawnProcess?: (args: string[], cwd: string, environment?: NodeJS.ProcessEnv) => SpawnedProcess;
164
- limits?: Partial<SubagentLimits>;
165
- }
166
-
167
- class AgentConfigurationError extends Error {
168
- constructor(filePath: string, field: string, message: string) {
169
- super(`${filePath} [${field}]: ${message}`);
170
- this.name = "AgentConfigurationError";
171
- }
172
- }
173
-
174
- function emptyUsage(): SubagentUsage {
175
- return {
176
- input: 0,
177
- output: 0,
178
- cacheRead: 0,
179
- cacheWrite: 0,
180
- totalTokens: 0,
181
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
182
- turns: 0,
183
- };
184
- }
185
-
186
- function addUsage(target: SubagentUsage, source: Partial<SubagentUsage> | undefined): void {
187
- if (!source) return;
188
- target.input += source.input ?? 0;
189
- target.output += source.output ?? 0;
190
- target.cacheRead += source.cacheRead ?? 0;
191
- target.cacheWrite += source.cacheWrite ?? 0;
192
- target.totalTokens += source.totalTokens ?? 0;
193
- target.cost.input += source.cost?.input ?? 0;
194
- target.cost.output += source.cost?.output ?? 0;
195
- target.cost.cacheRead += source.cost?.cacheRead ?? 0;
196
- target.cost.cacheWrite += source.cost?.cacheWrite ?? 0;
197
- target.cost.total += source.cost?.total ?? 0;
198
- target.turns += source.turns ?? 0;
199
- }
200
-
201
- function aggregateUsage(results: SubagentTaskResult[]): SubagentUsage {
202
- const total = emptyUsage();
203
- for (const result of results) addUsage(total, result.usage);
204
- return total;
205
- }
206
-
207
- function boundedText(text: string, maxBytes: number, marker: string): string {
208
- const capped = truncateUtf8(text, maxBytes);
209
- if (!capped.omittedBytes) return text;
210
- const markerBytes = Buffer.byteLength(marker, "utf8");
211
- if (markerBytes >= maxBytes) return truncateUtf8(text, maxBytes).text;
212
- return `${truncateUtf8(text, maxBytes - markerBytes).text}${marker}`;
213
- }
214
-
215
- function readBoundedFile(filePath: string, maxBytes: number): string {
216
- let descriptor: number | undefined;
217
- try {
218
- descriptor = openSync(filePath, "r");
219
- const buffer = Buffer.alloc(maxBytes + 1);
220
- const bytesRead = readSync(descriptor, buffer, 0, buffer.length, 0);
221
- if (bytesRead > maxBytes) throw new AgentConfigurationError(filePath, "file", `exceeds ${maxBytes} bytes`);
222
- return buffer.toString("utf8", 0, bytesRead);
223
- } finally {
224
- if (descriptor !== undefined) closeSync(descriptor);
225
- }
226
- }
227
-
228
- function requiredString(frontmatter: Record<string, unknown>, filePath: string, field: string): string {
229
- const value = frontmatter[field];
230
- if (typeof value !== "string" || !value.trim()) {
231
- throw new AgentConfigurationError(filePath, field, "must be a non-empty string");
232
- }
233
- return value.trim();
234
- }
235
-
236
- function optionalPositiveInteger(
237
- frontmatter: Record<string, unknown>,
238
- filePath: string,
239
- field: string,
240
- fallback?: number,
241
- maximum?: number,
242
- ): number | undefined {
243
- const value = frontmatter[field];
244
- if (value === undefined || value === "") return fallback;
245
- const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
246
- if (!Number.isInteger(parsed) || parsed <= 0 || maximum !== undefined && parsed > maximum) {
247
- const bound = maximum === undefined ? "" : " no greater than " + maximum;
248
- throw new AgentConfigurationError(filePath, field, `must be a positive integer${bound}`);
249
- }
250
- return parsed;
251
- }
252
-
253
- function parseAgentFile(filePath: string, source: AgentSource, limits: SubagentLimits): AgentRole {
254
- const content = readBoundedFile(filePath, limits.roleFileBytes);
255
- let parsed: { frontmatter: Record<string, unknown>; body: string };
256
- try {
257
- parsed = parseFrontmatter<Record<string, unknown>>(content);
258
- } catch (error) {
259
- throw new AgentConfigurationError(filePath, "frontmatter", error instanceof Error ? error.message : String(error));
260
- }
261
- const frontmatter = parsed.frontmatter;
262
- for (const field of Object.keys(frontmatter)) {
263
- if (!ROLE_FIELDS.has(field)) throw new AgentConfigurationError(filePath, field, "unknown role field");
264
- }
265
-
266
- const name = requiredString(frontmatter, filePath, "name");
267
- if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/u.test(name)) {
268
- throw new AgentConfigurationError(filePath, "name", "must use 1-64 letters, numbers, dots, underscores, or hyphens");
269
- }
270
- const description = requiredString(frontmatter, filePath, "description");
271
- if (description.length > 500) throw new AgentConfigurationError(filePath, "description", "must not exceed 500 characters");
272
-
273
- const accessValue = requiredString(frontmatter, filePath, "access");
274
- if (accessValue !== "read" && accessValue !== "write") {
275
- throw new AgentConfigurationError(filePath, "access", 'must be "read" or "write"');
276
- }
277
- const toolsValue = requiredString(frontmatter, filePath, "tools");
278
- const tools = [...new Set(toolsValue.split(",").map((tool) => tool.trim()).filter(Boolean))];
279
- if (tools.length === 0) throw new AgentConfigurationError(filePath, "tools", "must contain at least one tool");
280
- for (const tool of tools) {
281
- if (!KNOWN_TOOLS.has(tool)) throw new AgentConfigurationError(filePath, "tools", `unknown child tool ${JSON.stringify(tool)}`);
282
- if (accessValue === "read" && WRITE_TOOLS.has(tool)) {
283
- throw new AgentConfigurationError(filePath, "tools", `read-only roles cannot use ${tool}`);
284
- }
285
- }
286
-
287
- const prompt = parsed.body.trim();
288
- if (!prompt) throw new AgentConfigurationError(filePath, "prompt", "Markdown body must be non-empty");
289
- const modelValue = frontmatter.model;
290
- if (modelValue !== undefined && (typeof modelValue !== "string" || !modelValue.trim())) {
291
- throw new AgentConfigurationError(filePath, "model", "must be a non-empty string when provided");
292
- }
293
- const thinkingValue = frontmatter.thinking;
294
- if (thinkingValue !== undefined && (typeof thinkingValue !== "string" || !thinkingValue.trim())) {
295
- throw new AgentConfigurationError(filePath, "thinking", "must be a non-empty string when provided");
296
- }
297
-
298
- return {
299
- name,
300
- description,
301
- access: accessValue,
302
- tools,
303
- model: typeof modelValue === "string" ? modelValue.trim() : undefined,
304
- thinking: typeof thinkingValue === "string" ? thinkingValue.trim() : undefined,
305
- timeoutMs: optionalPositiveInteger(frontmatter, filePath, "timeoutMs"),
306
- prompt,
307
- source,
308
- filePath,
309
- };
310
- }
311
-
312
- function loadAgentDirectory(dir: string, source: AgentSource, limits: SubagentLimits): AgentRole[] {
313
- let entries;
314
- try {
315
- entries = readdirSync(dir, { withFileTypes: true });
316
- } catch (error) {
317
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
318
- throw new Error(`Could not read ${source} agent directory ${dir}: ${error instanceof Error ? error.message : String(error)}`);
319
- }
320
- const agents: AgentRole[] = [];
321
- const names = new Set<string>();
322
- for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
323
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
324
- const agent = parseAgentFile(path.join(dir, entry.name), source, limits);
325
- if (names.has(agent.name)) throw new AgentConfigurationError(agent.filePath, "name", `duplicate ${source} role ${JSON.stringify(agent.name)}`);
326
- names.add(agent.name);
327
- agents.push(agent);
328
- }
329
- return agents;
330
- }
331
-
332
- function isDirectory(candidate: string): boolean {
333
- try {
334
- return statSync(candidate).isDirectory();
335
- } catch {
336
- return false;
337
- }
338
- }
339
-
340
- function findProjectAgentsDir(cwd: string): string | null {
341
- let current = path.resolve(cwd);
342
- while (true) {
343
- const candidate = path.join(current, CONFIG_DIR_NAME, "agents");
344
- if (isDirectory(candidate)) return candidate;
345
- const parent = path.dirname(current);
346
- if (parent === current) return null;
347
- current = parent;
348
- }
349
- }
350
-
351
- export function discoverAgentRoles(
352
- cwd: string,
353
- scope: AgentScope,
354
- projectTrusted: boolean,
355
- options: Pick<SubagentRuntimeOptions, "bundledAgentsDir" | "userAgentsDir" | "limits"> = {},
356
- ): AgentDiscoveryResult {
357
- const limits = { ...SUBAGENT_LIMITS, ...options.limits };
358
- const bundledDir = options.bundledAgentsDir ?? fileURLToPath(new URL("./agents/", import.meta.url));
359
- const userDir = options.userAgentsDir ?? path.join(getAgentDir(), "agents");
360
- const wantsProject = scope === "project" || scope === "both";
361
- if (wantsProject && !projectTrusted) throw new Error("Project agents require a trusted project");
362
- const projectAgentsDir = wantsProject ? findProjectAgentsDir(cwd) : null;
363
-
364
- const layers: Array<{ dir: string; source: AgentSource }> = [{ dir: bundledDir, source: "bundled" }];
365
- if (scope === "user" || scope === "both") layers.push({ dir: userDir, source: "personal" });
366
- if (wantsProject && projectAgentsDir) layers.push({ dir: projectAgentsDir, source: "project" });
367
-
368
- const byName = new Map<string, AgentRole>();
369
- for (const layer of layers) {
370
- for (const agent of loadAgentDirectory(layer.dir, layer.source, limits)) byName.set(agent.name, agent);
371
- }
372
- return {
373
- agents: [...byName.values()].sort((left, right) => left.name.localeCompare(right.name)),
374
- projectAgentsDir,
375
- };
376
- }
377
-
378
- function matchingModels(value: string, available: Model<any>[]): Model<any>[] {
379
- const slash = value.indexOf("/");
380
- if (slash >= 1 && slash < value.length - 1) {
381
- const provider = value.slice(0, slash);
382
- const id = value.slice(slash + 1);
383
- return available.filter((model) => model.provider === provider && model.id === id);
384
- }
385
- return available.filter((model) => model.id === value);
386
- }
387
-
388
- function splitModelAndThinking(value: string, filePath: string, available: Model<any>[]): { model: string; thinking?: string } {
389
- if (matchingModels(value, available).length > 0) return { model: value };
390
- const colon = value.lastIndexOf(":");
391
- if (colon < 0) return { model: value };
392
- const model = value.slice(0, colon);
393
- if (!model) throw new AgentConfigurationError(filePath, "model", "model identifier is missing");
394
- if (matchingModels(model, available).length > 0) return { model, thinking: value.slice(colon + 1) };
395
- return { model: value };
396
- }
397
-
398
- function resolveAvailableModel(value: string, filePath: string, available: Model<any>[]): Model<any> {
399
- const matches = matchingModels(value, available);
400
- if (matches.length === 0) throw new AgentConfigurationError(filePath, "model", `unavailable model ${JSON.stringify(value)}`);
401
- if (matches.length > 1) throw new AgentConfigurationError(filePath, "model", `ambiguous model ${JSON.stringify(value)}; use provider/model`);
402
- return matches[0]!;
403
- }
404
-
405
- function configuredSetting(override: string | undefined, roleSetting: string | undefined): string | undefined {
406
- const overrideValue = override?.trim();
407
- const roleValue = roleSetting?.trim();
408
- const selected = overrideValue && overrideValue !== INHERIT_SETTING ? overrideValue : roleValue;
409
- return selected && selected !== INHERIT_SETTING ? selected : undefined;
410
- }
411
-
412
- export function resolveAgentModel(
413
- agent: AgentRole,
414
- ctx: ModelContext,
415
- modelOverride?: string,
416
- thinkingOverride?: string,
417
- ): ResolvedModel {
418
- const inheritedThinking = ctx.thinkingLevel ?? "off";
419
- const configuredModel = configuredSetting(modelOverride, agent.model);
420
- const configuredThinking = configuredSetting(thinkingOverride, agent.thinking);
421
- let definition: Model<any> | undefined;
422
- let thinking: string = configuredThinking ?? inheritedThinking;
423
-
424
- if (configuredModel) {
425
- const available = ctx.modelRegistry.getAvailable();
426
- const requested = splitModelAndThinking(configuredModel, agent.filePath, available);
427
- thinking = configuredThinking ?? requested.thinking ?? inheritedThinking;
428
- definition = resolveAvailableModel(requested.model, agent.filePath, available);
429
- } else {
430
- definition = ctx.model;
431
- if (!definition) throw new AgentConfigurationError(agent.filePath, "model", "no active parent model is available to inherit");
432
- }
433
-
434
- const supportedThinking = getSupportedThinkingLevels(definition) as readonly string[];
435
- if (!supportedThinking.includes(thinking)) {
436
- throw new AgentConfigurationError(agent.filePath, "thinking", `${definition.provider}/${definition.id} does not support thinking level ${thinking}`);
437
- }
438
- return { model: `${definition.provider}/${definition.id}`, thinking: thinking as ThinkingLevel, definition };
439
- }
440
-
441
- function getPiInvocation(args: string[]): { command: string; args: string[] } {
442
- const currentScript = process.argv[1];
443
- const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
444
- if (currentScript && !isBunVirtualScript) {
445
- try {
446
- if (statSync(currentScript).isFile()) return { command: process.execPath, args: [currentScript, ...args] };
447
- } catch {
448
- // Fall through to the installed pi command.
449
- }
450
- }
451
- const executable = path.basename(process.execPath).toLocaleLowerCase();
452
- return /^(node|bun)(\.exe)?$/u.test(executable)
453
- ? { command: "pi", args }
454
- : { command: process.execPath, args };
455
- }
456
-
457
- export function childProcessEnvironment(environment: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
458
- const childEnvironment = { ...environment };
459
- delete childEnvironment.PI_SESSION_FILE;
460
- delete childEnvironment.PI_SESSION_ID;
461
- return childEnvironment;
462
- }
463
-
464
- function defaultSpawnProcess(args: string[], cwd: string): SpawnedProcess {
465
- const invocation = getPiInvocation(args);
466
- return spawn(invocation.command, invocation.args, {
467
- cwd,
468
- detached: process.platform !== "win32",
469
- env: childProcessEnvironment(),
470
- shell: false,
471
- stdio: ["ignore", "pipe", "pipe"],
472
- windowsHide: true,
473
- }) as unknown as SpawnedProcess;
474
- }
475
-
476
- function truncateUtf8(text: string, maxBytes: number): { text: string; omittedBytes: number } {
477
- const bytes = Buffer.from(text, "utf8");
478
- if (bytes.length <= maxBytes) return { text, omittedBytes: 0 };
479
- let truncated = bytes.subarray(0, maxBytes).toString("utf8");
480
- if (truncated.endsWith("�")) truncated = truncated.slice(0, -1);
481
- return { text: truncated, omittedBytes: bytes.length - Buffer.byteLength(truncated, "utf8") };
482
- }
483
-
484
- function makeQueuedResult(id: string, agent: string, task: string, step?: number): SubagentTaskResult {
485
- return {
486
- id,
487
- agent,
488
- agentSource: "unknown",
489
- task,
490
- status: "queued",
491
- tools: [],
492
- trace: [],
493
- traceBytes: 0,
494
- traceTruncatedBytes: 0,
495
- stderr: "",
496
- stderrBytes: 0,
497
- stderrTruncatedBytes: 0,
498
- output: "",
499
- outputBytes: 0,
500
- outputTruncatedBytes: 0,
501
- toolCallCount: 0,
502
- usage: emptyUsage(),
503
- durationMs: 0,
504
- exitCode: null,
505
- step,
506
- };
507
- }
508
-
509
- function cloneResult(result: SubagentTaskResult): SubagentTaskResult {
510
- return {
511
- ...result,
512
- tools: [...result.tools],
513
- trace: [...result.trace],
514
- usage: { ...result.usage, cost: { ...result.usage.cost } },
515
- };
516
- }
517
-
518
- function mergeTaskResults(
519
- previous: SubagentTaskResult | undefined,
520
- next: SubagentTaskResult,
521
- maxTraceBytes?: number,
522
- maxStderrBytes?: number,
523
- ): SubagentTaskResult {
524
- if (!previous) return cloneResult(next);
525
- const merged = cloneResult(next);
526
- const trace: string[] = [];
527
- let traceBytes = 0;
528
- let traceTruncatedBytes = previous.traceTruncatedBytes + next.traceTruncatedBytes;
529
- for (const entry of [...previous.trace, ...next.trace]) {
530
- const retained = truncateUtf8(entry, maxTraceBytes === undefined ? Buffer.byteLength(entry, "utf8") : Math.max(0, maxTraceBytes - traceBytes));
531
- if (retained.text) trace.push(retained.text);
532
- const retainedBytes = Buffer.byteLength(retained.text, "utf8");
533
- traceBytes += retainedBytes;
534
- traceTruncatedBytes += retained.omittedBytes;
535
- }
536
- merged.trace = trace;
537
- merged.traceBytes = traceBytes;
538
- merged.traceTruncatedBytes = traceTruncatedBytes;
539
- const stderr = [previous.stderr, next.stderr].filter(Boolean).join("\n");
540
- const retainedStderr = truncateUtf8(stderr, maxStderrBytes === undefined ? Buffer.byteLength(stderr, "utf8") : maxStderrBytes);
541
- merged.stderr = retainedStderr.text;
542
- merged.stderrBytes = previous.stderrBytes + next.stderrBytes;
543
- merged.stderrTruncatedBytes = previous.stderrTruncatedBytes + next.stderrTruncatedBytes + retainedStderr.omittedBytes;
544
- merged.output = next.output || previous.output;
545
- merged.outputBytes = previous.outputBytes + next.outputBytes;
546
- merged.outputTruncatedBytes = previous.outputTruncatedBytes + next.outputTruncatedBytes;
547
- merged.toolCallCount = previous.toolCallCount + next.toolCallCount;
548
- merged.usage = emptyUsage();
549
- addUsage(merged.usage, previous.usage);
550
- addUsage(merged.usage, next.usage);
551
- merged.durationMs = previous.durationMs + next.durationMs;
552
- return merged;
553
- }
554
-
555
- function cloneDetails(mode: SubagentDetails["mode"], scope: AgentScope, projectAgentsDir: string | null, results: SubagentTaskResult[]): SubagentDetails {
556
- const cloned = results.map(cloneResult);
557
- return { mode, agentScope: scope, projectAgentsDir, results: cloned, aggregateUsage: aggregateUsage(cloned) };
558
- }
559
-
560
- async function writeRolePrompt(agent: AgentRole): Promise<{ directory: string; filePath: string }> {
561
- const directory = await mkdtemp(path.join(os.tmpdir(), "killeros-subagent-"));
562
- const filePath = path.join(directory, `${agent.name.replace(/[^A-Za-z0-9_.-]/gu, "_")}.md`);
563
- await writeFile(filePath, agent.prompt, { encoding: "utf8", mode: 0o600 });
564
- return { directory, filePath };
565
- }
566
-
567
- interface RunTaskOptions {
568
- cwd: string;
569
- agent: AgentRole;
570
- task: string;
571
- id: string;
572
- step?: number;
573
- model: ResolvedModel;
574
- signal?: AbortSignal;
575
- spawnProcess: (args: string[], cwd: string, environment?: NodeJS.ProcessEnv) => SpawnedProcess;
576
- webExtension?: string;
577
- projectTrusted: boolean;
578
- limits: SubagentLimits;
579
- sessionDirectory: string;
580
- sessionId: string;
581
- timeoutMs?: number;
582
- onChange: (result: SubagentTaskResult) => void;
583
- onHandle?: (handle: SubagentProcessHandle) => void;
584
- }
585
-
586
- function applyProcessResult(
587
- target: SubagentTaskResult,
588
- source: Readonly<SubagentProcessResult>,
589
- startedAt: number,
590
- onChange: (result: SubagentTaskResult) => void,
591
- ): void {
592
- target.status = source.status;
593
- target.trace = [...source.trace];
594
- target.traceBytes = source.traceBytes;
595
- target.traceTruncatedBytes = source.traceTruncatedBytes;
596
- target.stderr = source.stderr;
597
- target.stderrBytes = source.stderrBytes;
598
- target.stderrTruncatedBytes = source.stderrTruncatedBytes;
599
- target.output = source.output;
600
- target.outputBytes = source.outputBytes;
601
- target.outputTruncatedBytes = source.outputTruncatedBytes;
602
- target.toolCallCount = source.toolCallCount;
603
- target.usage = { ...source.usage, cost: { ...source.usage.cost } };
604
- target.model = source.model ?? target.model;
605
- target.terminationReason = source.terminationReason;
606
- target.errorMessage = source.errorMessage;
607
- target.exitCode = source.exitCode;
608
- target.durationMs = source.durationMs || Date.now() - startedAt;
609
- onChange(target);
610
- }
611
-
612
- async function runTask(options: RunTaskOptions): Promise<SubagentTaskResult> {
613
- const { agent, limits } = options;
614
- const result = makeQueuedResult(options.id, agent.name, options.task, options.step);
615
- result.agentSource = agent.source;
616
- result.sourcePath = agent.filePath;
617
- result.access = agent.access;
618
- result.tools = [...agent.tools];
619
- result.model = options.model.model;
620
- result.thinking = options.model.thinking;
621
- result.status = "running";
622
- const startedAt = Date.now();
623
- options.onChange(result);
624
-
625
- if (options.signal?.aborted) {
626
- result.status = "cancelled";
627
- result.terminationReason = "abort";
628
- result.durationMs = Date.now() - startedAt;
629
- options.onChange(result);
630
- return result;
631
- }
632
-
633
- let promptDirectory: string | undefined;
634
- try {
635
- const prompt = await writeRolePrompt(agent);
636
- promptDirectory = prompt.directory;
637
- if (options.signal?.aborted) {
638
- result.status = "cancelled";
639
- result.terminationReason = "abort";
640
- result.durationMs = Date.now() - startedAt;
641
- options.onChange(result);
642
- return result;
643
- }
644
- const args = [
645
- "--mode", "json",
646
- "-p",
647
- "--session-dir", options.sessionDirectory,
648
- "--session-id", options.sessionId,
649
- "--no-extensions",
650
- "--extension", options.webExtension ?? SUBAGENT_WEB_EXTENSION,
651
- "--no-prompt-templates",
652
- options.projectTrusted ? "--approve" : "--no-approve",
653
- "--model", options.model.model,
654
- "--thinking", options.model.thinking,
655
- "--tools", agent.tools.join(","),
656
- "--append-system-prompt", prompt.filePath,
657
- `Task: ${options.task}`,
658
- ];
659
- const handle = runSubagentProcess({
660
- args,
661
- cwd: options.cwd,
662
- signal: options.signal,
663
- spawnProcess: options.spawnProcess,
664
- limits: {
665
- ...(options.timeoutMs === undefined ? {} : { wallTimeMs: options.timeoutMs }),
666
- ...(limits.jsonlLineBytes === undefined ? {} : { jsonlLineBytes: limits.jsonlLineBytes }),
667
- ...(limits.traceBytes === undefined ? {} : { traceBytes: limits.traceBytes }),
668
- ...(limits.stderrBytes === undefined ? {} : { stderrBytes: limits.stderrBytes }),
669
- ...(limits.taskOutputBytes === undefined ? {} : { outputBytes: limits.taskOutputBytes }),
670
- ...(limits.quotaTokens === undefined ? {} : { quotaTokens: limits.quotaTokens }),
671
- ...(limits.quotaUsd === undefined ? {} : { quotaUsd: limits.quotaUsd }),
672
- killGraceMs: limits.killGraceMs,
673
- },
674
- retention: {
675
- traceBytes: limits.traceRetentionBytes,
676
- stderrBytes: limits.stderrRetentionBytes,
677
- outputBytes: limits.taskOutputRetentionBytes,
678
- },
679
- onUpdate: (next) => applyProcessResult(result, next, startedAt, options.onChange),
680
- });
681
- options.onHandle?.(handle);
682
- const final = await handle.result;
683
- applyProcessResult(result, final, startedAt, options.onChange);
684
- return result;
685
- } catch (error) {
686
- result.status = options.signal?.aborted ? "cancelled" : "failed";
687
- result.terminationReason = options.signal?.aborted ? "abort" : "spawn_error";
688
- result.errorMessage = error instanceof Error ? error.message : String(error);
689
- result.durationMs = Date.now() - startedAt;
690
- options.onChange(result);
691
- return result;
692
- } finally {
693
- if (promptDirectory) {
694
- try {
695
- await rm(promptDirectory, { recursive: true, force: true });
696
- } catch {
697
- // Temporary prompt cleanup is best effort after child termination.
698
- }
699
- }
700
- }
701
- }
702
-
703
- async function mapReadTasks<T>(items: T[], concurrency: number, run: (item: T, index: number) => Promise<void>): Promise<void> {
704
- let next = 0;
705
- const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
706
- while (true) {
707
- const index = next;
708
- next += 1;
709
- if (index >= items.length) return;
710
- await run(items[index]!, index);
711
- }
712
- });
713
- await Promise.all(workers);
714
- }
715
-
716
- function waitForConfirmedProcessExit(handle: SubagentProcessHandle, timeoutMs = 1_000): Promise<boolean> {
717
- if (handle.hasExited) return Promise.resolve(true);
718
- return new Promise((resolve) => {
719
- let settled = false;
720
- let timeout: NodeJS.Timeout | undefined;
721
- const finish = (exited: boolean): void => {
722
- if (settled) return;
723
- settled = true;
724
- if (timeout) clearTimeout(timeout);
725
- resolve(exited);
726
- };
727
- timeout = setTimeout(() => finish(handle.hasExited), timeoutMs);
728
- void handle.exited.then(() => finish(true));
729
- });
730
- }
731
-
732
- function createSubagentParams(limits: Pick<SubagentLimits, "maxTasks" | "maxReadConcurrency" | "taskCharacters">) {
733
- const taskSchema = Type.Object({
734
- agent: Type.String({ minLength: 1, maxLength: 64, description: "Agent role name" }),
735
- task: Type.String({ minLength: 1, maxLength: limits.taskCharacters, description: "Bounded task for the role" }),
736
- });
737
- const chainTaskSchema = Type.Object({
738
- agent: Type.String({ minLength: 1, maxLength: 64, description: "Agent role name" }),
739
- task: Type.String({ minLength: 1, maxLength: limits.taskCharacters, description: "Task with optional {previous} handoff placeholder" }),
740
- });
741
- return Type.Object({
742
- action: Type.Optional(StringEnum(["spawn", "list", "inspect", "steer", "interrupt", "collect", "close"] as const, {
743
- default: "spawn",
744
- description: "Thread lifecycle action",
745
- })),
746
- threadId: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Stable child thread ID" })),
747
- message: Type.Optional(Type.String({ minLength: 1, maxLength: 4_000, description: "Bounded steering message; only valid with action steer" })),
748
- all: Type.Optional(Type.Boolean({ description: "Interrupt every active child thread" })),
749
- agent: Type.Optional(Type.String({ minLength: 1, maxLength: 64, description: "Agent role for single mode" })),
750
- task: Type.Optional(Type.String({ minLength: 1, maxLength: limits.taskCharacters, description: "Task for single mode" })),
751
- tasks: Type.Optional(Type.Array(taskSchema, { minItems: 1, maxItems: limits.maxTasks, description: `Parallel role tasks: read-only batches run concurrently up to ${limits.maxReadConcurrency}; batches with writers use a shared pool by default up to ${limits.maxTasks}. Set writerConcurrency to cap that pool, or set it to 1 to serialize the entire writer-containing batch; concurrent writers share the parent worktree, so callers must avoid file conflicts` })),
752
- writerConcurrency: Type.Optional(Type.Integer({ minimum: 1, maximum: limits.maxTasks, description: `Optional shared-pool cap for parallel tasks that include writers. Defaults to ${limits.maxTasks}; set 1 to serialize the entire writer-containing batch. Concurrent writers share the parent worktree, so callers must avoid file conflicts` })),
753
- chain: Type.Optional(Type.Array(chainTaskSchema, { minItems: 1, maxItems: limits.maxTasks, description: "Sequential role tasks; {previous} inserts the prior result" })),
754
- model: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Model for every task as provider/model; inherit uses each role setting or the active parent" })),
755
- thinking: Type.Optional(Type.String({ minLength: 1, maxLength: 16, description: "Thinking effort for every task: off, minimal, low, medium, high, xhigh, max, or inherit" })),
756
- agentScope: Type.Optional(StringEnum(["user", "project", "both"] as const, {
757
- default: "user",
758
- description: "Role sources: user includes bundled and personal; project includes bundled and trusted project; both includes all",
759
- })),
760
- });
761
- }
762
-
763
- type TaskInput = { agent: string; task: string };
764
-
765
- type ToolUpdate = (partial: { content: Array<{ type: "text"; text: string }>; details: SubagentDetails }) => void;
766
-
767
- function requestedAgents(params: { agent?: string; tasks?: TaskInput[]; chain?: TaskInput[] }): string[] {
768
- if (params.agent) return [params.agent];
769
- return (params.tasks ?? params.chain ?? []).map((task) => task.agent);
770
- }
771
-
772
- function clipCharacters(text: string, maxCharacters: number, fromEnd = false): string {
773
- const characters = [...text];
774
- if (characters.length <= maxCharacters) return text;
775
- return (fromEnd ? characters.slice(-maxCharacters) : characters.slice(0, maxCharacters)).join("");
776
- }
777
-
778
- function buildSteeredTask(task: string, steering: readonly string[], maxCharacters: number): string {
779
- const steeringLabel = "\n\nParent steering:\n";
780
- const steeringText = clipCharacters(steering.join("\n"), Math.max(0, maxCharacters - [...steeringLabel].length), true);
781
- const required = [...steeringLabel, ...steeringText].length;
782
- const taskText = clipCharacters(task, Math.max(0, maxCharacters - required));
783
- return `${taskText}${steeringLabel}${steeringText}`;
784
- }
785
-
786
- function formatUsage(usage: SubagentUsage): string {
787
- const parts = [`${usage.turns} turn${usage.turns === 1 ? "" : "s"}`, `${usage.totalTokens} tokens`];
788
- if (usage.cost.total) parts.push(`$${usage.cost.total.toFixed(4)}`);
789
- return parts.join(" · ");
790
- }
791
-
792
- function buildToolContent(mode: SubagentDetails["mode"], results: SubagentTaskResult[], maxBytes: number): string {
793
- const sections = results.map((result) => {
794
- const heading = `### ${result.id} · ${result.agent} · ${result.status}`;
795
- const reason = result.terminationReason && result.terminationReason !== "completed" ? `\nReason: ${result.terminationReason}` : "";
796
- const body = result.output || result.errorMessage || result.stderr.trim() || "(no output)";
797
- const truncation = result.outputTruncatedBytes ? `\n\n[Task output truncated: ${result.outputTruncatedBytes} bytes omitted; bounded detail is available when expanded.]` : "";
798
- return `${heading}${reason}\n\n${body}${truncation}`;
799
- });
800
- const complete = results.filter((result) => result.status === "complete").length;
801
- const text = `${mode}: ${complete}/${results.length} complete · ${formatUsage(aggregateUsage(results))}\n\n${sections.join("\n\n---\n\n")}`;
802
- const marker = "\n\n[Combined subagent output truncated to 50 KiB; inspect the expanded tool result for bounded per-task details.]";
803
- return boundedText(text, maxBytes, marker);
804
- }
805
-
806
- function statusColor(status: SubagentStatus): "accent" | "success" | "error" | "warning" | "muted" {
807
- if (status === "running") return "accent";
808
- if (status === "complete") return "success";
809
- if (status === "failed") return "error";
810
- if (status === "limited" || status === "cancelled") return "warning";
811
- return "muted";
812
- }
813
-
814
- function statusIcon(status: SubagentStatus): string {
815
- if (status === "running") return "✻";
816
- if (status === "complete") return "✓";
817
- if (status === "failed") return "✗";
818
- if (status === "queued") return "○";
819
- return "!";
820
- }
821
-
822
- interface ActiveThreadRuntime {
823
- controller: AbortController;
824
- handle?: SubagentProcessHandle;
825
- handles: Set<SubagentProcessHandle>;
826
- steering: string[];
827
- restarting: boolean;
828
- traceCount: number;
829
- startedAt: number;
830
- aggregate?: SubagentTaskResult;
831
- requestedReason?: string;
832
- }
833
-
834
- function parentThreadId(ctx: ExtensionContext): string {
835
- try {
836
- const id = ctx.sessionManager?.getSessionId?.();
837
- if (id) return `main:${id}`;
838
- } catch {
839
- // Test and RPC contexts may not expose a session manager.
840
- }
841
- return "main";
842
- }
843
-
844
- function threadCapabilityBoundary(agent: AgentRole): {
845
- filesystem: "read" | "write";
846
- network: "none" | "read";
847
- process: "none" | "limited";
848
- childThreads: false;
849
- } {
850
- return {
851
- filesystem: agent.access,
852
- network: agent.tools.some((tool) => WEB_TOOLS.has(tool)) ? "read" : "none",
853
- process: agent.tools.includes("bash") ? "limited" : "none",
854
- childThreads: false,
855
- };
856
- }
857
-
858
- function threadUsage(usage: SubagentUsage): SubagentThread["usage"] {
859
- return {
860
- inputTokens: usage.input,
861
- outputTokens: usage.output,
862
- cacheReadTokens: usage.cacheRead,
863
- cacheWriteTokens: usage.cacheWrite,
864
- totalTokens: usage.totalTokens,
865
- costUsd: usage.cost.total,
866
- turns: usage.turns,
867
- };
868
- }
869
-
870
- function legacyStatus(state: SubagentThreadState): SubagentStatus {
871
- if (state === "active") return "running";
872
- if (state === "done" || state === "closed") return "complete";
873
- if (state === "failed") return "failed";
874
- if (state === "stopped") return "cancelled";
875
- return "queued";
876
- }
877
-
878
- function threadResult(thread: SubagentThread, source?: SubagentTaskResult): SubagentTaskResult {
879
- if (source) {
880
- const result = cloneResult(source);
881
- if (thread.state === "queued") result.status = "queued";
882
- else if (thread.state === "active") result.status = "running";
883
- return result;
884
- }
885
- return {
886
- ...makeQueuedResult(thread.id, thread.role, thread.prompt),
887
- status: legacyStatus(thread.state),
888
- agentSource: "unknown",
889
- model: thread.model,
890
- tools: [...thread.tools],
891
- trace: thread.trace.map((event) => event.message ?? event.kind),
892
- usage: {
893
- input: thread.usage.inputTokens,
894
- output: thread.usage.outputTokens,
895
- cacheRead: thread.usage.cacheReadTokens,
896
- cacheWrite: thread.usage.cacheWriteTokens,
897
- totalTokens: thread.usage.totalTokens,
898
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: thread.usage.costUsd },
899
- turns: thread.usage.turns,
900
- },
901
- output: thread.result ?? "",
902
- toolCallCount: 0,
903
- terminationReason: thread.stopReason,
904
- };
905
- }
906
-
907
- function threadBoardRecord(result: SubagentTaskResult): ThreadBoardRecord {
908
- return {
909
- id: result.id,
910
- agent: result.agent,
911
- task: result.task,
912
- status: result.status,
913
- usage: {
914
- input: result.usage.input,
915
- output: result.usage.output,
916
- cacheRead: result.usage.cacheRead,
917
- cacheWrite: result.usage.cacheWrite,
918
- totalTokens: result.usage.totalTokens,
919
- turns: result.usage.turns,
920
- cost: result.usage.cost.total,
921
- },
922
- trace: result.trace,
923
- traceTruncatedBytes: result.traceTruncatedBytes,
924
- handoff: result.output,
925
- output: result.output,
926
- terminationReason: result.terminationReason,
927
- errorMessage: result.errorMessage,
928
- durationMs: result.durationMs,
929
- step: result.step,
930
- };
931
- }
932
-
933
- export function registerSubagentTool(pi: ExtensionAPI, options: SubagentRuntimeOptions = {}): void {
934
- const limits = { ...SUBAGENT_LIMITS, ...options.limits };
935
- const spawnProcess = options.spawnProcess ?? defaultSpawnProcess;
936
- const threads = new SubagentThreadRegistry();
937
- const activeRuntimes = new Map<string, ActiveThreadRuntime>();
938
- const savedResults = new Map<string, SubagentTaskResult>();
939
-
940
- const detailsFor = (
941
- parentId: string,
942
- mode: SubagentDetails["mode"] = "single",
943
- scope: AgentScope = "user",
944
- projectAgentsDir: string | null = null,
945
- selectedThreadId?: string,
946
- ): SubagentDetails => {
947
- const all = threads.listAll().filter((thread) => thread.parentId === parentId);
948
- const visible = all.filter((thread) => thread.state !== "closed");
949
- const results = visible.map((thread) => threadResult(thread, savedResults.get(thread.id)));
950
- return {
951
- ...cloneDetails(mode, scope, projectAgentsDir, results),
952
- parentId,
953
- threads: all,
954
- activeThreads: all.filter((thread) => thread.state === "active"),
955
- doneThreads: all.filter((thread) => ["done", "failed", "stopped"].includes(thread.state)),
956
- selectedThreadId,
957
- };
958
- };
959
-
960
- const threadBoardText = (parentId: string, selectedThreadId?: string): string => {
961
- const details = detailsFor(parentId, "single", "user", null, selectedThreadId);
962
- const active = details.activeThreads ?? [];
963
- const done = details.doneThreads ?? [];
964
- const row = (thread: SubagentThread): string => `- ${thread.id} · ${thread.role} · ${thread.state} · ${thread.prompt}`;
965
- const lines = [
966
- `parent ${parentId}`,
967
- `Active (${active.length})`,
968
- ...(active.length ? active.map(row) : ["- none"]),
969
- `Done (${done.length})`,
970
- ...(done.length ? done.map(row) : ["- none"]),
971
- "Controls: inspect · steer · interrupt · collect · close",
972
- ];
973
- if (selectedThreadId) {
974
- const selected = details.threads?.find((thread) => thread.id === selectedThreadId);
975
- if (selected) {
976
- lines.push(`Inspect ${selected.id}: ${selected.state}`);
977
- lines.push(`Role: ${selected.role}`);
978
- lines.push(`Model: ${selected.model}`);
979
- lines.push(`Tools: ${selected.tools.join(", ")}`);
980
- lines.push(`Trace: ${selected.trace.length} entries`);
981
- if (selected.result) lines.push(`Handoff: ${selected.result}`);
982
- if (selected.stopReason) lines.push(`Reason: ${selected.stopReason}`);
983
- }
984
- }
985
- return boundedText(lines.join("\n"), limits.toolOutputBytes, "\n\n[Thread board truncated; inspect a child thread for its bounded detail.]");
986
- };
987
-
988
- const syncThread = (threadId: SubagentThreadId, next: SubagentTaskResult, runtime?: ActiveThreadRuntime): SubagentTaskResult => {
989
- const effective = mergeTaskResults(runtime?.aggregate, next, limits.traceRetentionBytes, limits.stderrRetentionBytes);
990
- if (runtime?.requestedReason && next.status === "cancelled") effective.terminationReason = runtime.requestedReason;
991
- savedResults.set(threadId, cloneResult(effective));
992
- let thread = threads.inspect(threadId);
993
- if (!thread || threads.isDisposed) return effective;
994
- if (thread.state === "queued" && next.status === "running") {
995
- thread = threads.begin(threadId);
996
- }
997
- if (thread.state !== "active") return effective;
998
- if (runtime && next.trace.length < runtime.traceCount) runtime.traceCount = 0;
999
- const from = runtime?.traceCount ?? 0;
1000
- let retainedTraceBytes = thread.trace.reduce((total, entry) => total + Buffer.byteLength(entry.message ?? "", "utf8"), 0);
1001
- for (const entry of next.trace.slice(from)) {
1002
- const retained = truncateUtf8(entry, limits.traceRetentionBytes === undefined
1003
- ? Buffer.byteLength(entry, "utf8")
1004
- : Math.max(0, limits.traceRetentionBytes - retainedTraceBytes));
1005
- if (retained.text) {
1006
- threads.trace(threadId, { kind: "child", message: retained.text });
1007
- retainedTraceBytes += Buffer.byteLength(retained.text, "utf8");
1008
- }
1009
- }
1010
- if (runtime) runtime.traceCount = next.trace.length;
1011
- const handoff = effective.output ? { summary: effective.output } : undefined;
1012
- thread = threads.patch(threadId, { usage: threadUsage(effective.usage), result: effective.output || undefined, handoff });
1013
- const restartPending = runtime?.restarting === true && ["cancelled", "complete"].includes(next.status);
1014
- if (restartPending) return effective;
1015
- if (effective.status === "complete") {
1016
- threads.complete(threadId, { usage: threadUsage(effective.usage), result: effective.output || undefined, handoff });
1017
- } else if (effective.status === "failed") {
1018
- threads.fail(threadId, {
1019
- usage: threadUsage(effective.usage),
1020
- result: effective.output || undefined,
1021
- handoff,
1022
- message: effective.errorMessage ?? effective.terminationReason ?? "child failed",
1023
- code: effective.terminationReason,
1024
- });
1025
- } else if (effective.status === "cancelled" || effective.status === "limited") {
1026
- threads.stop(threadId, {
1027
- usage: threadUsage(effective.usage),
1028
- result: effective.output || undefined,
1029
- handoff,
1030
- reason: effective.terminationReason ?? (effective.status === "limited" ? "resource_limit" : "interrupted"),
1031
- });
1032
- }
1033
- return effective;
1034
- };
1035
-
1036
- if (typeof pi.on === "function") {
1037
- pi.on("session_shutdown", () => {
1038
- for (const runtime of activeRuntimes.values()) {
1039
- runtime.restarting = false;
1040
- runtime.requestedReason = "session_shutdown";
1041
- runtime.handle?.stop("session_shutdown");
1042
- runtime.controller.abort();
1043
- }
1044
- threads.dispose();
1045
- });
1046
- }
1047
-
1048
- pi.registerTool({
1049
- name: "subagent",
1050
- label: "Subagents",
1051
- description: `Spawn and manage named child threads. Children finish naturally. Parallel tasks with write-capable roles use one shared pool by default, up to ${limits.maxTasks}; read-only batches run concurrently up to ${limits.maxReadConcurrency}. Set writerConcurrency to cap the shared pool, or set it to 1 to serialize the entire writer-containing batch. Concurrent writers share the parent worktree, so callers must avoid file conflicts. The message parameter is only valid with action steer. Use action list, inspect, steer, interrupt, collect, and close to manage active and completed handoffs.`,
1052
- promptSnippet: "Delegate bounded specialist work to isolated KillerOS subagents",
1053
- promptGuidelines: [
1054
- "Use subagent for clearly separable specialist work; prefer read-only scout, planner, reviewer, or security roles before a writer.",
1055
- `Parallel tasks with write-capable roles use one shared pool by default because all children share the parent worktree. Set writerConcurrency to cap the pool, or set it to 1 to serialize the entire writer-containing batch; callers remain responsible for file conflicts.`,
1056
- "Every child can load relevant skills with read and can use web_search, source_check, fetch_content, and get_search_content for external research.",
1057
- "When the user names a model or thinking effort, pass model and thinking separately; use inherit when the active parent or role setting should decide.",
1058
- "Keep completed and stopped threads inspectable until the parent explicitly closes them.",
1059
- ],
1060
- parameters: createSubagentParams(limits),
1061
- executionMode: "parallel",
1062
-
1063
- async execute(_toolCallId, params, signal, onUpdate, ctx) {
1064
- const action = params.action ?? "spawn";
1065
- if (params.message !== undefined && action !== "steer") {
1066
- throw new Error("message is only valid with action steer");
1067
- }
1068
- const parentId = parentThreadId(ctx);
1069
- const actionDetails = (selectedThreadId?: string): SubagentDetails => detailsFor(parentId, "single", params.agentScope ?? "user", null, selectedThreadId);
1070
- const actionResult = (text: string, selectedThreadId?: string) => {
1071
- const details = actionDetails(selectedThreadId);
1072
- return {
1073
- content: [{ type: "text" as const, text: boundedText(text, limits.toolOutputBytes, "\n\n[Thread action output truncated.]") }],
1074
- details,
1075
- usage: details.aggregateUsage,
1076
- };
1077
- };
1078
-
1079
- if (action === "list") return actionResult(threadBoardText(parentId));
1080
- if (action === "inspect") {
1081
- if (!params.threadId) throw new Error("inspect requires threadId");
1082
- const thread = threads.inspect(params.threadId as SubagentThreadId);
1083
- if (!thread || thread.parentId !== parentId) throw new Error(`Unknown child thread ${JSON.stringify(params.threadId)}`);
1084
- return actionResult(threadBoardText(parentId, params.threadId), params.threadId);
1085
- }
1086
- if (action === "steer") {
1087
- if (!params.threadId || !params.message) throw new Error("steer requires threadId and message");
1088
- const threadId = params.threadId as SubagentThreadId;
1089
- const thread = threads.inspect(threadId);
1090
- if (!thread || thread.parentId !== parentId) throw new Error(`Unknown child thread ${JSON.stringify(params.threadId)}`);
1091
- threads.steer(threadId, params.message);
1092
- const runtime = activeRuntimes.get(params.threadId);
1093
- if (runtime) {
1094
- runtime.steering.push(params.message);
1095
- if (runtime.steering.length > MAX_RUNTIME_STEERING_MESSAGES) runtime.steering.splice(0, runtime.steering.length - MAX_RUNTIME_STEERING_MESSAGES);
1096
- runtime.restarting = true;
1097
- runtime.requestedReason = "steer";
1098
- runtime.handle?.stop("steer");
1099
- }
1100
- return actionResult(`Steering queued for ${params.threadId}. The child keeps the same thread and handoff record.`, params.threadId);
1101
- }
1102
- if (action === "interrupt") {
1103
- if (!params.all && !params.threadId) throw new Error("interrupt requires threadId or all=true");
1104
- let targets: SubagentThread[];
1105
- if (params.all) {
1106
- targets = threads.listActive().filter((thread) => thread.parentId === parentId);
1107
- } else {
1108
- const target = threads.inspect(params.threadId as SubagentThreadId);
1109
- if (!target || target.parentId !== parentId) throw new Error(`Unknown child thread ${JSON.stringify(params.threadId)}`);
1110
- if (target.state !== "active" && target.state !== "queued") {
1111
- throw new Error(`Cannot interrupt thread ${params.threadId} from ${target.state}`);
1112
- }
1113
- targets = [target];
1114
- }
1115
- for (const thread of targets) {
1116
- if (thread.parentId !== parentId) continue;
1117
- const runtime = activeRuntimes.get(thread.id);
1118
- if (runtime) {
1119
- runtime.restarting = false;
1120
- runtime.requestedReason = "interrupt";
1121
- runtime.handle?.stop("interrupt");
1122
- runtime.controller.abort();
1123
- } else if (thread.state === "active" || thread.state === "queued") {
1124
- threads.stop(thread.id, { reason: "interrupt" });
1125
- }
1126
- }
1127
- return actionResult(params.all ? "Interrupt requested for all active child threads." : `Interrupt requested for ${params.threadId}.`);
1128
- }
1129
- if (action === "collect") {
1130
- if (!params.threadId) throw new Error("collect requires threadId");
1131
- const thread = threads.inspect(params.threadId as SubagentThreadId);
1132
- if (!thread || thread.parentId !== parentId) throw new Error(`Unknown child thread ${JSON.stringify(params.threadId)}`);
1133
- const collected = threads.collect(params.threadId as SubagentThreadId);
1134
- return actionResult(`Collected ${params.threadId}: ${collected.result ?? collected.failure?.message ?? collected.stopReason ?? "no handoff"}`, params.threadId);
1135
- }
1136
- if (action === "close") {
1137
- if (!params.threadId) throw new Error("close requires threadId");
1138
- const thread = threads.inspect(params.threadId as SubagentThreadId);
1139
- if (!thread || thread.parentId !== parentId) throw new Error(`Unknown child thread ${JSON.stringify(params.threadId)}`);
1140
- threads.close(params.threadId as SubagentThreadId);
1141
- return actionResult(`Closed ${params.threadId}. Its result record remains inspectable.`, params.threadId);
1142
- }
1143
-
1144
- const scope: AgentScope = params.agentScope ?? "user";
1145
- const hasSingleFields = params.agent !== undefined || params.task !== undefined;
1146
- const hasParallel = params.tasks !== undefined;
1147
- const hasChain = params.chain !== undefined;
1148
- const hasSingle = hasSingleFields && Boolean(params.agent && params.task);
1149
- if (Number(hasSingleFields) + Number(hasParallel) + Number(hasChain) !== 1
1150
- || hasSingleFields && !hasSingle
1151
- || hasParallel && params.tasks!.length === 0
1152
- || hasChain && params.chain!.length === 0) {
1153
- throw new Error("Provide exactly one subagent mode: agent + task, tasks, or chain");
1154
- }
1155
- if (params.writerConcurrency !== undefined) {
1156
- if (!hasParallel) throw new Error("writerConcurrency is only valid with parallel tasks");
1157
- if (!Number.isSafeInteger(params.writerConcurrency) || params.writerConcurrency < 1 || params.writerConcurrency > limits.maxTasks) {
1158
- throw new Error(`writerConcurrency must be a positive integer no greater than ${limits.maxTasks}`);
1159
- }
1160
- }
1161
-
1162
- const discovery = discoverAgentRoles(ctx.cwd, scope, ctx.isProjectTrusted(), options);
1163
- const roles = new Map(discovery.agents.map((agent) => [agent.name, agent]));
1164
- const requested = requestedAgents(params);
1165
- for (const name of requested) {
1166
- if (!roles.has(name)) {
1167
- const available = discovery.agents.map((agent) => `${agent.name} (${agent.source})`).join(", ") || "none";
1168
- throw new Error(`Unknown subagent ${JSON.stringify(name)}. Available: ${available}`);
1169
- }
1170
- }
1171
-
1172
- const projectRoles = [...new Set(requested.map((name) => roles.get(name)!).filter((role) => role.source === "project"))];
1173
- if (projectRoles.length) {
1174
- if (!ctx.hasUI) throw new Error("Project-local subagents require interactive confirmation");
1175
- const approved = await ctx.ui.confirm(
1176
- "Run project-local subagents?",
1177
- `Roles: ${projectRoles.map((role) => role.name).join(", ")}\nSources:\n${projectRoles.map((role) => role.filePath).join("\n")}\n\nThese trusted repository files control child prompts and tools.`,
1178
- );
1179
- if (!approved) throw new Error("Project-local subagents were not approved");
1180
- }
1181
-
1182
- const resolvedModels = new Map<string, ResolvedModel>();
1183
- for (const name of new Set(requested)) {
1184
- resolvedModels.set(name, resolveAgentModel(roles.get(name)!, ctx, params.model, params.thinking));
1185
- }
1186
-
1187
- const mode: SubagentDetails["mode"] = hasParallel ? "parallel" : hasChain ? "chain" : "single";
1188
- const inputs: TaskInput[] = hasSingle
1189
- ? [{ agent: params.agent!, task: params.task! }]
1190
- : hasParallel ? params.tasks! : params.chain!;
1191
- if (inputs.length > limits.maxTasks) throw new Error(`At most ${limits.maxTasks} subagent tasks are allowed`);
1192
- const readIndexes = hasParallel
1193
- ? inputs.map((input, index) => ({ input, index })).filter(({ input }) => roles.get(input.agent)!.access === "read")
1194
- : [];
1195
- const writerIndexes = hasParallel
1196
- ? inputs.map((input, index) => ({ input, index })).filter(({ input }) => roles.get(input.agent)!.access === "write").map(({ index }) => index)
1197
- : [];
1198
- if (params.writerConcurrency !== undefined && hasParallel && writerIndexes.length === 0) {
1199
- throw new Error("writerConcurrency requires at least one write-capable role");
1200
- }
1201
- const writerConcurrency = params.writerConcurrency ?? limits.maxTasks;
1202
- const useSharedParallelPool = hasParallel && writerIndexes.length > 0;
1203
- const executionNote = hasParallel
1204
- ? writerIndexes.length
1205
- ? `Parallel schedule: all tasks run through a shared pool of up to ${writerConcurrency}${params.writerConcurrency === undefined ? " (default)" : ""}; concurrent write-capable tasks share the parent worktree, so callers must avoid file conflicts.`
1206
- : `Parallel schedule: read-only tasks run concurrently up to ${limits.maxReadConcurrency}.`
1207
- : undefined;
1208
-
1209
- const inFlight = threads.listAll().filter((thread) => ["queued", "active"].includes(thread.state)).length;
1210
- if (inFlight + inputs.length > limits.maxTasks) {
1211
- throw new Error(`At most ${limits.maxTasks} child threads may be active at once`);
1212
- }
1213
-
1214
- const threadRecords = inputs.map((input, index) => threads.spawn({
1215
- parentId: parentId as SubagentThreadId,
1216
- role: input.agent,
1217
- prompt: input.task,
1218
- model: resolvedModels.get(input.agent)!.model,
1219
- tools: roles.get(input.agent)!.tools,
1220
- capabilityBoundary: threadCapabilityBoundary(roles.get(input.agent)!),
1221
- }));
1222
- const results = threadRecords.map((thread, index) => {
1223
- return makeQueuedResult(thread.id, inputs[index]!.agent, inputs[index]!.task, hasChain ? index + 1 : undefined);
1224
- });
1225
- const emit = (message = `${mode}: ${results.filter((result) => !["queued", "running"].includes(result.status)).length}/${results.length} settled`): void => {
1226
- const board = detailsFor(parentId, mode, scope, discovery.projectAgentsDir);
1227
- const currentResults = results.map(cloneResult);
1228
- (onUpdate as ToolUpdate | undefined)?.({
1229
- content: [{ type: "text", text: message }],
1230
- details: { ...board, executionNote, results: currentResults, aggregateUsage: aggregateUsage(currentResults) },
1231
- });
1232
- };
1233
- const runAt = async (index: number, task: string): Promise<void> => {
1234
- const threadId = threadRecords[index]!.id;
1235
- const initialThread = threads.inspect(threadId);
1236
- if (signal?.aborted) {
1237
- results[index] = { ...results[index]!, status: "cancelled", terminationReason: "abort" };
1238
- if (initialThread?.state === "queued" || initialThread?.state === "active") threads.stop(threadId, { reason: "abort" });
1239
- savedResults.set(threadId, cloneResult(results[index]!));
1240
- emit();
1241
- return;
1242
- }
1243
- if (!initialThread) return;
1244
- if (initialThread.state === "closed") {
1245
- results[index] = { ...results[index]!, status: "cancelled", terminationReason: initialThread.stopReason ?? "disposed" };
1246
- savedResults.set(threadId, cloneResult(results[index]!));
1247
- emit();
1248
- return;
1249
- }
1250
- if (initialThread.state === "stopped") {
1251
- results[index] = { ...results[index]!, status: "cancelled", terminationReason: initialThread.stopReason ?? "interrupted" };
1252
- savedResults.set(threadId, cloneResult(results[index]!));
1253
- emit();
1254
- return;
1255
- }
1256
- if (initialThread.state !== "queued") return;
1257
- const input = inputs[index]!;
1258
- threads.begin(threadId);
1259
- if ([...task].length > limits.taskCharacters) {
1260
- results[index] = {
1261
- ...results[index]!,
1262
- status: "failed",
1263
- terminationReason: "task_limit",
1264
- errorMessage: `Expanded task exceeds ${limits.taskCharacters} characters`,
1265
- };
1266
- threads.fail(threadId, { message: results[index]!.errorMessage ?? "Expanded task exceeds the task limit", code: "task_limit" });
1267
- savedResults.set(threadId, cloneResult(results[index]!));
1268
- emit();
1269
- return;
1270
- }
1271
- const controller = new AbortController();
1272
- const runtime: ActiveThreadRuntime = {
1273
- controller,
1274
- handles: new Set(),
1275
- steering: [],
1276
- restarting: false,
1277
- traceCount: 0,
1278
- startedAt: Date.now(),
1279
- };
1280
- activeRuntimes.set(threadId, runtime);
1281
- let sessionDirectory: string;
1282
- try {
1283
- sessionDirectory = await mkdtemp(path.join(os.tmpdir(), "killeros-subagent-session-"));
1284
- } catch (error) {
1285
- activeRuntimes.delete(threadId);
1286
- const message = error instanceof Error ? error.message : String(error);
1287
- results[index] = {
1288
- ...results[index]!,
1289
- status: "failed",
1290
- terminationReason: "session_error",
1291
- errorMessage: message,
1292
- };
1293
- threads.fail(threadId, { message, code: "session_error" });
1294
- savedResults.set(threadId, cloneResult(results[index]!));
1295
- emit();
1296
- return;
1297
- }
1298
- const currentThread = threads.inspect(threadId);
1299
- if (controller.signal.aborted || threads.isDisposed || currentThread?.state !== "active") {
1300
- activeRuntimes.delete(threadId);
1301
- try {
1302
- await rm(sessionDirectory, { recursive: true, force: true });
1303
- } catch {
1304
- // Temporary child session cleanup is best effort before process startup.
1305
- }
1306
- const reason = runtime.requestedReason ?? currentThread?.stopReason ?? (threads.isDisposed ? "session_shutdown" : "interrupted");
1307
- results[index] = { ...results[index]!, status: "cancelled", terminationReason: reason };
1308
- if (!threads.isDisposed && currentThread?.state === "active") threads.stop(threadId, { reason });
1309
- savedResults.set(threadId, cloneResult(results[index]!));
1310
- emit();
1311
- return;
1312
- }
1313
- const sessionId = `killeros-${threadId.replace(/[^A-Za-z0-9_.-]/gu, "_")}`;
1314
- const agent = roles.get(input.agent)!;
1315
- const queuedSteering = initialThread.steering.map((entry) => entry.message);
1316
- let currentTask = queuedSteering.length ? buildSteeredTask(task, queuedSteering, limits.taskCharacters) : task;
1317
- const stopForBudget = (reason: string, message: string): void => {
1318
- const limited = cloneResult(runtime.aggregate ?? results[index]!);
1319
- limited.status = "limited";
1320
- limited.terminationReason = reason;
1321
- limited.errorMessage = message;
1322
- runtime.aggregate = limited;
1323
- results[index] = cloneResult(limited);
1324
- savedResults.set(threadId, cloneResult(limited));
1325
- if (!threads.isDisposed && threads.inspect(threadId)?.state === "active") {
1326
- threads.stop(threadId, {
1327
- usage: threadUsage(limited.usage),
1328
- result: limited.output || undefined,
1329
- handoff: limited.output ? { summary: limited.output } : undefined,
1330
- reason,
1331
- });
1332
- }
1333
- emit();
1334
- };
1335
- try {
1336
- while (true) {
1337
- const aggregate = runtime.aggregate;
1338
- const wallTimeMs = agent.timeoutMs ?? limits.wallTimeMs;
1339
- const remainingWallTimeMs = wallTimeMs === undefined ? undefined : wallTimeMs - (Date.now() - runtime.startedAt);
1340
- const usedTraceBytes = (aggregate?.traceBytes ?? 0) + (aggregate?.traceTruncatedBytes ?? 0);
1341
- const usedStderrBytes = aggregate?.stderrBytes ?? 0;
1342
- const usedOutputBytes = aggregate?.outputBytes ?? 0;
1343
- const usedTokens = aggregate?.usage.totalTokens ?? 0;
1344
- const usedCost = aggregate?.usage.cost.total ?? 0;
1345
- if (remainingWallTimeMs !== undefined && remainingWallTimeMs <= 0) {
1346
- stopForBudget("wall_time_limit", `Child thread exceeds ${wallTimeMs} ms`);
1347
- break;
1348
- }
1349
- if (limits.traceBytes !== undefined && usedTraceBytes >= limits.traceBytes) {
1350
- stopForBudget("trace_limit", `Child thread retains more than ${limits.traceBytes} trace bytes`);
1351
- break;
1352
- }
1353
- if (limits.stderrBytes !== undefined && usedStderrBytes >= limits.stderrBytes) {
1354
- stopForBudget("stderr_limit", `Child thread emits more than ${limits.stderrBytes} stderr bytes`);
1355
- break;
1356
- }
1357
- if (limits.taskOutputBytes !== undefined && usedOutputBytes >= limits.taskOutputBytes) {
1358
- stopForBudget("output_limit", `Child thread emits more than ${limits.taskOutputBytes} output bytes`);
1359
- break;
1360
- }
1361
- if (limits.quotaTokens !== undefined && usedTokens >= limits.quotaTokens) {
1362
- stopForBudget("quota_tokens", `Child thread exceeds ${limits.quotaTokens} tokens`);
1363
- break;
1364
- }
1365
- if (limits.quotaUsd !== undefined && usedCost >= limits.quotaUsd) {
1366
- stopForBudget("quota_cost", `Child thread exceeds $${limits.quotaUsd}`);
1367
- break;
1368
- }
1369
- runtime.traceCount = 0;
1370
- const next = await runTask({
1371
- cwd: ctx.cwd,
1372
- agent: roles.get(input.agent)!,
1373
- task: currentTask,
1374
- id: results[index]!.id,
1375
- step: results[index]!.step,
1376
- model: resolvedModels.get(input.agent)!,
1377
- signal: controller.signal,
1378
- webExtension: options.webExtension,
1379
- projectTrusted: ctx.isProjectTrusted(),
1380
- spawnProcess,
1381
- sessionDirectory,
1382
- sessionId,
1383
- limits: {
1384
- ...limits,
1385
- ...(limits.traceBytes === undefined ? {} : { traceBytes: limits.traceBytes - usedTraceBytes }),
1386
- ...(limits.stderrBytes === undefined ? {} : { stderrBytes: limits.stderrBytes - usedStderrBytes }),
1387
- ...(limits.taskOutputBytes === undefined ? {} : { taskOutputBytes: limits.taskOutputBytes - usedOutputBytes }),
1388
- ...(limits.quotaTokens === undefined ? {} : { quotaTokens: limits.quotaTokens - usedTokens }),
1389
- ...(limits.quotaUsd === undefined ? {} : { quotaUsd: limits.quotaUsd - usedCost }),
1390
- },
1391
- timeoutMs: remainingWallTimeMs,
1392
- onHandle: (handle) => {
1393
- runtime.handle = handle;
1394
- runtime.handles.add(handle);
1395
- },
1396
- onChange: (changed) => {
1397
- results[index] = syncThread(threadId, changed, runtime);
1398
- emit();
1399
- },
1400
- });
1401
- next.task = task;
1402
- runtime.aggregate = mergeTaskResults(runtime.aggregate, next, limits.traceRetentionBytes, limits.stderrRetentionBytes);
1403
- runtime.aggregate.task = task;
1404
- results[index] = cloneResult(runtime.aggregate);
1405
- savedResults.set(threadId, cloneResult(runtime.aggregate));
1406
- const shouldRestart = runtime.steering.length > 0 && !controller.signal.aborted && (runtime.restarting || next.status === "complete" || next.status === "cancelled");
1407
- if (!shouldRestart) break;
1408
- const previousHandle = runtime.handle;
1409
- if (previousHandle && !(await waitForConfirmedProcessExit(previousHandle))) break;
1410
- if (controller.signal.aborted || threads.isDisposed) break;
1411
- const steering = runtime.steering.splice(0);
1412
- runtime.restarting = false;
1413
- runtime.requestedReason = undefined;
1414
- if (!threads.isDisposed && threads.inspect(threadId)?.state === "active") {
1415
- threads.patch(threadId, {
1416
- usage: threadUsage(runtime.aggregate.usage),
1417
- result: runtime.aggregate.output || undefined,
1418
- handoff: runtime.aggregate.output ? { summary: runtime.aggregate.output } : undefined,
1419
- });
1420
- }
1421
- currentTask = buildSteeredTask(task, steering, limits.taskCharacters);
1422
- }
1423
- } finally {
1424
- activeRuntimes.delete(threadId);
1425
- const removeSessionDirectory = async (): Promise<void> => {
1426
- try {
1427
- await rm(sessionDirectory, { recursive: true, force: true });
1428
- } catch {
1429
- // Temporary child session cleanup is best effort after process termination.
1430
- }
1431
- };
1432
- const pendingExits = [...runtime.handles]
1433
- .filter((handle) => !handle.hasExited)
1434
- .map((handle) => handle.exited);
1435
- if (!pendingExits.length) await removeSessionDirectory();
1436
- else void Promise.all(pendingExits).then(removeSessionDirectory);
1437
- }
1438
- emit();
1439
- };
1440
-
1441
- const settleQueued = (reason: string): void => {
1442
- for (let index = 0; index < results.length; index += 1) {
1443
- const result = results[index]!;
1444
- if (result.status !== "queued") continue;
1445
- const thread = threads.inspect(threadRecords[index]!.id);
1446
- const alreadyStopped = thread?.state === "stopped";
1447
- result.status = signal?.aborted || alreadyStopped ? "cancelled" : "failed";
1448
- result.terminationReason = alreadyStopped
1449
- ? thread.stopReason ?? "interrupted"
1450
- : signal?.aborted ? "abort" : reason;
1451
- if (thread?.state === "queued" || thread?.state === "active") {
1452
- threads.stop(threadRecords[index]!.id, { reason: result.terminationReason });
1453
- }
1454
- savedResults.set(threadRecords[index]!.id, cloneResult(result));
1455
- }
1456
- };
1457
-
1458
- emit(`${mode}: ${results.length} queued`);
1459
- if (hasChain) {
1460
- let previous = "";
1461
- for (let index = 0; index < inputs.length; index += 1) {
1462
- const task = inputs[index]!.task.replaceAll("{previous}", previous);
1463
- await runAt(index, task);
1464
- if (results[index]!.status !== "complete") break;
1465
- previous = results[index]!.output;
1466
- }
1467
- settleQueued("chain_stopped");
1468
- } else if (hasParallel) {
1469
- try {
1470
- if (useSharedParallelPool) {
1471
- const indexes = inputs.map((_, index) => index);
1472
- await mapReadTasks(indexes, writerConcurrency, async (index) => runAt(index, inputs[index]!.task));
1473
- } else {
1474
- await mapReadTasks(readIndexes, limits.maxReadConcurrency, async ({ index }) => runAt(index, inputs[index]!.task));
1475
- for (const index of writerIndexes) await runAt(index, inputs[index]!.task);
1476
- }
1477
- } finally {
1478
- settleQueued("parallel_stopped");
1479
- }
1480
- } else {
1481
- await runAt(0, inputs[0]!.task);
1482
- }
1483
-
1484
- const board = detailsFor(parentId, mode, scope, discovery.projectAgentsDir);
1485
- const currentResults = results.map(cloneResult);
1486
- const details: SubagentDetails = { ...board, executionNote, results: currentResults, aggregateUsage: aggregateUsage(currentResults) };
1487
- return {
1488
- content: [{ type: "text", text: buildToolContent(mode, details.results, limits.toolOutputBytes) }],
1489
- details,
1490
- usage: details.aggregateUsage,
1491
- };
1492
- },
1493
-
1494
- renderCall(args, theme) {
1495
- const scope = args.agentScope ?? "user";
1496
- if (args.action && args.action !== "spawn") return new Text(`${theme.fg("toolTitle", theme.bold("threads "))}${theme.fg("accent", args.action)}${theme.fg("dim", args.threadId ? ` · ${args.threadId}` : "")}`, 0, 0);
1497
- if (args.tasks?.length) {
1498
- const schedule = args.writerConcurrency === undefined ? "parallel default" : `shared pool ${args.writerConcurrency}`;
1499
- return new Text(`${theme.fg("toolTitle", theme.bold("subagents "))}${theme.fg("accent", `parallel ${args.tasks.length} · ${schedule}`)}${theme.fg("dim", ` · ${scope}`)}`, 0, 0);
1500
- }
1501
- if (args.chain?.length) return new Text(`${theme.fg("toolTitle", theme.bold("subagents "))}${theme.fg("accent", `chain ${args.chain.length}`)}${theme.fg("dim", ` · ${scope}`)}`, 0, 0);
1502
- return new Text(`${theme.fg("toolTitle", theme.bold("subagent "))}${theme.fg("accent", args.agent ?? "…")}${theme.fg("dim", ` · ${scope}`)}`, 0, 0);
1503
- },
1504
-
1505
- renderResult(result, { expanded }, theme) {
1506
- const details = result.details as SubagentDetails | undefined;
1507
- if (!details?.results.length) {
1508
- const first = result.content[0];
1509
- return new Text(first?.type === "text" ? first.text : "(no output)", 0, 0);
1510
- }
1511
- const board = formatThreadBoard({
1512
- title: `Subagents · ${details.mode}`,
1513
- threads: details.results.map(threadBoardRecord),
1514
- selectedThreadId: details.selectedThreadId,
1515
- });
1516
- if (!expanded) {
1517
- const lines = [
1518
- theme.fg("toolTitle", theme.bold(`Active (${board.active.length})`)),
1519
- ...board.active.map((task) => `${theme.fg("accent", "✻")} ${theme.fg("toolTitle", theme.bold(task.agent))}${theme.fg("dim", ` · ${task.id} · ${task.state.label} · ${task.usage.text}`)}`),
1520
- theme.fg("toolTitle", theme.bold(`Done (${board.done.length})`)),
1521
- ...board.done.map((task) => `${theme.fg(task.state.status === "complete" ? "success" : "warning", `${task.state.label}`)} ${theme.fg("toolTitle", theme.bold(task.agent))}${theme.fg("dim", ` · ${task.id} · ${task.usage.text}`)}`),
1522
- ];
1523
- if (details.executionNote) lines.push(theme.fg("dim", details.executionNote));
1524
- lines.push(theme.fg("dim", `Total · ${formatUsage(details.aggregateUsage)} · Ctrl+O to expand`));
1525
- return new Text(lines.join("\n"), 0, 0);
1526
- }
1527
-
1528
- const container = new Container();
1529
- container.addChild(new Text(theme.fg("toolTitle", theme.bold(`Subagents · ${details.mode}`)), 0, 0));
1530
- container.addChild(new Text(theme.fg("dim", `Active ${board.active.length} · Done ${board.done.length} · Controls: Inspect · Steer · Interrupt · Collect · Close`), 0, 0));
1531
- if (details.executionNote) container.addChild(new Text(theme.fg("dim", details.executionNote), 0, 0));
1532
- if (board.selected) {
1533
- const inspection = formatThreadInspection(threadBoardRecord(details.results.find((task) => task.id === board.selected!.id)!));
1534
- container.addChild(new Spacer(1));
1535
- container.addChild(new Text(theme.fg("accent", `Inspect ${inspection.id} · ${inspection.state.label} · ${inspection.usage.text}`), 0, 0));
1536
- for (const entry of inspection.trace.entries) container.addChild(new Text(`${theme.fg("muted", "→ ")}${theme.fg("toolOutput", entry)}`, 0, 0));
1537
- }
1538
- for (const task of details.results) {
1539
- container.addChild(new Spacer(1));
1540
- const status = theme.fg(statusColor(task.status), `${statusIcon(task.status)} ${task.status}`);
1541
- container.addChild(new Text(`${status} ${theme.fg("accent", task.agent)}${theme.fg("dim", ` · ${task.id} · ${task.agentSource}`)}`, 0, 0));
1542
- container.addChild(new Text(theme.fg("dim", `${task.model ?? "no model"} · ${task.thinking ?? "off"} · ${task.tools.join(", ")} · ${formatUsage(task.usage)} · ${task.durationMs}ms`), 0, 0));
1543
- container.addChild(new Text(theme.fg("muted", `Task: ${task.task}`), 0, 0));
1544
- for (const entry of task.trace) container.addChild(new Text(`${theme.fg("muted", "→ ")}${theme.fg("toolOutput", entry)}`, 0, 0));
1545
- if (task.traceTruncatedBytes || task.stderrTruncatedBytes || task.outputTruncatedBytes) {
1546
- container.addChild(new Text(theme.fg("warning", `Truncated · trace ${task.traceTruncatedBytes} B · stderr ${task.stderrTruncatedBytes} B · output ${task.outputTruncatedBytes} B`), 0, 0));
1547
- }
1548
- if (task.output) container.addChild(new Markdown(task.output, 0, 0, getMarkdownTheme()));
1549
- else if (task.errorMessage || task.stderr) container.addChild(new Text(theme.fg("error", task.errorMessage || task.stderr), 0, 0));
1550
- }
1551
- container.addChild(new Spacer(1));
1552
- container.addChild(new Text(theme.fg("dim", `Total · ${formatUsage(details.aggregateUsage)}`), 0, 0));
1553
- return container;
1554
- },
1555
- });
1556
- }
1
+ export * from "./killeros/subagents.ts";