@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -15,6 +15,7 @@ type AtomicJsonWriterOptions = {
15
15
  mode?: number;
16
16
  retryRenameErrors?: boolean;
17
17
  retryDirectoryErrors?: boolean;
18
+ ignoreCleanupErrorAfterSuccess?: boolean;
18
19
  retryDelaysMs?: readonly number[];
19
20
  wait?: (delayMs: number) => void;
20
21
  };
@@ -46,6 +47,7 @@ export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (
46
47
  const mode = options.mode;
47
48
  const retryRenameErrors = options.retryRenameErrors ?? process.platform === "win32";
48
49
  const retryDirectoryErrors = options.retryDirectoryErrors ?? retryRenameErrors;
50
+ const ignoreCleanupErrorAfterSuccess = options.ignoreCleanupErrorAfterSuccess ?? false;
49
51
  const retryDelaysMs = options.retryDelaysMs ?? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS;
50
52
  const renameRetryDelaysMs = retryRenameErrors ? retryDelaysMs : [];
51
53
  const directoryRetryDelaysMs = retryDirectoryErrors ? retryDelaysMs : [];
@@ -71,7 +73,7 @@ export function createAtomicJsonWriter(options: AtomicJsonWriterOptions = {}): (
71
73
  } catch (cleanupError) {
72
74
  // Preserve the write/rename failure: cleanup is best effort and must
73
75
  // not hide the error callers need to classify or report.
74
- if (writeError === undefined) throw cleanupError;
76
+ if (writeError === undefined && !ignoreCleanupErrorAfterSuccess) throw cleanupError;
75
77
  }
76
78
  }
77
79
  };
