pi-subagents 0.32.0 → 0.33.1

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +34 -2
  2. package/README.md +147 -58
  3. package/install.mjs +2 -1
  4. package/package.json +3 -2
  5. package/skills/pi-subagents/SKILL.md +75 -17
  6. package/src/agents/agent-management.ts +177 -5
  7. package/src/agents/agent-memory.ts +254 -0
  8. package/src/agents/agent-serializer.ts +11 -0
  9. package/src/agents/agents.ts +142 -12
  10. package/src/agents/chain-serializer.ts +27 -2
  11. package/src/extension/doctor.ts +1 -9
  12. package/src/extension/fanout-child.ts +2 -2
  13. package/src/extension/index.ts +65 -90
  14. package/src/extension/rpc.ts +369 -0
  15. package/src/extension/schemas.ts +52 -8
  16. package/src/extension/tool-description.ts +200 -0
  17. package/src/intercom/intercom-bridge.ts +21 -253
  18. package/src/intercom/native-supervisor-channel.ts +519 -0
  19. package/src/runs/background/async-execution.ts +51 -7
  20. package/src/runs/background/async-job-tracker.ts +12 -2
  21. package/src/runs/background/async-status.ts +27 -2
  22. package/src/runs/background/completion-batcher.ts +166 -0
  23. package/src/runs/background/control-channel.ts +106 -1
  24. package/src/runs/background/fleet-view.ts +515 -0
  25. package/src/runs/background/notify.ts +161 -44
  26. package/src/runs/background/result-watcher.ts +1 -2
  27. package/src/runs/background/run-id-resolver.ts +3 -2
  28. package/src/runs/background/run-status.ts +166 -6
  29. package/src/runs/background/scheduled-runs.ts +514 -0
  30. package/src/runs/background/subagent-runner.ts +409 -35
  31. package/src/runs/background/wait.ts +353 -0
  32. package/src/runs/foreground/chain-execution.ts +95 -21
  33. package/src/runs/foreground/execution.ts +150 -21
  34. package/src/runs/foreground/subagent-executor.ts +378 -64
  35. package/src/runs/shared/dynamic-fanout.ts +1 -1
  36. package/src/runs/shared/model-fallback.ts +167 -20
  37. package/src/runs/shared/model-scope.ts +128 -0
  38. package/src/runs/shared/nested-events.ts +31 -0
  39. package/src/runs/shared/parallel-utils.ts +1 -0
  40. package/src/runs/shared/pi-args.ts +30 -1
  41. package/src/runs/shared/subagent-prompt-runtime.ts +123 -3
  42. package/src/runs/shared/tool-budget.ts +74 -0
  43. package/src/runs/shared/turn-budget.ts +52 -0
  44. package/src/shared/artifacts.ts +1 -0
  45. package/src/shared/atomic-json.ts +15 -2
  46. package/src/shared/child-transcript.ts +212 -0
  47. package/src/shared/settings.ts +3 -1
  48. package/src/shared/types.ts +134 -19
  49. package/src/slash/prompt-workflows.ts +330 -0
  50. package/src/slash/slash-commands.ts +16 -2
  51. package/src/tui/render.ts +16 -8
  52. package/src/extension/companion-suggestions.ts +0 -359
@@ -1,9 +1,12 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
- import { SUBAGENT_FANOUT_CHILD_ENV } from "./pi-args.ts";
4
+ import { registerNativeSupervisorClient } from "../../intercom/native-supervisor-channel.ts";
5
+ import { consumeSteerRequestsFromDir, writeSteerRequestToDir, type SteerRequest } from "../background/control-channel.ts";
6
+ import { SUBAGENT_FANOUT_CHILD_ENV, SUBAGENT_STEER_INBOX_ENV } from "./pi-args.ts";
5
7
  import { STRUCTURED_OUTPUT_CAPTURE_ENV, STRUCTURED_OUTPUT_SCHEMA_ENV, validateStructuredOutputValue } from "./structured-output.ts";
