pi-subagents 0.31.1 → 0.33.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +219 -40
  3. package/install.mjs +2 -1
  4. package/package.json +3 -2
  5. package/skills/pi-subagents/SKILL.md +71 -10
  6. package/src/agents/agent-management.ts +179 -2
  7. package/src/agents/agent-memory.ts +254 -0
  8. package/src/agents/agent-serializer.ts +11 -0
  9. package/src/agents/agents.ts +193 -19
  10. package/src/agents/chain-serializer.ts +27 -2
  11. package/src/extension/config.ts +27 -4
  12. package/src/extension/doctor.ts +1 -7
  13. package/src/extension/fanout-child.ts +3 -2
  14. package/src/extension/index.ts +70 -41
  15. package/src/extension/rpc.ts +369 -0
  16. package/src/extension/schemas.ts +54 -10
  17. package/src/extension/tool-description.ts +200 -0
  18. package/src/intercom/intercom-bridge.ts +21 -253
  19. package/src/intercom/native-supervisor-channel.ts +510 -0
  20. package/src/runs/background/async-execution.ts +187 -38
  21. package/src/runs/background/async-job-tracker.ts +88 -2
  22. package/src/runs/background/async-status.ts +67 -10
  23. package/src/runs/background/chain-root-attachment.ts +34 -4
  24. package/src/runs/background/completion-batcher.ts +166 -0
  25. package/src/runs/background/control-channel.ts +156 -1
  26. package/src/runs/background/fleet-view.ts +515 -0
  27. package/src/runs/background/notify.ts +161 -44
  28. package/src/runs/background/result-watcher.ts +1 -2
  29. package/src/runs/background/run-id-resolver.ts +3 -2
  30. package/src/runs/background/run-status.ts +167 -6
  31. package/src/runs/background/scheduled-runs.ts +514 -0
  32. package/src/runs/background/stale-run-reconciler.ts +28 -1
  33. package/src/runs/background/subagent-runner.ts +840 -127
  34. package/src/runs/background/wait.ts +353 -0
  35. package/src/runs/foreground/chain-execution.ts +123 -27
  36. package/src/runs/foreground/execution.ts +174 -27
  37. package/src/runs/foreground/subagent-executor.ts +569 -81
  38. package/src/runs/shared/acceptance.ts +45 -22
  39. package/src/runs/shared/dynamic-fanout.ts +2 -2
  40. package/src/runs/shared/model-fallback.ts +171 -20
  41. package/src/runs/shared/model-scope.ts +128 -0
  42. package/src/runs/shared/nested-events.ts +89 -0
  43. package/src/runs/shared/parallel-utils.ts +50 -1
  44. package/src/runs/shared/pi-args.ts +35 -4
  45. package/src/runs/shared/pi-spawn.ts +52 -20
  46. package/src/runs/shared/single-output.ts +2 -0
  47. package/src/runs/shared/subagent-prompt-runtime.ts +110 -4
  48. package/src/runs/shared/tool-budget.ts +74 -0
  49. package/src/runs/shared/turn-budget.ts +52 -0
  50. package/src/runs/shared/worktree.ts +28 -5
  51. package/src/shared/artifacts.ts +16 -1
  52. package/src/shared/atomic-json.ts +15 -2
  53. package/src/shared/child-transcript.ts +212 -0
  54. package/src/shared/fork-context.ts +133 -22
  55. package/src/shared/settings.ts +3 -1
  56. package/src/shared/types.ts +197 -4
  57. package/src/shared/utils.ts +99 -14
  58. package/src/slash/prompt-workflows.ts +330 -0
  59. package/src/slash/slash-commands.ts +133 -2
  60. package/src/tui/render.ts +32 -12
@@ -3,8 +3,22 @@ import * as path from "node:path";
3
3
  import { TEMP_ARTIFACTS_DIR, type ArtifactPaths } from "./types.ts";
4
4
  import { getAgentDir } from "./utils.ts";
5
5
  const CLEANUP_MARKER_FILE = ".last-cleanup";
6
+ const PROJECT_ARTIFACT_ROOT = ".pi-subagents";
6
7
 