@@ -0,0 +1,46 @@
1
+ import { previewDisplayText } from "./display-text.ts";
2
+ import { PROMPT_REDACTED } from "./utils.ts";
3
+
4
+ /**
5
+ * Human-readable display name for a child session, derived at launch time from
6
+ * the agent name and its task (or workflow node label). The parent computes it
7
+ * once and threads it two ways:
8
+ *
9
+ * 1. Into the child's runtime config as `sessionName`, where the prompt
10
+ * runtime calls `pi.setSessionName(...)` so the child's own session file
11
+ * is identifiable in `pi --resume` and host session browsers.
12
+ * 2. Into the `sessionName` field of result/progress payloads, so hosts
13
+ * rendering the parent stream can label each child row.
14
+ *
15
+ * The name is display-only metadata. When the intercom bridge is active the
16
+ * child keeps its machine intercom target as the session name instead — that
17
+ * name is a routing address and must win (see subagent-prompt-runtime).
18
+ */
19
+
20
+ /** Longest task excerpt kept in the name; the full string is capped below. */
21
+ const TASK_EXCERPT_MAX_CHARS = 60;
22
+ /** Hard cap on the final name so host UI rows stay one line. */
23
+ export const CHILD_SESSION_NAME_MAX_CHARS = 80;
24
+
25
+ export function deriveChildSessionName(input: {
26
+ agent?: string;
27
+ task?: string;
28
+ /** Workflow node label; preferred over the task excerpt when present. */
29
+ label?: string;
30
+ }): string | undefined {
31
+ const agent = input.agent?.trim() ?? "";
32
+ const rawLabel = input.label?.trim() ?? "";
33
+ const rawTask = input.task?.trim() ?? "";
34
+ // Never build a name from redacted text — the excerpt would be meaningless
35
+ // and the redaction marker itself carries no information.
36
+ const excerptSource =
37
+ rawLabel && rawLabel !== PROMPT_REDACTED
38
+ ? rawLabel
39
+ : rawTask && rawTask !== PROMPT_REDACTED
40
+ ? rawTask
41
+ : "";
42
+ const excerpt = excerptSource ? previewDisplayText(excerptSource, TASK_EXCERPT_MAX_CHARS) : "";
43
+ const base = agent && excerpt ? `${agent}: ${excerpt}` : agent || excerpt;
44
+ if (!base) return undefined;
45
+ return previewDisplayText(base, CHILD_SESSION_NAME_MAX_CHARS);
46
+ }
@@ -0,0 +1,24 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Pi exposes replaced extension contexts as ordinary Errors without a stable code. */
4
+ export function isStaleExtensionContextError(error: unknown): boolean {
5
+ return error instanceof Error
6
+ && /extension ctx is stale|extension context no longer active|stale after session replacement or reload/i.test(error.message);
7
+ }
8
+
9
+ /** Run a synchronous operation against a cached UI context without leaking replacement errors. */
10
+ export function withCachedUiContext<T>(
11
+ ctx: ExtensionContext | null | undefined,
12
+ onStale: () => void,
13
+ run: (ctx: ExtensionContext) => T,
14
+ ): T | undefined {
15
+ if (!ctx) return undefined;
16
+ try {
17
+ if (!ctx.hasUI) return undefined;
18
+ return run(ctx);
19
+ } catch (error) {
20
+ if (!isStaleExtensionContextError(error)) throw error;
21
+ onStale();
22
+ return undefined;
23
+ }
24
+ }
@@ -37,6 +37,8 @@ interface ForkableSessionManager {
37
37
 
38
38
  interface ForkContextResolverOptions {
39
39
  openSession?: (path: string, sessionDir?: string) => BranchSessionManager;
40
+ /** Rewrite a created fork before its path can be used to spawn a child. */
41
+ pruneSession?: (sessionFile: string) => Promise<void>;
40
42
  /** Decide per child index whether a sanitized transcript must also disable the child's
41
43
  * thinking. Defaults to true (the pre-existing conservative behavior) when omitted. */
42
44
  forceThinkingOffForIndex?: (index: number) => boolean;
@@ -48,6 +50,7 @@ interface ForkContextResolution {
48
50
  }
49
51
 
50
52
  interface ForkContextResolver {
53
+ prepareSessionForIndex(index?: number): Promise<void>;
51
54
  sessionFileForIndex(index?: number): string | undefined;
52
55
  thinkingOverrideForIndex(index?: number): "off" | undefined;
53
56
  }
@@ -171,18 +174,6 @@ function readSessionEntries(sessionFile: string): BranchSessionEntry[] {
171
174
  });
172
175
  }
173
176
 