6
- import type { JsonSchemaObject } from "../../shared/types.ts";
8
+ import { TOOL_BUDGET_ENV, decodeToolBudgetEnv, shouldBlockToolForBudget, toolBudgetBlockedMessage, toolBudgetSoftNudge } from "./tool-budget.ts";
9
+ import type { JsonSchemaObject, ResolvedToolBudget } from "../../shared/types.ts";
7
10
 
8
11
  const SUBAGENT_INHERIT_PROJECT_CONTEXT_ENV = "PI_SUBAGENT_INHERIT_PROJECT_CONTEXT";
9
12
  const SUBAGENT_INHERIT_SKILLS_ENV = "PI_SUBAGENT_INHERIT_SKILLS";
@@ -155,7 +158,124 @@ export function stripParentOnlySubagentMessages(messages: unknown[]): unknown[]
155
158
  return changed ? filtered : messages;
156
159
  }
157
160
 
161
+ export function formatSteerMessage(request: SteerRequest): string {
162
+ return [
163
+ "Mid-run steering from the parent orchestrator:",
164
+ "",
165
+ request.message,
166
+ "",
167
+ "Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.",
168
+ ].join("\n");
169
+ }
170
+
171
+ function registerToolBudget(pi: ExtensionAPI, budget: ResolvedToolBudget | undefined): void {
172
+ if (!budget) return;
173
+ let toolCount = 0;
174
+ let softNudged = false;
175
+ const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: "steer" }) => unknown }).sendUserMessage;
176
+ const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: { toolName?: string }) => unknown) => void;
177
+ onRuntimeEvent("tool_call", (event) => {
178
+ const toolName = typeof event.toolName === "string" ? event.toolName : "tool";
179
+ toolCount++;
180
+ if (budget.soft !== undefined && toolCount >= budget.soft && !softNudged) {
181
+ softNudged = true;
182
+ try {
183
+ sendUserMessage?.(toolBudgetSoftNudge(budget, toolCount), { deliverAs: "steer" });
184
+ } catch {
185
+ // Budget nudges are advisory; blocking below remains authoritative.
186
+ }
187
+ }
188
+ if (!shouldBlockToolForBudget(budget, toolName, toolCount)) return undefined;
189
+ return { block: true, reason: toolBudgetBlockedMessage(budget, toolName, toolCount) };
190
+ });
191
+ }
192
+
193
+ function registerSteeringInbox(pi: ExtensionAPI): void {
194
+ const steerInbox = process.env[SUBAGENT_STEER_INBOX_ENV]?.trim();
195
+ if (!steerInbox) return;
196
+ const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: "steer" }) => unknown }).sendUserMessage;
197
+ if (typeof sendUserMessage !== "function") return;
198
+
199
+ let canSteer = false;
200
+ let disposed = false;
201
+ let flushing = false;
202
+ let started = false;
203
+ let watcher: fs.FSWatcher | undefined;
204
+ let interval: NodeJS.Timeout | undefined;
205
+ const flush = (): void => {
206
+ if (disposed || flushing || !canSteer) return;
207
+ flushing = true;
208
+ try {
209
+ const requests = consumeSteerRequestsFromDir(steerInbox);
210
+ for (let index = 0; index < requests.length; index++) {
211
+ const request = requests[index]!;
212
+ try {
213
+ sendUserMessage(formatSteerMessage(request), { deliverAs: "steer" });
214
+ } catch {
215
+ for (const pending of requests.slice(index)) writeSteerRequestToDir(steerInbox, pending);
216
+ break;
217
+ }
218
+ }
219
+ } finally {
220
+ flushing = false;
221
+ }
222
+ };
223
+ const start = (): void => {
224
+ if (started || disposed) return;
225
+ try {
226
+ fs.mkdirSync(steerInbox, { recursive: true });
227
+ } catch {
228
+ return;
229
+ }
230
+ started = true;
231
+ try {
232
+ watcher = fs.watch(steerInbox, () => flush());
233
+ watcher.on("error", () => {});
234
+ } catch {
235
+ watcher = undefined;
236
+ }
237
+ interval = setInterval(flush, 250);
238
+ interval.unref?.();
239
+ };
240
+ const activate = (): undefined => {
241
+ start();
242
+ canSteer = true;
243
+ flush();
244
+ return undefined;
245
+ };
246
+
247
+ const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown) => unknown) => void;
248
+ onRuntimeEvent("session_start", () => start());
249
+ for (const eventName of ["message_start", "message_update", "message_end", "tool_execution_start", "tool_execution_end", "turn_end"] as const) {
250
+ onRuntimeEvent(eventName, activate);
251
+ }
252
+ onRuntimeEvent("session_shutdown", () => {
253
+ disposed = true;
254
+ try {
255
+ watcher?.close();
256
+ } catch {}
257
+ if (interval) clearInterval(interval);
258
+ });
259
+ }
260
+
158
261
  export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