7
- export function getArtifactsDir(sessionFile: string | null): string {
8
+ export function getProjectSubagentsDir(cwd: string): string {
9
+ return path.join(cwd, PROJECT_ARTIFACT_ROOT);
10
+ }
11
+
12
+ export function getProjectArtifactsDir(cwd: string): string {
13
+ return path.join(getProjectSubagentsDir(cwd), "artifacts");
14
+ }
15
+
16
+ export function getProjectChainRunsDir(cwd: string): string {
17
+ return path.join(getProjectSubagentsDir(cwd), "chain-runs");
18
+ }
19
+
20
+ export function getArtifactsDir(sessionFile: string | null, projectCwd?: string): string {
21
+ if (projectCwd) return getProjectArtifactsDir(projectCwd);
8
22
  if (sessionFile) {
9
23
  const sessionDir = path.dirname(sessionFile);
10
24
  return path.join(sessionDir, "subagent-artifacts");
@@ -20,6 +34,7 @@ export function getArtifactPaths(artifactsDir: string, runId: string, agent: str
20
34
  inputPath: path.join(artifactsDir, `${base}_input.md`),
21
35
  outputPath: path.join(artifactsDir, `${base}_output.md`),
22
36
  jsonlPath: path.join(artifactsDir, `${base}.jsonl`),
37
+ transcriptPath: path.join(artifactsDir, `${base}_transcript.jsonl`),
23
38
  metadataPath: path.join(artifactsDir, `${base}_meta.json`),
24
39
  };
25
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
+ }
@@ -1,27 +1,115 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import * as fs from "node:fs";
3
+ import * as path from "node:path";
2
4
  import { SessionManager } from "@earendil-works/pi-coding-agent";
3
5
 
4
6
  type SubagentExecutionContext = "fresh" | "fork";
5
7
 
8
+ interface BranchSessionEntry {
9
+ type: string;
10
+ id?: string;
11
+ parentId?: string | null;
12
+ timestamp?: string;
13
+ message?: {
14
+ role?: string;
15
+ content?: unknown;
16
+ provider?: string;
17
+ api?: string;
18
+ model?: string;
19
+ };
20
+ thinkingLevel?: string;
21
+ }
22
+
23
+ interface BranchSessionManager {
24
+ createBranchedSession(leafId: string): string | undefined;
25
+ getHeader?: () => BranchSessionEntry | null;
26
+ getEntries?: () => BranchSessionEntry[];
27
+ }
28
+
6
29
  interface ForkableSessionManager {
7
30
  getSessionFile(): string | undefined;
8
31
  getLeafId(): string | null;
9
32
  getSessionDir?(): string;
10
- openSession?: (path: string, sessionDir?: string) => { createBranchedSession(leafId: string): string | undefined };
33
+ openSession?: (path: string, sessionDir?: string) => BranchSessionManager;
11
34
  }
12
35
 
13
36
  interface ForkContextResolverOptions {
14
- openSession?: (path: string, sessionDir?: string) => { createBranchedSession(leafId: string): string | undefined };
37
+ openSession?: (path: string, sessionDir?: string) => BranchSessionManager;
38
+ }
39
+
40
+ interface ForkContextResolution {
41
+ sessionFile: string;
42
+ thinkingOverride?: "off";
15
43
  }
16
44
 
17
45
  interface ForkContextResolver {
18
46
  sessionFileForIndex(index?: number): string | undefined;
47
+ thinkingOverrideForIndex(index?: number): "off" | undefined;
19
48
  }
20
49
 
21
50
  export function resolveSubagentContext(value: unknown): SubagentExecutionContext {
22
51
  return value === "fork" ? "fork" : "fresh";
23
52
  }
24
53
 
54
+ function isUnsafeAnthropicThinkingBlock(message: BranchSessionEntry["message"], block: unknown): boolean {
55
+ if (!message || !block || typeof block !== "object" || !("type" in block)) return false;
56
+ const provider = typeof message.provider === "string" ? message.provider.toLowerCase() : "";
57
+ const api = typeof message.api === "string" ? message.api.toLowerCase() : "";
58
+ const model = typeof message.model === "string" ? message.model.toLowerCase() : "";
59
+ const isAnthropic = provider === "anthropic" || api === "anthropic-messages" || model.startsWith("anthropic/");
60
+ if (block.type === "redacted_thinking") return true;
61
+ if (block.type !== "thinking" || !isAnthropic) return false;
62
+ const signature = "thinkingSignature" in block ? block.thinkingSignature : "signature" in block ? block.signature : undefined;
63
+ return block.redacted === true || (typeof signature === "string" && signature.length > 0);
64
+ }
65
+
66
+ function createEntryId(entries: BranchSessionEntry[]): string {
67
+ const ids = new Set(entries.map((entry) => entry.id).filter((id): id is string => typeof id === "string"));
68
+ for (let attempt = 0; attempt < 100; attempt++) {
69
+ const id = randomUUID().slice(0, 8);
70
+ if (!ids.has(id)) return id;
71
+ }
72
+ return randomUUID();
73
+ }
74
+
75
+ function appendThinkingOffEntry(entries: BranchSessionEntry[]): void {
76
+ const last = entries[entries.length - 1];
77
+ if (last?.type === "thinking_level_change" && last.thinkingLevel === "off") return;
78
+ const parent = [...entries].reverse().find((entry) => typeof entry.id === "string");
79
+ entries.push({
80
+ type: "thinking_level_change",
81
+ id: createEntryId(entries),
82
+ parentId: parent?.id ?? null,
83
+ timestamp: new Date().toISOString(),
84
+ thinkingLevel: "off",
85
+ });
86
+ }
87
+
88
+ function sanitizeUnsafeThinkingBlocks(entries: BranchSessionEntry[]): boolean {
89
+ let sanitized = false;
90
+ for (const entry of entries) {
91
+ if (entry.type !== "message" || entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
92
+ const filtered = entry.message.content.filter((block) => !isUnsafeAnthropicThinkingBlock(entry.message, block));
93
+ if (filtered.length === entry.message.content.length) continue;
94
+ entry.message.content = filtered;
95
+ sanitized = true;
96
+ }
97
+ if (sanitized) appendThinkingOffEntry(entries);
98
+ return sanitized;
99
+ }
100
+
101
+ function readSessionEntries(sessionFile: string): BranchSessionEntry[] {
102
+ const lines = fs.readFileSync(sessionFile, "utf-8").split("\n").filter((line) => line.trim().length > 0);
103
+ return lines.map((line, index) => {
104
+ try {
105
+ return JSON.parse(line) as BranchSessionEntry;
106
+ } catch (error) {
107
+ const cause = error instanceof Error ? error : new Error(String(error));
108
+ throw new Error(`Unable to inspect forked session ${sessionFile}: invalid JSONL on line ${index + 1}: ${cause.message}`, { cause });
109
+ }
110
+ });
111
+ }
112
+
25
113
  export function createForkContextResolver(
26
114
  sessionManager: ForkableSessionManager,
27
115
  requestedContext: unknown,
@@ -30,6 +118,7 @@ export function createForkContextResolver(
30
118
  if (resolveSubagentContext(requestedContext) !== "fork") {
31
119
  return {
32
120
  sessionFileForIndex: () => undefined,
121
+ thinkingOverrideForIndex: () => undefined,
33
122
  };
34
123
  }
35
124
 
@@ -47,30 +136,52 @@ export function createForkContextResolver(
47
136
  ?? sessionManager.openSession
48
137
  ?? ((file: string, dir?: string) => SessionManager.open(file, dir));
49
138
  const sessionDir = sessionManager.getSessionDir?.();
50
- const cachedSessionFiles = new Map<number, string>();
139
+ const cachedResolutions = new Map<number, ForkContextResolution>();
51
140
 
52
- return {
53
- sessionFileForIndex(index = 0): string | undefined {
54
- const cached = cachedSessionFiles.get(index);
55
- if (cached) return cached;
56
- try {
57
- if (!fs.existsSync(parentSessionFile)) {
58
- throw new Error(`Parent session file does not exist: ${parentSessionFile}. Pi has not persisted enough history to fork yet.`);
59
- }
60
- const sourceManager = openSession(parentSessionFile, sessionDir);
61
- const sessionFile = sourceManager.createBranchedSession(leafId);
62
- if (!sessionFile) {
63
- throw new Error("Session manager did not return a forked session file.");
141
+ const resolveFork = (index = 0): ForkContextResolution => {
142
+ const cached = cachedResolutions.get(index);
143
+ if (cached) return cached;
144
+ try {
145
+ if (!fs.existsSync(parentSessionFile)) {
146
+ throw new Error(`Parent session file does not exist: ${parentSessionFile}. Pi has not persisted enough history to fork yet.`);
147
+ }
148
+ const sourceManager = openSession(parentSessionFile, sessionDir);
149
+ const sessionFile = sourceManager.createBranchedSession(leafId);
150
+ if (!sessionFile) {
151
+ throw new Error("Session manager did not return a forked session file.");
152
+ }
153
+ let thinkingOverride: "off" | undefined;
154
+ if (!fs.existsSync(sessionFile)) {
155
+ const header = sourceManager.getHeader?.();
156
+ const entries = sourceManager.getEntries?.();
157
+ if (!header || !entries) {
158
+ throw new Error(`Session manager returned a forked session file that does not exist and cannot be persisted by fallback: ${sessionFile}`);
64
159
  }
65
- if (!fs.existsSync(sessionFile)) {
66
- throw new Error(`Session manager returned a forked session file that does not exist: ${sessionFile}`);
160
+ if (sanitizeUnsafeThinkingBlocks(entries)) thinkingOverride = "off";
161
+ fs.mkdirSync(path.dirname(sessionFile), { recursive: true });
162
+ fs.writeFileSync(sessionFile, `${[header, ...entries].map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
163
+ } else {
164
+ const entries = readSessionEntries(sessionFile);
165
+ if (sanitizeUnsafeThinkingBlocks(entries)) {
166
+ thinkingOverride = "off";
167
+ fs.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
67
168
  }
68
- cachedSessionFiles.set(index, sessionFile);
69
- return sessionFile;
70
- } catch (error) {
71
- const cause = error instanceof Error ? error : new Error(String(error));
72
- throw new Error(`Failed to create forked subagent session: ${cause.message}`, { cause });
73
169
  }
170
+ const resolution = { sessionFile, ...(thinkingOverride ? { thinkingOverride } : {}) };
171
+ cachedResolutions.set(index, resolution);
172
+ return resolution;
173
+ } catch (error) {
174
+ const cause = error instanceof Error ? error : new Error(String(error));
175
+ throw new Error(`Failed to create forked subagent session: ${cause.message}`, { cause });
176
+ }
177
+ };
178
+
179
+ return {
180
+ sessionFileForIndex(index = 0): string | undefined {
181
+ return resolveFork(index).sessionFile;
182
+ },
183
+ thinkingOverrideForIndex(index = 0): "off" | undefined {
184
+ return resolveFork(index).thinkingOverride;
74
185
  },
75
186
  };
76
187
  }
@@ -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