174
- /** Keep Pi from restoring a forked session into the parent's cwd instead of the child launch cwd. */
175
- export function alignForkedSessionCwd(sessionFile: string, cwd: string): void {
176
- const entries = readSessionEntries(sessionFile);
177
- const header = entries[0];
178
- if (header?.type !== "session") throw new Error(`Forked session ${sessionFile} does not start with a session header.`);
179
- const resolvedCwd = path.resolve(cwd);
180
- const effectiveCwd = fs.realpathSync.native(resolvedCwd);
181
- if (header.cwd === effectiveCwd) return;
182
- header.cwd = effectiveCwd;
183
- fs.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
184
- }
185
-
186
177
  export function createForkContextResolver(
187
178
  sessionManager: ForkableSessionManager,
188
179
  requestedContext: unknown,
@@ -190,6 +181,7 @@ export function createForkContextResolver(
190
181
  ): ForkContextResolver {
191
182
  if (resolveSubagentContext(requestedContext) !== "fork") {
192
183
  return {
184
+ prepareSessionForIndex: async () => {},
193
185
  sessionFileForIndex: () => undefined,
194
186
  thinkingOverrideForIndex: () => undefined,
195
187
  };
@@ -226,6 +218,8 @@ export function createForkContextResolver(
226
218
  "forks",
227
219
  );
228
220
  const cachedResolutions = new Map<number, ForkContextResolution>();
221
+ const preparedIndexes = new Set<number>();
222
+ const preparationPromises = new Map<number, Promise<void>>();
229
223
 
230
224
  const resolveFork = (index = 0): ForkContextResolution => {
231
225
  const cached = cachedResolutions.get(index);
@@ -274,7 +268,22 @@ export function createForkContextResolver(
274
268
  };
275
269
 
276
270
  return {
271
+ async prepareSessionForIndex(index = 0): Promise<void> {
272
+ const resolution = resolveFork(index);
273
+ if (!options.pruneSession || preparedIndexes.has(index)) return;
274
+ let preparation = preparationPromises.get(index);
275
+ if (!preparation) {
276
+ preparation = options.pruneSession(resolution.sessionFile).then(() => {
277
+ preparedIndexes.add(index);
278
+ });
279
+ preparationPromises.set(index, preparation);
280
+ }
281
+ await preparation;
282
+ },
277
283
  sessionFileForIndex(index = 0): string | undefined {
284
+ if (options.pruneSession && !preparedIndexes.has(index)) {
285
+ throw new Error(`Pruned fork session ${index} was used before pruning completed.`);
286
+ }
278
287
  return resolveFork(index).sessionFile;
279
288
  },
280
289
  thinkingOverrideForIndex(index = 0): "off" | undefined {
@@ -0,0 +1,27 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+
4
+ interface SessionEntry {
5
+ type?: string;
6
+ cwd?: string;
7
+ [key: string]: unknown;
8
+ }
9
+
10
+ /** Keep Pi from restoring a forked session into the parent's cwd instead of the child launch cwd. */
11
+ export function alignForkedSessionCwd(sessionFile: string, cwd: string): void {
12
+ const lines = fs.readFileSync(sessionFile, "utf-8").split("\n").filter((line) => line.trim().length > 0);
13
+ const entries = lines.map((line, index) => {
14
+ try {
15
+ return JSON.parse(line) as SessionEntry;
16
+ } catch (error) {
17
+ const cause = error instanceof Error ? error : new Error(String(error));
18
+ throw new Error(`Unable to inspect forked session ${sessionFile}: invalid JSONL on line ${index + 1}: ${cause.message}`, { cause });
19
+ }
20
+ });
21
+ const header = entries[0];
22
+ if (header?.type !== "session") throw new Error(`Forked session ${sessionFile} does not start with a session header.`);
23
+ const effectiveCwd = fs.realpathSync.native(path.resolve(cwd));
24
+ if (header.cwd === effectiveCwd) return;
25
+ header.cwd = effectiveCwd;
26
+ fs.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
27
+ }
@@ -4,17 +4,32 @@
4
4
 
5
5
  import * as fs from "node:fs";
6
6
  import * as path from "node:path";
7
- import type { Usage, SingleResult } from "./types.ts";
7
+ import type { Usage, SingleResult, TokenUsage } from "./types.ts";
8
8
  import type { ChainStep } from "./settings.ts";
9
9
  import { isDynamicParallelStep, isParallelStep } from "./settings.ts";
10
10
  import { previewDisplayText, sanitizeDisplayText } from "./display-text.ts";
11
11
  import { splitKnownThinkingSuffix, THINKING_LEVELS } from "./model-info.ts";
12
12
 
13
13
  /**
14
- * Format token count with k suffix for large numbers
14
+ * Format token count for compact display.
15
15
  */
16
16
  export function formatTokens(n: number): string {
17
- return n < 1000 ? String(n) : n < 10000 ? `${(n / 1000).toFixed(1)}k` : `${Math.round(n / 1000)}k`;
17
+ if (n < 1000) return String(n);
18
+ if (n < 10000) return `${(n / 1000).toFixed(1)}k`;
19
+ if (n < 999_500) return `${Math.round(n / 1000)}k`;
20
+ return `${Number((n / 1_000_000).toFixed(1))}M`;
21
+ }
22
+
23
+ export function formatTokenUsage(usage: TokenUsage, legacyLabel = "tok"): string {
24
+ return usage.window !== undefined
25
+ ? `${formatTokens(usage.window)} window · ${formatTokens(usage.total)} spent`
26
+ : `${formatTokens(usage.total)} ${legacyLabel}`;
27
+ }
28
+ export function formatContextUsage(usage: Pick<TokenUsage, "window" | "windowPeak">, contextLimit: number): string | undefined {
29
+ if (usage.window === undefined || !Number.isFinite(usage.window) || !Number.isFinite(contextLimit) || contextLimit <= 0) return undefined;
30
+ const peak = usage.windowPeak !== undefined && Number.isFinite(usage.windowPeak) ? usage.windowPeak : usage.window;
31
+ const used = Math.max(0, usage.window, peak);
32
+ return `ctx ${formatTokens(used)}/${formatTokens(contextLimit)} (${Math.round((used / contextLimit) * 100)}%)`;
18
33
  }
19
34
 
20
35
  export function formatModelThinking(model?: string, thinking?: string): string {
@@ -8,6 +8,7 @@ export interface DrainableSource {
8
8
  export interface JsonlWriteStream {
9
9
  write(chunk: string): boolean;
10
10
  once(event: "drain", listener: () => void): JsonlWriteStream;
11
+ on?(event: "error", listener: (error: Error) => void): JsonlWriteStream;
11
12
  end(callback?: () => void): void;
12
13
  }
13
14
 
@@ -50,6 +51,16 @@ export function createJsonlWriter(
50
51
  let closed = false;
51
52
  let bytesWritten = 0;
52
53
  const maxBytes = deps.maxBytes ?? DEFAULT_MAX_JSONL_BYTES;
54
+ // The mirror is best effort: a stream that cannot open or write (for example
55
+ // because its directory was removed) must not surface as an uncaught error.
56
+ stream.on?.("error", () => {
57
+ closed = true;
58
+ stream = undefined;
59
+ if (backpressured) {
60
+ backpressured = false;
61
+ source.resume();
62
+ }
63
+ });
53
64
 
54
65
  return {
55
66
  writeLine(line: string) {
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import type { AgentConfig } from "../agents/agents.ts";
4
+ import type { ExtensionBindings } from "../runs/shared/extension-bindings.ts";
4
5
 
5
6
  export const AGENT_DEFINITION_PROJECTION_VERSION = 1 as const;
6
7
  export const LAUNCH_BINDING_PROJECTION_VERSION = 1 as const;
@@ -17,7 +18,7 @@ function stableJson(value: unknown): string {
17
18
  return JSON.stringify(value);
18
19
  }
19
20
 
20
- function sha256(value: unknown): string {
21
+ export function stableJsonDigest(value: unknown): string {
21
22
  return createHash("sha256").update(stableJson(value)).digest("hex");
22
23
  }
23
24
 
@@ -42,14 +43,20 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
42
43
  systemPrompt: agent.systemPrompt,
43
44
  systemPromptMode: agent.systemPromptMode,
44
45
  inheritProjectContext: agent.inheritProjectContext,
46
+ inheritGlobalContext: agent.inheritGlobalContext,
45
47
  inheritSkills: agent.inheritSkills,
46
48
  model: agent.model,
49
+ modelProvider: agent.modelProvider,
47
50
  fallbackModels: agent.fallbackModels,
51
+ fast: agent.fast,
48
52
  thinking: agent.thinking,
49
53
  tools: agent.tools,
54
+ excludeTools: agent.excludeTools,
55
+ allowNestedSubagents: agent.allowNestedSubagents,
50
56
  mcpDirectTools: agent.mcpDirectTools,
51
57
  extensions: agent.extensions,
52
58
  subagentOnlyExtensions: agent.subagentOnlyExtensions,
59
+ mutationTools: agent.mutationTools,
53
60
  skills: agent.skills,
54
61
  skillPath: agent.skillPath,
55
62
  output: agent.output,
@@ -58,7 +65,6 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
58
65
  defaultContext: agent.defaultContext,
59
66
  defaultAsync: agent.defaultAsync,
60
67
  defaultTimeoutMs: agent.defaultTimeoutMs,
61
- defaultTurnBudget: agent.defaultTurnBudget,
62
68
  defaultAcceptance: agent.defaultAcceptance,
63
69
  acceptanceRole: agent.acceptanceRole,
64
70
  interactive: agent.interactive,
@@ -70,7 +76,7 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
70
76
  }
71
77
 
72
78
  export function agentDefinitionDigest(agent: AgentConfig): string {
73
- return sha256(projectAgentDefinition(agent));
79
+ return stableJsonDigest(projectAgentDefinition(agent));
74
80
  }
75
81
 
76
82
  export interface LaunchBindingInput {
@@ -79,19 +85,23 @@ export interface LaunchBindingInput {
79
85
  task?: string;
80
86
  model?: string;
81
87
  modelCandidates?: string[];
88
+ fast?: boolean;
82
89
  thinking?: string;
83
90
  systemPrompt?: string | null;
84
91
  systemPromptMode?: AgentConfig["systemPromptMode"];
85
92
  inheritProjectContext: boolean;
93
+ inheritGlobalContext: boolean;
86
94
  inheritSkills: boolean;
87
95
  skills?: string[];
88
96
  tools?: string[];
97
+ excludeTools?: string[];
89
98
  extensions?: string[];
90
99
  subagentOnlyExtensions?: string[];
91
100
  mcpDirectTools?: string[];
92
101
  outputPath?: string;
93
102
  outputMode?: string;
94
103
  structuredOutputSchema?: unknown;
104
+ extensionBindings?: ExtensionBindings;
95
105
  }
96
106
 
97
107
  /** Canonical projection of the resolved inputs handed to the child. */
@@ -99,26 +109,30 @@ export function projectLaunchBinding(input: LaunchBindingInput): Record<string,
99
109
  return {
100
110
  version: LAUNCH_BINDING_PROJECTION_VERSION,
101
111
  definitionDigest: input.definitionDigest,
102
- taskDigest: input.task === undefined ? undefined : sha256(input.task),
112
+ taskDigest: input.task === undefined ? undefined : stableJsonDigest(input.task),
103
113
  // The ordered candidate set already contains each attempted model; keeping only
104
114
  // this set makes retries correlate to the same preflight binding.
105
115
  modelCandidates: input.modelCandidates,
116
+ fast: input.fast,
106
117
  thinking: input.thinking,
107
- systemPromptDigest: input.systemPrompt === undefined || input.systemPrompt === null ? undefined : sha256(input.systemPrompt),
118
+ systemPromptDigest: input.systemPrompt === undefined || input.systemPrompt === null ? undefined : stableJsonDigest(input.systemPrompt),
108
119
  systemPromptMode: input.systemPromptMode,
109
120
  inheritProjectContext: input.inheritProjectContext,
121
+ inheritGlobalContext: input.inheritGlobalContext,
110
122
  inheritSkills: input.inheritSkills,
111
123
  skills: input.skills,
112
124
  tools: input.tools,
125
+ excludeTools: input.excludeTools,
113
126
  extensions: input.extensions,
114
127
  subagentOnlyExtensions: input.subagentOnlyExtensions,
115
128
  mcpDirectTools: input.mcpDirectTools,
116
129
  outputPath: input.outputPath,
117
130
  outputMode: input.outputMode,
118
131
  structuredOutputSchema: input.structuredOutputSchema,
132
+ extensionBindings: input.extensionBindings,
119
133
  };
120
134
  }
121
135
 
122
136
  export function launchBindingDigest(input: LaunchBindingInput): string {
123
- return sha256(projectLaunchBinding(input));
137
+ return stableJsonDigest(projectLaunchBinding(input));
124
138
  }