262
+ registerSteeringInbox(pi);
263
+ registerToolBudget(pi, decodeToolBudgetEnv(process.env[TOOL_BUDGET_ENV]));
264
+ let nativeSupervisorClientRegistered = false;
265
+ let nativeSupervisorFallbackRegistered = false;
266
+ const registerNativeSupervisorClientOnce = (): void => {
267
+ if (nativeSupervisorClientRegistered) return;
268
+ nativeSupervisorClientRegistered = true;
269
+ registerNativeSupervisorClient(pi, { includeIntercomFallback: false });
270
+ };
271
+ const registerNativeSupervisorFallbackOnce = (): void => {
272
+ registerNativeSupervisorClientOnce();
273
+ if (nativeSupervisorFallbackRegistered) return;
274
+ nativeSupervisorFallbackRegistered = true;
275
+ registerNativeSupervisorClient(pi);
276
+ };
277
+ const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown) => unknown) => void;
278
+ onRuntimeEvent("session_start", registerNativeSupervisorClientOnce);
159
279
  const structuredOutputPath = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV];
160
280
  const structuredSchemaPath = process.env[STRUCTURED_OUTPUT_SCHEMA_ENV];
161
281
  if (structuredOutputPath && structuredSchemaPath) {
@@ -194,7 +314,6 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
194
314
  });
195
315
  }
196
316
 
197
- const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown) => unknown) => void;
198
317
  onRuntimeEvent("context", (event: { messages: unknown[] }) => {
199
318
  const messages = stripParentOnlySubagentMessages(event.messages);
200
319
  if (messages === event.messages) return undefined;
@@ -202,6 +321,7 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
202
321
  });
203
322
 
204
323
  onRuntimeEvent("before_agent_start", async (event: { systemPrompt: string }) => {
324
+ registerNativeSupervisorFallbackOnce();
205
325
  const intercomSessionName = process.env[SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();
206
326
  if (intercomSessionName && typeof pi.setSessionName === "function") {
207
327
  pi.setSessionName(intercomSessionName);
@@ -0,0 +1,74 @@
1
+ import type { ResolvedToolBudget, ToolBudgetConfig, ToolBudgetState } from "../../shared/types.ts";
2
+
3
+ export const DEFAULT_TOOL_BUDGET_BLOCK = ["read", "grep", "find", "ls"] as const;
4
+ export const TOOL_BUDGET_ENV = "PI_SUBAGENT_TOOL_BUDGET";
5
+
6
+ export function normalizeToolBudgetBlock(block: ToolBudgetConfig["block"] | undefined): "*" | string[] {
7
+ if (block === "*") return "*";
8
+ if (block === undefined) return [...DEFAULT_TOOL_BUDGET_BLOCK];
9
+ return [...new Set(block.map((tool) => tool.trim()).filter(Boolean))];
10
+ }
11
+
12
+ export function validateToolBudgetConfig(raw: unknown, label = "toolBudget"): { budget?: ResolvedToolBudget; error?: string } {
13
+ if (raw === undefined) return {};
14
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: `${label} must be an object with hard and optional soft/block.` };
15
+ const value = raw as ToolBudgetConfig;
16
+ if (typeof value.hard !== "number" || !Number.isInteger(value.hard) || value.hard < 1) {
17
+ return { error: `${label}.hard must be an integer >= 1.` };
18
+ }
19
+ if (value.soft !== undefined && (typeof value.soft !== "number" || !Number.isInteger(value.soft) || value.soft < 1)) {
20
+ return { error: `${label}.soft must be an integer >= 1 when provided.` };
21
+ }
22
+ if (value.soft !== undefined && value.soft > value.hard) {
23
+ return { error: `${label}.soft must be <= ${label}.hard.` };
24
+ }
25
+ if (value.block !== undefined && value.block !== "*") {
26
+ if (!Array.isArray(value.block)) return { error: `${label}.block must be "*" or an array of tool names.` };
27
+ if (value.block.length === 0) return { error: `${label}.block must contain at least one tool name.` };
28
+ for (const item of value.block) {
29
+ if (typeof item !== "string" || !item.trim()) return { error: `${label}.block must contain non-empty tool names.` };
30
+ }
31
+ }
32
+ return { budget: { hard: value.hard, ...(value.soft !== undefined ? { soft: value.soft } : {}), block: normalizeToolBudgetBlock(value.block) } };
33
+ }
34
+
35
+ export function initialToolBudgetState(budget: ResolvedToolBudget): ToolBudgetState {
36
+ return { ...budget, toolCount: 0, outcome: "within-budget" };
37
+ }
38
+
39
+ export function toolBudgetState(budget: ResolvedToolBudget, toolCount: number, blockedTool?: string): ToolBudgetState {
40
+ const overHard = toolCount > budget.hard;
41
+ const overSoft = budget.soft !== undefined && toolCount >= budget.soft;
42
+ return {
43
+ ...budget,
44
+ toolCount,
45
+ outcome: overHard ? "hard-blocked" : overSoft ? "soft-reached" : "within-budget",
46
+ ...(overSoft ? { softReachedAt: budget.soft } : {}),
47
+ ...(overHard ? { hardReachedAt: budget.hard, blockedTool } : {}),
48
+ };
49
+ }
50
+
51
+ export function shouldBlockToolForBudget(budget: ResolvedToolBudget, toolName: string, nextToolCount: number): boolean {
52
+ if (nextToolCount <= budget.hard) return false;
53
+ return budget.block === "*" || budget.block.includes(toolName);
54
+ }
55
+
56
+ export function toolBudgetSoftNudge(budget: ResolvedToolBudget, toolCount: number): string {
57
+ return `Tool budget soft limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (soft ${budget.soft}, hard ${budget.hard}). Stop starting new browsing/search work and finalize from the context you already have.`;
58
+ }
59
+
60
+ export function toolBudgetBlockedMessage(budget: ResolvedToolBudget, toolName: string, toolCount: number): string {
61
+ return `Tool budget hard limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (hard ${budget.hard}). The '${toolName}' tool is blocked so you can finalize from the context you already have.`;
62
+ }
63
+
64
+ export function encodeToolBudgetEnv(budget: ResolvedToolBudget | undefined): string | undefined {
65
+ return budget ? JSON.stringify(budget) : undefined;
66
+ }
67
+
68
+ export function decodeToolBudgetEnv(value: string | undefined): ResolvedToolBudget | undefined {
69
+ if (!value?.trim()) return undefined;
70
+ const parsed = JSON.parse(value) as unknown;
71
+ const normalized = validateToolBudgetConfig(parsed, TOOL_BUDGET_ENV);
72
+ if (normalized.error) throw new Error(normalized.error);
73
+ return normalized.budget;
74
+ }
@@ -0,0 +1,52 @@
1
+ import type { ResolvedTurnBudget, TurnBudgetState } from "../../shared/types.ts";
2
+
3
+ export const DEFAULT_TURN_BUDGET_GRACE_TURNS = 1;
4
+
5
+ export function appendTurnBudgetSystemPrompt(systemPrompt: string, budget: ResolvedTurnBudget | undefined): string {
6
+ if (!budget) return systemPrompt;
7
+ const grace = budget.graceTurns === 1 ? "1 additional assistant turn" : `${budget.graceTurns} additional assistant turns`;
8
+ const block = [
9
+ "## Turn budget",
10
+ `This child run has a soft budget of ${budget.maxTurns} assistant turn${budget.maxTurns === 1 ? "" : "s"}.`,
11
+ `After that, ${grace} may be allowed only for a final wrap-up.`,
12
+ "When you approach or reach the soft budget, stop starting new tool work and return the final answer immediately.",
13
+ "This runner uses process-mode execution, so live steering after launch may be unavailable; treat this instruction as the wrap-up request.",
14
+ "If you continue past the soft budget plus grace turns, the supervisor may abort the process and return only partial output.",
15
+ ].join("\n");
16
+ return systemPrompt.trim() ? `${systemPrompt.trim()}\n\n${block}` : block;
17
+ }
18
+
19
+ export function turnBudgetSoftNote(budget: ResolvedTurnBudget, turnCount: number): string {
20
+ return `Turn budget wrap-up was requested after ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns}, grace ${budget.graceTurns}). Process-mode live steering is unavailable, so the child was warned at launch to wrap up by this budget. Output may be partial.`;
21
+ }
22
+
23
+ export function turnBudgetExceededMessage(budget: ResolvedTurnBudget, turnCount: number): string {
24
+ return `Subagent exceeded turn budget after ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns} + grace ${budget.graceTurns}).`;
25
+ }
26
+
27
+ export function formatTurnBudgetOutput(message: string, output: string): string {
28
+ return output.trim()
29
+ ? `${message}\n\nPartial output before turn-budget abort:\n${output}`
30
+ : message;
31
+ }
32
+
33
+ export function initialTurnBudgetState(budget: ResolvedTurnBudget): TurnBudgetState {
34
+ return { ...budget, outcome: "within-budget", turnCount: 0 };
35
+ }
36
+
37
+ export function turnBudgetState(budget: ResolvedTurnBudget, turnCount: number, exceeded: boolean): TurnBudgetState {
38
+ return {
39
+ ...budget,
40
+ turnCount,
41
+ outcome: exceeded ? "exceeded" : "wrap-up-requested",
42
+ wrapUpRequestedAtTurn: budget.maxTurns,
43
+ ...(exceeded ? { exceededAtTurn: turnCount } : {}),
44
+ };
45
+ }
46
+
47
+ export function shouldAbortForTurnBudget(budget: ResolvedTurnBudget, turnCount: number, terminalAssistantStop: boolean): boolean {
48
+ const hardLimit = budget.maxTurns + budget.graceTurns;
49
+ if (turnCount < hardLimit) return false;
50
+ if (turnCount > hardLimit) return true;
51
+ return !terminalAssistantStop;
52
+ }
@@ -34,6 +34,7 @@ export function getArtifactPaths(artifactsDir: string, runId: string, agent: str
34
34
  inputPath: path.join(artifactsDir, `${base}_input.md`),
35
35
  outputPath: path.join(artifactsDir, `${base}_output.md`),
36
36
  jsonlPath: path.join(artifactsDir, `${base}.jsonl`),
37
+ transcriptPath: path.join(artifactsDir, `${base}_transcript.jsonl`),
37
38
  metadataPath: path.join(artifactsDir, `${base}_meta.json`),
38
39
  };
39
40
  }
@@ -13,13 +13,26 @@ type AtomicJsonWriterOptions = {
13
13
  wait?: (delayMs: number) => void;
14
14
  };
15
15
 
16
- const DEFAULT_RENAME_RETRY_DELAYS_MS = [10, 25, 50, 100, 200] as const;
16
+ const DEFAULT_RENAME_RETRY_DELAYS_MS = [10, 25, 50, 100, 200, 500, 1000, 2000, 4000] as const;
17
17
  const RETRYABLE_RENAME_ERROR_CODES = new Set(["EACCES", "EBUSY", "EPERM"]);
18
+ const WAIT_BUFFER = typeof SharedArrayBuffer !== "undefined" ? new SharedArrayBuffer(4) : undefined;
19
+ const WAIT_VIEW = WAIT_BUFFER ? new Int32Array(WAIT_BUFFER) : undefined;
18
20
 
19
21
  function waitSync(delayMs: number): void {
22
+ if (delayMs <= 0) return;
23
+ if (WAIT_VIEW) {
24
+ try {
25
+ // writeAtomicJson is synchronous because callers often update status from sync callbacks.
26
+ // Atomics.wait gives Windows rename locks time to clear without burning CPU.
27
+ Atomics.wait(WAIT_VIEW, 0, 0, delayMs);
28
+ return;
29
+ } catch {
30
+ // Fall through to the portable busy wait below.
31
+ }
32
+ }
20
33
  const end = Date.now() + delayMs;
21
34
  while (Date.now() < end) {
22
- // writeAtomicJson is synchronous because callers often update status from sync callbacks.
35
+ // Portable fallback for runtimes where Atomics.wait is unavailable.
23
36
  }
24
37
  }
25
38
 
@@ -0,0 +1,212 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { Message } from "@earendil-works/pi-ai";
4
+ import { extractTextFromContent, extractToolArgsPreview } from "./utils.ts";
5
+
6
+ export const CHILD_TRANSCRIPT_ARTIFACT_VERSION = 1;
7
+ const DEFAULT_MAX_CHILD_TRANSCRIPT_BYTES = 50 * 1024 * 1024;
8
+
9
+ type ChildTranscriptSource = "foreground" | "async";
10
+ type ChildTranscriptRecordType = "message" | "tool_start" | "tool_end" | "stdout" | "stderr" | "truncated";
11
+
12
+ type ChildTranscriptMessage = Message & {
13
+ model?: string;
14
+ errorMessage?: string;
15
+ stopReason?: string;
16
+ usage?: unknown;
17
+ };
18
+
19
+ interface ChildTranscriptEvent {
20
+ type?: string;
21
+ message?: ChildTranscriptMessage;
22
+ toolName?: string;
23
+ args?: unknown;
24
+ }
25
+
26
+ interface ChildTranscriptWriterInput {
27
+ transcriptPath: string;
28
+ source: ChildTranscriptSource;
29
+ runId: string;
30
+ agent: string;
31
+ childIndex?: number;
32
+ cwd: string;
33
+ maxBytes?: number;
34
+ }
35
+
36
+ export interface ChildTranscriptWriter {
37
+ path: string;
38
+ writeInitialUserMessage(prompt: string): void;
39
+ writeChildEvent(event: ChildTranscriptEvent): void;
40
+ writeStdoutLine(line: string): void;
41
+ writeStderrLine(line: string): void;
42
+ writeStderrText(text: string): void;
43
+ getError(): string | undefined;
44
+ }
45
+
46
+ function errorMessage(error: unknown): string {
47
+ return error instanceof Error ? error.message : String(error);
48
+ }
49
+
50
+ function finiteNumber(value: unknown): number | undefined {
51
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
52
+ }
53
+
54
+ function normalizeUsage(value: unknown): { input: number; output: number; cacheRead: number; cacheWrite: number; cost: number } | undefined {
55
+ if (!value || typeof value !== "object") return undefined;
56
+ const raw = value as Record<string, unknown>;
57
+ const rawCost = raw.cost;
58
+ const cost = rawCost && typeof rawCost === "object"
59
+ ? finiteNumber((rawCost as { total?: unknown }).total) ?? 0
60
+ : finiteNumber(rawCost) ?? 0;
61
+ return {
62
+ input: finiteNumber(raw.input) ?? finiteNumber(raw.inputTokens) ?? 0,
63
+ output: finiteNumber(raw.output) ?? finiteNumber(raw.outputTokens) ?? 0,
64
+ cacheRead: finiteNumber(raw.cacheRead) ?? 0,
65
+ cacheWrite: finiteNumber(raw.cacheWrite) ?? 0,
66
+ cost,
67
+ };
68
+ }
69
+
70
+ function eventArgs(event: ChildTranscriptEvent): Record<string, unknown> {
71
+ return event.args && typeof event.args === "object" && !Array.isArray(event.args)
72
+ ? event.args as Record<string, unknown>
73
+ : {};
74
+ }
75
+
76
+ export function createChildTranscriptWriter(input: ChildTranscriptWriterInput): ChildTranscriptWriter {
77
+ let bytesWritten = 0;
78
+ let writeError: string | undefined;
79
+ let truncated = false;
80
+ const maxBytes = input.maxBytes ?? DEFAULT_MAX_CHILD_TRANSCRIPT_BYTES;
81
+
82
+ const baseRecord = (recordType: ChildTranscriptRecordType) => {
83
+ const ts = Date.now();
84
+ return {
85
+ version: CHILD_TRANSCRIPT_ARTIFACT_VERSION,
86
+ recordType,
87
+ source: input.source,
88
+ runId: input.runId,
89
+ agent: input.agent,
90
+ ...(input.childIndex !== undefined ? { childIndex: input.childIndex } : {}),
91
+ cwd: input.cwd,
92
+ ts,
93
+ timestamp: new Date(ts).toISOString(),
94
+ };
95
+ };
96
+
97
+ const writeTruncatedMarker = () => {
98
+ truncated = true;
99
+ const marker = `${JSON.stringify({
100
+ ...baseRecord("truncated"),
101
+ maxBytes,
102
+ message: `Child transcript exceeded ${maxBytes} bytes; further records were omitted.`,
103
+ })}\n`;
104
+ const markerBytes = Buffer.byteLength(marker, "utf-8");
105
+ if (bytesWritten + markerBytes > maxBytes) return false;
106
+ try {
107
+ fs.appendFileSync(input.transcriptPath, marker, "utf-8");
108
+ bytesWritten += markerBytes;
109
+ return true;
110
+ } catch (error) {
111
+ writeError = `Failed to write child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
112
+ return false;
113
+ }
114
+ };
115
+
116
+ const writeRecord = (record: Record<string, unknown>) => {
117
+ if (writeError || truncated) return;
118
+ const line = `${JSON.stringify(record)}\n`;
119
+ const bytes = Buffer.byteLength(line, "utf-8");
120
+ if (bytesWritten + bytes > maxBytes) {
121
+ writeTruncatedMarker();
122
+ return;
123
+ }
124
+ const markerProbe = `${JSON.stringify({
125
+ ...baseRecord("truncated"),
126
+ maxBytes,
127
+ message: `Child transcript exceeded ${maxBytes} bytes; further records were omitted.`,
128
+ })}\n`;
129
+ if (bytesWritten + bytes + Buffer.byteLength(markerProbe, "utf-8") > maxBytes) {
130
+ writeTruncatedMarker();
131
+ return;
132
+ }
133
+ try {
134
+ fs.appendFileSync(input.transcriptPath, line, "utf-8");
135
+ bytesWritten += bytes;
136
+ } catch (error) {
137
+ writeError = `Failed to write child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
138
+ }
139
+ };
140
+
141
+ try {
142
+ fs.mkdirSync(path.dirname(input.transcriptPath), { recursive: true });
143
+ fs.writeFileSync(input.transcriptPath, "", "utf-8");
144
+ } catch (error) {
145
+ writeError = `Failed to initialize child transcript '${input.transcriptPath}': ${errorMessage(error)}`;
146
+ }
147
+
148
+ const writeMessage = (sourceEventType: string, message: ChildTranscriptMessage) => {
149
+ const text = extractTextFromContent(message.content);
150
+ writeRecord({
151
+ ...baseRecord("message"),
152
+ sourceEventType,
153
+ role: message.role,
154
+ ...(text ? { text } : {}),
155
+ ...(message.model ? { model: message.model } : {}),
156
+ ...(message.stopReason ? { stopReason: message.stopReason } : {}),
157
+ ...(message.errorMessage ? { errorMessage: message.errorMessage } : {}),
158
+ ...(message.usage ? { usage: normalizeUsage(message.usage) } : {}),
159
+ message,
160
+ });
161
+ };
162
+
163
+ return {
164
+ path: input.transcriptPath,
165
+ writeInitialUserMessage(prompt: string) {
166
+ writeRecord({
167
+ ...baseRecord("message"),
168
+ sourceEventType: "initial_prompt",
169
+ role: "user",
170
+ text: prompt,
171
+ message: { role: "user", content: [{ type: "text", text: prompt }] },
172
+ });
173
+ },
174
+ writeChildEvent(event: ChildTranscriptEvent) {
175
+ if ((event.type === "message_end" || event.type === "tool_result_end") && event.message) {
176
+ writeMessage(event.type, event.message);
177
+ return;
178
+ }
179
+ if (event.type === "tool_execution_start" && event.toolName) {
180
+ const args = eventArgs(event);
181
+ writeRecord({
182
+ ...baseRecord("tool_start"),
183
+ sourceEventType: event.type,
184
+ toolName: event.toolName,
185
+ ...(Object.keys(args).length > 0 ? { argsPreview: extractToolArgsPreview(args) } : {}),
186
+ });
187
+ return;
188
+ }
189
+ if (event.type === "tool_execution_end") {
190
+ writeRecord({
191
+ ...baseRecord("tool_end"),
192
+ sourceEventType: event.type,
193
+ ...(event.toolName ? { toolName: event.toolName } : {}),
194
+ });
195
+ }
196
+ },
197
+ writeStdoutLine(line: string) {
198
+ if (!line.trim()) return;
199
+ writeRecord({ ...baseRecord("stdout"), text: line });
200
+ },
201
+ writeStderrLine(line: string) {
202
+ if (!line.trim()) return;
203
+ writeRecord({ ...baseRecord("stderr"), text: line });
204
+ },
205
+ writeStderrText(text: string) {
206
+ for (const line of text.split(/\r?\n/)) this.writeStderrLine(line);
207
+ },
208
+ getError() {
209
+ return writeError;
210
+ },
211
+ };
212
+ }
@@ -6,7 +6,7 @@ import * as fs from "node:fs";
6
6
  import * as path from "node:path";
7
7
  import type { AgentConfig } from "../agents/agents.ts";
8
8
  import { normalizeSkillInput } from "../agents/skills.ts";
9
- import { CHAIN_RUNS_DIR, type AcceptanceInput, type JsonSchemaObject, type OutputMode } from "./types.ts";
9
+ import { CHAIN_RUNS_DIR, type AcceptanceInput, type JsonSchemaObject, type OutputMode, type ToolBudgetConfig } from "./types.ts";
10
10
  const CHAIN_DIR_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours
11
11
  const INITIAL_PROGRESS_CONTENT = "# Progress\n\n## Status\nIn Progress\n\n## Tasks\n\n## Files Changed\n\n## Notes\n";
12
12
 
@@ -55,6 +55,7 @@ export interface SequentialStep {
55
55
  progress?: boolean;
56
56
  skill?: string | string[] | false;
57
57
  model?: string;
58
+ toolBudget?: ToolBudgetConfig;
58
59
  acceptance?: AcceptanceInput;
59
60
  }
60
61
 
@@ -74,6 +75,7 @@ export interface ParallelTaskItem {
74
75
  progress?: boolean;
75
76
  skill?: string | string[] | false;
76
77
  model?: string;
78
+ toolBudget?: ToolBudgetConfig;
77
79
  acceptance?: AcceptanceInput;
78
80
  }
79
81