@xzzpig/pi-subagents 0.14.0 → 0.15.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 (198) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +63 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  21. package/package.json +9 -4
  22. package/prompts/parallel-review.md +1 -1
  23. package/runner-peer-loader.mjs +24 -0
  24. package/runner-peer-preload.mjs +36 -0
  25. package/skills/pi-subagents/SKILL.md +34 -22
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  27. package/skills/pi-subagents/references/execution-controls.md +27 -8
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  31. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  32. package/src/agents/advertised-agent-prompt.ts +94 -0
  33. package/src/agents/agent-management.ts +71 -59
  34. package/src/agents/agent-serializer.ts +6 -3
  35. package/src/agents/agents.ts +198 -72
  36. package/src/agents/builtin-names.ts +1 -0
  37. package/src/agents/chain-serializer.ts +5 -0
  38. package/src/agents/runtime-agent-registry.ts +7 -6
  39. package/src/api/delegation.ts +4 -0
  40. package/src/api/preflight.ts +110 -71
  41. package/src/api/required-child-extensions.ts +6 -0
  42. package/src/api/shared-types.ts +3 -1
  43. package/src/api/workflow-resources.ts +6 -0
  44. package/src/extension/config.ts +14 -37
  45. package/src/extension/fanout-child.ts +68 -5
  46. package/src/extension/herdr-pi-bridge.ts +164 -0
  47. package/src/extension/index.ts +141 -51
  48. package/src/extension/public-execution.ts +7 -6
  49. package/src/extension/rpc.ts +8 -21
  50. package/src/extension/schemas.ts +86 -84
  51. package/src/extension/tool-description.ts +32 -79
  52. package/src/inspectors/actions.ts +148 -0
  53. package/src/inspectors/ghostty/actions.ts +74 -0
  54. package/src/inspectors/ghostty/plugin.ts +17 -0
  55. package/src/inspectors/herdr/actions.ts +99 -179
  56. package/src/inspectors/herdr/plugin.ts +20 -0
  57. package/src/inspectors/herdr/project-panes.ts +4 -1
  58. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  59. package/src/inspectors/plugins.ts +8 -0
  60. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  61. package/src/inspectors/types.ts +51 -0
  62. package/src/integrations/pi-web-session-liveness.ts +73 -0
  63. package/src/intercom/intercom-bridge.ts +50 -8
  64. package/src/intercom/native-supervisor-channel.ts +142 -115
  65. package/src/intercom/supervisor-ui.ts +3 -2
  66. package/src/missions/workflow-state.ts +37 -16
  67. package/src/policy/authority.ts +4 -0
  68. package/src/profiles/profiles.ts +12 -6
  69. package/src/runs/background/active-async-capacity.ts +22 -18
  70. package/src/runs/background/active-run-index.ts +17 -1
  71. package/src/runs/background/async-execution.ts +359 -176
  72. package/src/runs/background/async-job-tracker.ts +41 -7
  73. package/src/runs/background/async-resume.ts +19 -12
  74. package/src/runs/background/async-retention.ts +20 -0
  75. package/src/runs/background/async-status-snapshot.ts +10 -12
  76. package/src/runs/background/async-status.ts +32 -13
  77. package/src/runs/background/auto-drain.ts +59 -35
  78. package/src/runs/background/binary-bootstrap.ts +38 -0
  79. package/src/runs/background/chain-append.ts +1 -1
  80. package/src/runs/background/chain-root-attachment.ts +22 -33
  81. package/src/runs/background/control-channel.ts +78 -44
  82. package/src/runs/background/fleet-view.ts +30 -2
  83. package/src/runs/background/notify.ts +193 -19
  84. package/src/runs/background/owned-process-tree.ts +35 -8
  85. package/src/runs/background/process-terminal.ts +23 -23
  86. package/src/runs/background/result-files.ts +8 -4
  87. package/src/runs/background/result-watcher.ts +19 -2
  88. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  89. package/src/runs/background/run-child-session.ts +118 -41
  90. package/src/runs/background/run-status.ts +78 -5
  91. package/src/runs/background/runner-aliases.ts +22 -5
  92. package/src/runs/background/runner-child-launch.ts +93 -0
  93. package/src/runs/background/runner-child-sessions.ts +5 -4
  94. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  95. package/src/runs/background/scheduled-runs.ts +51 -18
  96. package/src/runs/background/stale-run-reconciler.ts +38 -12
  97. package/src/runs/background/steering.ts +20 -2
  98. package/src/runs/background/subagent-runner.ts +766 -432
  99. package/src/runs/background/subagent-wait.ts +179 -28
  100. package/src/runs/background/wait-completions.ts +79 -27
  101. package/src/runs/background/wait-subscriptions.ts +9 -3
  102. package/src/runs/background/wait-tool.ts +5 -3
  103. package/src/runs/foreground/async-steering-action.ts +37 -7
  104. package/src/runs/foreground/async-stop-action.ts +93 -3
  105. package/src/runs/foreground/execution.ts +174 -194
  106. package/src/runs/foreground/foreground-history.ts +5 -2
  107. package/src/runs/foreground/prompt-audit.ts +12 -6
  108. package/src/runs/foreground/subagent-executor.ts +896 -397
  109. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  110. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  111. package/src/runs/shared/acceptance.ts +54 -14
  112. package/src/runs/shared/agent-contract.ts +1 -1
  113. package/src/runs/shared/async-status-projection.ts +172 -78
  114. package/src/runs/shared/capability-ceiling.ts +2 -0
  115. package/src/runs/shared/child-hooks.ts +167 -3
  116. package/src/runs/shared/child-launch-plan.ts +15 -3
  117. package/src/runs/shared/child-launch.ts +44 -16
  118. package/src/runs/shared/child-lifecycle.ts +6 -3
  119. package/src/runs/shared/child-runtime-config.ts +8 -1
  120. package/src/runs/shared/child-session.ts +130 -24
  121. package/src/runs/shared/child-tool-plan.ts +145 -14
  122. package/src/runs/shared/completion-evidence.ts +2 -2
  123. package/src/runs/shared/completion-guard.ts +6 -3
  124. package/src/runs/shared/dynamic-fanout.ts +2 -2
  125. package/src/runs/shared/effective-system-prompt.ts +33 -0
  126. package/src/runs/shared/external-cli-contract.ts +11 -1
  127. package/src/runs/shared/external-cli-preflight.ts +6 -2
  128. package/src/runs/shared/external-cli-runner.ts +9 -7
  129. package/src/runs/shared/herdr-connection.ts +134 -0
  130. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  131. package/src/runs/shared/herdr-machine.ts +279 -0
  132. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  133. package/src/runs/shared/herdr-placed-run.ts +263 -0
  134. package/src/runs/shared/host-step-status.ts +11 -11
  135. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  136. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  137. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  138. package/src/runs/shared/model-scope.ts +1 -1
  139. package/src/runs/shared/nested-events.ts +19 -10
  140. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  141. package/src/runs/shared/parallel-handoff.ts +57 -12
  142. package/src/runs/shared/parallel-utils.ts +10 -4
  143. package/src/runs/shared/pi-spawn.ts +10 -0
  144. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  145. package/src/runs/shared/run-fanout-budget.ts +8 -8
  146. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  147. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  148. package/src/runs/shared/task-intent.ts +46 -13
  149. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  150. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  151. package/src/runs/shared/worktree-setup-command.ts +213 -0
  152. package/src/runs/shared/worktree.ts +437 -214
  153. package/src/shared/child-cache-retention.ts +43 -0
  154. package/src/shared/fork-context.ts +15 -72
  155. package/src/shared/launch-contract.ts +70 -8
  156. package/src/shared/model-response-aliases.ts +13 -0
  157. package/src/shared/opencode-session-headers.ts +30 -0
  158. package/src/shared/pruned-fork.ts +1 -1
  159. package/src/shared/required-child-extensions.ts +81 -0
  160. package/src/shared/settings.ts +5 -2
  161. package/src/shared/shortcuts.ts +0 -4
  162. package/src/shared/types.ts +163 -90
  163. package/src/shared/utils.ts +10 -2
  164. package/src/shared/watch-strategy.ts +2 -0
  165. package/src/shared/workflow-child-permit.ts +18 -13
  166. package/src/slash/delegation-adapters.ts +3 -1
  167. package/src/slash/delegation-request.ts +14 -0
  168. package/src/slash/slash-commands.ts +2 -7
  169. package/src/slash/subagents-admin.ts +31 -14
  170. package/src/tui/fleet-status.ts +165 -20
  171. package/src/tui/fleet.ts +30 -19
  172. package/src/tui/render.ts +210 -50
  173. package/src/watchdog/child-status.ts +28 -28
  174. package/src/watchdog/lsp-diagnostics.ts +1 -1
  175. package/src/watchdog/model-selection.ts +21 -1
  176. package/src/watchdog/permission-arbiter.ts +5 -2
  177. package/src/watchdog/register-child.ts +10 -2
  178. package/src/watchdog/register-main.ts +39 -35
  179. package/src/watchdog/render.ts +1 -1
  180. package/src/watchdog/review.ts +122 -74
  181. package/src/watchdog/rules.ts +1 -1
  182. package/src/watchdog/runtime.ts +100 -27
  183. package/src/watchdog/scope.ts +1 -1
  184. package/src/watchdog/settings.ts +3 -0
  185. package/src/watchdog/tool-actions.ts +13 -12
  186. package/src/watchdog/turn-delta.ts +23 -0
  187. package/src/watchdog/types.ts +5 -3
  188. package/src/watchdog/warning-format.ts +1 -1
  189. package/src/workflows/chat-progress.ts +3 -3
  190. package/src/workflows/scripted-workflow.ts +349 -26
  191. package/src/workflows/workflow-checklist.ts +17 -20
  192. package/src/workflows/workflow-child-summary.ts +57 -8
  193. package/src/workflows/workflow-preflight.ts +19 -19
  194. package/src/workflows/workflow-receipt.ts +24 -6
  195. package/src/workflows/workflow-resources.ts +108 -22
  196. package/src/workflows/workflow-settlement.ts +3 -0
  197. package/src/runs/shared/model-exclusions.ts +0 -373
  198. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -0,0 +1,43 @@
1
+ import type { StreamFn } from "@earendil-works/pi-agent-core";
2
+
3
+ /**
4
+ * Anthropic prices a cache write by the TTL it is asked for: 1.25x base input
5
+ * for the 5m window, 2x for the 1h one. Child sessions are short-lived and
6
+ * rarely idle, so a 1h window they never claim is a flat surcharge on every
7
+ * write. Setting this to `short` keeps that surcharge off children while the
8
+ * parent keeps `long`, the same split Claude Code makes between its main
9
+ * conversation and its subagents.
10
+ *
11
+ * Unset means children inherit the parent's retention, which is the behaviour
12
+ * before this setting existed.
13
+ */
14
+ export function childCacheRetention(env: NodeJS.ProcessEnv = process.env): string | undefined {
15
+ return env.PI_SUBAGENT_CACHE_RETENTION || undefined;
16
+ }
17
+
18
+ /**
19
+ * Launch-environment form for spawned children. Empty when unset, so the child
20
+ * inherits the parent's `PI_CACHE_RETENTION` rather than having it cleared.
21
+ */
22
+ export function childCacheRetentionEnv(env?: NodeJS.ProcessEnv): { PI_CACHE_RETENTION?: string } {
23
+ const retention = childCacheRetention(env);
24
+ return retention ? { PI_CACHE_RETENTION: retention } : {};
25
+ }
26
+
27
+ /**
28
+ * Pi resolves retention per request as `options.env?.[name] || process.env[name]`,
29
+ * so a per-call env beats the process-wide one. Wrapping the session's own
30
+ * stream function keeps this scoped to one child, with no shared-state race
31
+ * against a parent turn streaming concurrently.
32
+ */
33
+ export function pinChildCacheRetention(agent: { streamFunction: StreamFn } | undefined, env?: NodeJS.ProcessEnv): void {
34
+ if (!agent?.streamFunction) return;
35
+ const retention = childCacheRetention(env);
36
+ if (!retention) return;
37
+ const base = agent.streamFunction;
38
+ agent.streamFunction = (model, context, options) =>
39
+ base(model, context, {
40
+ ...options,
41
+ env: { ...(options?.env ?? {}), PI_CACHE_RETENTION: retention },
42
+ });
43
+ }
@@ -1,8 +1,12 @@
1
- import { randomUUID } from "node:crypto";
1
+ // Forking a parent transcript into a child must drop Anthropic's signed and redacted
2
+ // thinking blocks: a thinking signature is bound to the session that produced it and
3
+ // cannot be replayed into a branch. Stripping them is required; disabling the child's
4
+ // thinking is not. Pi >= 0.85.0 recovers from signed-thinking mismatches on the
5
+ // transport, so a sanitized transcript is safe to resume with thinking enabled and the
6
+ // child keeps the level it asked for, reasoning fresh from its first turn.
2
7
  import * as fs from "node:fs";
3
8
  import * as path from "node:path";
4
9
  import { SessionManager } from "@earendil-works/pi-coding-agent";
5
- import { findModelInfo, type ModelInfo } from "./model-info.ts";
6
10
 
7
11
  type SubagentExecutionContext = "fresh" | "fork";
8
12
 
@@ -19,7 +23,6 @@ interface BranchSessionEntry {
19
23
  api?: string;
20
24
  model?: string;
21
25
  };
22
- thinkingLevel?: string;
23
26
  }
24
27
 
25
28
  interface BranchSessionManager {
@@ -39,20 +42,11 @@ interface ForkContextResolverOptions {
39
42
  openSession?: (path: string, sessionDir?: string) => BranchSessionManager;
40
43
  /** Rewrite a created fork before its path can be used to spawn a child. */
41
44
  pruneSession?: (sessionFile: string) => Promise<void>;
42
- /** Decide per child index whether a sanitized transcript must also disable the child's
43
- * thinking. Defaults to true (the pre-existing conservative behavior) when omitted. */
44
- forceThinkingOffForIndex?: (index: number) => boolean;
45
- }
46
-
47
- interface ForkContextResolution {
48
- sessionFile: string;
49
- thinkingOverride?: "off";
50
45
  }
51
46
 
52
47
  interface ForkContextResolver {
53
48
  prepareSessionForIndex(index?: number): Promise<void>;
54
49
  sessionFileForIndex(index?: number): string | undefined;
55
- thinkingOverrideForIndex(index?: number): "off" | undefined;
56
50
  }
57
51
 
58
52
  export function resolveSubagentContext(value: unknown): SubagentExecutionContext {
@@ -101,20 +95,6 @@ export function canPreferForkFromSnapshot(input: PreferredForkSnapshot): boolean
101
95
  }
102
96
  }
103
97
 
104
- /** Decide whether a resolved child model uses Anthropic's provider or message API, which
105
- * requires the sanitized fork to disable thinking. Unknown models stay conservative. */
106
- export function forkedChildRequiresThinkingOff(
107
- model: string | undefined,
108
- availableModels?: ModelInfo[],
109
- preferredProvider?: string,
110
- ): boolean {
111
- if (!model) return true;
112
- const info = findModelInfo(model, availableModels, preferredProvider);
113
- if (!info) return true;
114
- return info.provider.toLowerCase() === "anthropic"
115
- || info.api?.toLowerCase() === "anthropic-messages";
116
- }
117
-
118
98
  function isUnsafeAnthropicThinkingBlock(message: BranchSessionEntry["message"], block: unknown): boolean {
119
99
  if (!message || !block || typeof block !== "object" || !("type" in block)) return false;
120
100
  const provider = typeof message.provider === "string" ? message.provider.toLowerCase() : "";
@@ -128,28 +108,6 @@ function isUnsafeAnthropicThinkingBlock(message: BranchSessionEntry["message"],
128
108
  return record.redacted === true || (typeof signature === "string" && signature.length > 0);
129
109
  }
130
110
 
131
- function createEntryId(entries: BranchSessionEntry[]): string {
132
- const ids = new Set(entries.map((entry) => entry.id).filter((id): id is string => typeof id === "string"));
133
- for (let attempt = 0; attempt < 100; attempt++) {
134
- const id = randomUUID().slice(0, 8);
135
- if (!ids.has(id)) return id;
136
- }
137
- return randomUUID();
138
- }
139
-
140
- function appendThinkingOffEntry(entries: BranchSessionEntry[]): void {
141
- const last = entries[entries.length - 1];
142
- if (last?.type === "thinking_level_change" && last.thinkingLevel === "off") return;
143
- const parent = [...entries].reverse().find((entry) => typeof entry.id === "string");
144
- entries.push({
145
- type: "thinking_level_change",
146
- id: createEntryId(entries),
147
- parentId: parent?.id ?? null,
148
- timestamp: new Date().toISOString(),
149
- thinkingLevel: "off",
150
- });
151
- }
152
-
153
111
  function sanitizeUnsafeThinkingBlocks(entries: BranchSessionEntry[]): boolean {
154
112
  let sanitized = false;
155
113
  for (const entry of entries) {
@@ -183,7 +141,6 @@ export function createForkContextResolver(
183
141
  return {
184
142
  prepareSessionForIndex: async () => {},
185
143
  sessionFileForIndex: () => undefined,
186
- thinkingOverrideForIndex: () => undefined,
187
144
  };
188
145
  }
189
146
 
@@ -217,12 +174,12 @@ export function createForkContextResolver(
217
174
  path.basename(parentSessionFile, ".jsonl"),
218
175
  "forks",
219
176
  );
220
- const cachedResolutions = new Map<number, ForkContextResolution>();
177
+ const cachedSessionFiles = new Map<number, string>();
221
178
  const preparedIndexes = new Set<number>();
222
179
  const preparationPromises = new Map<number, Promise<void>>();
223
180
 
224
- const resolveFork = (index = 0): ForkContextResolution => {
225
- const cached = cachedResolutions.get(index);
181
+ const resolveFork = (index = 0): string => {
182
+ const cached = cachedSessionFiles.get(index);
226
183
  if (cached) return cached;
227
184
  try {
228
185
  if (!fs.existsSync(parentSessionFile)) {
@@ -233,34 +190,23 @@ export function createForkContextResolver(
233
190
  if (!sessionFile) {
234
191
  throw new Error("Session manager did not return a forked session file.");
235
192
  }
236
- const forceThinkingOff = (sanitized: boolean): boolean =>
237
- sanitized && (options.forceThinkingOffForIndex?.(index) ?? true);
238
- let thinkingOverride: "off" | undefined;
239
193
  if (!fs.existsSync(sessionFile)) {
240
194
  const header = sourceManager.getHeader?.();
241
195
  const entries = sourceManager.getEntries?.();
242
196
  if (!header || !entries) {
243
197
  throw new Error(`Session manager returned a forked session file that does not exist and cannot be persisted by fallback: ${sessionFile}`);
244
198
  }
245
- if (forceThinkingOff(sanitizeUnsafeThinkingBlocks(entries))) {
246
- appendThinkingOffEntry(entries);
247
- thinkingOverride = "off";
248
- }
199
+ sanitizeUnsafeThinkingBlocks(entries);
249
200
  fs.mkdirSync(path.dirname(sessionFile), { recursive: true });
250
201
  fs.writeFileSync(sessionFile, `${[header, ...entries].map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
251
202
  } else {
252
203
  const entries = readSessionEntries(sessionFile);
253
204
  if (sanitizeUnsafeThinkingBlocks(entries)) {
254
- if (forceThinkingOff(true)) {
255
- appendThinkingOffEntry(entries);
256
- thinkingOverride = "off";
257
- }
258
205
  fs.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
259
206
  }
260
207
  }
261
- const resolution = { sessionFile, ...(thinkingOverride ? { thinkingOverride } : {}) };
262
- cachedResolutions.set(index, resolution);
263
- return resolution;
208
+ cachedSessionFiles.set(index, sessionFile);
209
+ return sessionFile;
264
210
  } catch (error) {
265
211
  const cause = error instanceof Error ? error : new Error(String(error));
266
212
  throw new Error(`Failed to create forked subagent session: ${cause.message}`, { cause });
@@ -269,11 +215,11 @@ export function createForkContextResolver(
269
215
 
270
216
  return {
271
217
  async prepareSessionForIndex(index = 0): Promise<void> {
272
- const resolution = resolveFork(index);
218
+ const sessionFile = resolveFork(index);
273
219
  if (!options.pruneSession || preparedIndexes.has(index)) return;
274
220
  let preparation = preparationPromises.get(index);
275
221
  if (!preparation) {
276
- preparation = options.pruneSession(resolution.sessionFile).then(() => {
222
+ preparation = options.pruneSession(sessionFile).then(() => {
277
223
  preparedIndexes.add(index);
278
224
  });
279
225
  preparationPromises.set(index, preparation);
@@ -284,10 +230,7 @@ export function createForkContextResolver(
284
230
  if (options.pruneSession && !preparedIndexes.has(index)) {
285
231
  throw new Error(`Pruned fork session ${index} was used before pruning completed.`);
286
232
  }
287
- return resolveFork(index).sessionFile;
288
- },
289
- thinkingOverrideForIndex(index = 0): "off" | undefined {
290
- return resolveFork(index).thinkingOverride;
233
+ return resolveFork(index);
291
234
  },
292
235
  };
293
236
  }
@@ -1,10 +1,13 @@
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 { PiLaunchToolPlan } from "../runs/shared/child-tool-plan.ts";
4
5
  import type { ExtensionBindings } from "../runs/shared/extension-bindings.ts";
5
6
 
6
- export const AGENT_DEFINITION_PROJECTION_VERSION = 1 as const;
7
- export const LAUNCH_BINDING_PROJECTION_VERSION = 1 as const;
7
+ export const AGENT_DEFINITION_PROJECTION_VERSION = 2 as const;
8
+ // v2: the Intercom bridge prompt and tools are part of the binding on every
9
+ // path, and the bridge text no longer names the parent session.
10
+ export const LAUNCH_BINDING_PROJECTION_VERSION = 2 as const;
8
11
 
9
12
  function stableJson(value: unknown): string {
10
13
  if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
@@ -47,7 +50,6 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
47
50
  inheritSkills: agent.inheritSkills,
48
51
  model: agent.model,
49
52
  modelProvider: agent.modelProvider,
50
- fallbackModels: agent.fallbackModels,
51
53
  fast: agent.fast,
52
54
  thinking: agent.thinking,
53
55
  tools: agent.tools,
@@ -60,6 +62,7 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
60
62
  skills: agent.skills,
61
63
  skillPath: agent.skillPath,
62
64
  output: agent.output,
65
+ outputSchema: agent.outputSchema,
63
66
  defaultReads: agent.defaultReads,
64
67
  defaultProgress: agent.defaultProgress,
65
68
  defaultContext: agent.defaultContext,
@@ -77,8 +80,9 @@ export function projectAgentDefinition(agent: AgentConfig): Record<string, unkno
77
80
  };
78
81
  }
79
82
 
83
+ /** Digest of the parsed definition; a runtime overlay that already captured it wins over re-hashing the overlaid copy. */
80
84
  export function agentDefinitionDigest(agent: AgentConfig): string {
81
- return stableJsonDigest(projectAgentDefinition(agent));
85
+ return agent.definitionDigest ?? stableJsonDigest(projectAgentDefinition(agent));
82
86
  }
83
87
 
84
88
  export interface LaunchBindingInput {
@@ -86,7 +90,6 @@ export interface LaunchBindingInput {
86
90
  /** Caller task; runtime acceptance/output task annotations are explicitly outside the preflight-known subset. */
87
91
  task?: string;
88
92
  model?: string;
89
- modelCandidates?: string[];
90
93
  fast?: boolean;
91
94
  thinking?: string;
92
95
  systemPrompt?: string | null;
@@ -114,9 +117,7 @@ export function projectLaunchBinding(input: LaunchBindingInput): Record<string,
114
117
  version: LAUNCH_BINDING_PROJECTION_VERSION,
115
118
  definitionDigest: input.definitionDigest,
116
119
  taskDigest: input.task === undefined ? undefined : stableJsonDigest(input.task),
117
- // The ordered candidate set already contains each attempted model; keeping only
118
- // this set makes retries correlate to the same preflight binding.
119
- modelCandidates: input.modelCandidates,
120
+ model: input.model,
120
121
  fast: input.fast,
121
122
  thinking: input.thinking,
122
123
  systemPromptDigest: input.systemPrompt === undefined || input.systemPrompt === null ? undefined : stableJsonDigest(input.systemPrompt),
@@ -142,3 +143,64 @@ export function projectLaunchBinding(input: LaunchBindingInput): Record<string,
142
143
  export function launchBindingDigest(input: LaunchBindingInput): string {
143
144
  return stableJsonDigest(projectLaunchBinding(input));
144
145
  }
146
+
147
+ type LaunchBindingPromptMode = Pick<LaunchBindingInput, "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills">;
148
+
149
+ /**
150
+ * Who the child is: the launched agent, or the identity a persisted step
151
+ * already captured when a runner recomputes the binding per model attempt.
152
+ */
153
+ export type LaunchBindingIdentity =
154
+ | { agent: AgentConfig }
155
+ | ({ definitionDigest: string } & LaunchBindingPromptMode);
156
+
157
+ export type LaunchBindingSource = LaunchBindingIdentity
158
+ & Pick<LaunchBindingInput, "fast" | "thinking" | "skills" | "outputPath" | "outputMode" | "sandbox" | "permissionProfile" | "structuredOutputSchema" | "extensionBindings">
159
+ & {
160
+ task: string;
161
+ model?: string;
162
+ /** Effective child system prompt before runtime acceptance prose. */
163
+ systemPrompt: string;
164
+ toolPlan: Pick<PiLaunchToolPlan, "effectiveToolAllowlist" | "excludeTools" | "extensionArgs" | "effectiveMcpTools">;
165
+ };
166
+
167
+ export interface LaunchBinding {
168
+ definitionDigest: string;
169
+ launchContractDigest: string;
170
+ }
171
+
172
+ /**
173
+ * Assemble launch identity from resolved preflight or execution inputs.
174
+ * The stable projection omits undefined optional fields.
175
+ */
176
+ export function resolveLaunchBinding(source: LaunchBindingSource): LaunchBinding {
177
+ const identity = "agent" in source ? {
178
+ definitionDigest: agentDefinitionDigest(source.agent),
179
+ systemPromptMode: source.agent.systemPromptMode,
180
+ inheritProjectContext: source.agent.inheritProjectContext,
181
+ inheritGlobalContext: source.agent.inheritGlobalContext,
182
+ inheritSkills: source.agent.inheritSkills,
183
+ } : source;
184
+ return {
185
+ definitionDigest: identity.definitionDigest,
186
+ launchContractDigest: launchBindingDigest({
187
+ ...identity,
188
+ task: source.task,
189
+ model: source.model,
190
+ fast: source.fast,
191
+ thinking: source.thinking || undefined,
192
+ systemPrompt: source.systemPrompt,
193
+ skills: source.skills,
194
+ tools: source.toolPlan.effectiveToolAllowlist,
195
+ excludeTools: source.toolPlan.excludeTools.length > 0 ? source.toolPlan.excludeTools : undefined,
196
+ extensions: source.toolPlan.extensionArgs,
197
+ mcpDirectTools: source.toolPlan.effectiveMcpTools,
198
+ outputPath: source.outputPath || undefined,
199
+ outputMode: source.outputMode,
200
+ sandbox: source.sandbox || undefined,
201
+ permissionProfile: source.permissionProfile || undefined,
202
+ structuredOutputSchema: source.structuredOutputSchema,
203
+ extensionBindings: source.extensionBindings || undefined,
204
+ }),
205
+ };
206
+ }
@@ -0,0 +1,13 @@
1
+ export function validateModelResponseAliases(value: unknown, label = "config.modelResponseAliases"): void {
2
+ if (value === undefined) return;
3
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be a JSON object`);
4
+ for (const [candidate, aliases] of Object.entries(value)) {
5
+ const slash = candidate.indexOf("/");
6
+ if (slash <= 0 || !candidate.slice(0, slash).trim() || !candidate.slice(slash + 1).trim()) {
7
+ throw new Error(`${label} key ${JSON.stringify(candidate)} must be a non-empty provider/model ID`);
8
+ }
9
+ if (!Array.isArray(aliases) || aliases.some((alias) => typeof alias !== "string" || !alias.trim())) {
10
+ throw new Error(`${label}[${JSON.stringify(candidate)}] must be an array of non-empty response ID strings`);
11
+ }
12
+ }
13
+ }
@@ -0,0 +1,30 @@
1
+ import type { Api, Model, ProviderHeaders } from "@earendil-works/pi-ai";
2
+
3
+ const OPENCODE_HOST = "opencode.ai";
4
+
5
+ function matchesOpenCodeHost(baseUrl: string): boolean {
6
+ try {
7
+ return new URL(baseUrl).hostname === OPENCODE_HOST;
8
+ } catch {
9
+ return false;
10
+ }
11
+ }
12
+
13
+ /**
14
+ * OpenCode session-routing headers for internal subagent model calls.
15
+ *
16
+ * Pi's own session path emits these from coding-agent's provider-attribution
17
+ * merge, but subagent-internal calls (watchdog review, permission arbiter,
18
+ * task-mutation arbiter, prompt audit) stream through bare Agents that bypass
19
+ * that path. Without them OpenCode falls back to client-IP affinity and loses
20
+ * prompt-cache routing (see pi issue #4847). Returns undefined for every other
21
+ * provider so non-OpenCode requests stay byte-identical.
22
+ */
23
+ export function opencodeSessionHeaders(
24
+ model: Pick<Model<Api>, "provider" | "baseUrl">,
25
+ sessionId: string | undefined,
26
+ ): ProviderHeaders | undefined {
27
+ if (!sessionId) return undefined;
28
+ if (model.provider !== "opencode" && model.provider !== "opencode-go" && !matchesOpenCodeHost(model.baseUrl)) return undefined;
29
+ return { "x-opencode-session": sessionId, "x-opencode-client": "pi" };
30
+ }
@@ -5,7 +5,7 @@ import * as path from "node:path";
5
5
  import type { TextContent } from "@earendil-works/pi-ai";
6
6
  import { completeSimple } from "@earendil-works/pi-ai/compat";
7
7
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
- import { resolveModelCandidate } from "../runs/shared/model-fallback.ts";
8
+ import { resolveModelCandidate } from "../runs/shared/model-resolution.ts";
9
9
  import { splitKnownThinkingSuffix, toModelInfo } from "./model-info.ts";
10
10
  import type { ForkContextConfig } from "./types.ts";
11
11
 
@@ -0,0 +1,81 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+
4
+ const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
5
+ const MAX_REQUIRED_EXTENSIONS = 32;
6
+ const MAX_PATH_BYTES = 4096;
7
+ const EMPTY_SNAPSHOT: RequiredChildExtensionSnapshot = Object.freeze([]);
8
+
9
+ export interface RequiredChildExtension {
10
+ /** Safe host-owned identity exposed in launch evidence. */
11
+ id: string;
12
+ /** Existing importable module path. Snapshotted to its canonical absolute path. */
13
+ path: string;
14
+ }
15
+
16
+ export interface RegisterRequiredChildExtensionsInput {
17
+ sessionId: string;
18
+ extensions: readonly RequiredChildExtension[];
19
+ }
20
+
21
+ export interface RequiredChildExtensionRegistration { dispose(): void }
22
+ export type RequiredChildExtensionSnapshot = ReadonlyArray<Readonly<RequiredChildExtension>>;
23
+
24
+ /** Validate and freeze a snapshot; registration canonicalizes once, while retained launches preserve that identity. */
25
+ export function snapshotRequiredChildExtensions(value: unknown, label = "Required child extensions", canonicalizeFiles = false): RequiredChildExtensionSnapshot {
26
+ if (!Array.isArray(value) || value.length > MAX_REQUIRED_EXTENSIONS) throw new Error(`${label} must be an array of at most ${MAX_REQUIRED_EXTENSIONS} entries.`);
27
+ const ids = new Set<string>();
28
+ const paths = new Set<string>();
29
+ return Object.freeze(value.map((entry, index) => {
30
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.keys(entry).some((key) => key !== "id" && key !== "path")) throw new Error(`${label} entry ${index} requires only id and path.`);
31
+ const id = "id" in entry ? entry.id : undefined;
32
+ const rawPath = "path" in entry ? entry.path : undefined;
33
+ if (typeof id !== "string" || !ID_PATTERN.test(id)) throw new Error(`${label} entry ${index} requires a safe id of at most 128 characters.`);
34
+ if (ids.has(id)) throw new Error(`${label} id '${id}' is duplicated.`);
35
+ if (typeof rawPath !== "string" || !rawPath.trim() || rawPath.includes("\0") || Buffer.byteLength(rawPath, "utf8") > MAX_PATH_BYTES || (!canonicalizeFiles && !path.isAbsolute(rawPath))) throw new Error(`${label} '${id}' requires ${canonicalizeFiles ? "a" : "an absolute"} non-empty path of at most ${MAX_PATH_BYTES} bytes without NUL.`);
36
+ let extensionPath = rawPath;
37
+ if (canonicalizeFiles) {
38
+ try {
39
+ extensionPath = fs.realpathSync(path.resolve(rawPath));
40
+ if (!fs.statSync(extensionPath).isFile()) throw new Error("not a file");
41
+ } catch (error) {
42
+ throw new Error(`${label} '${id}' is not an importable file: ${error instanceof Error ? error.message : String(error)}`);
43
+ }
44
+ }
45
+ if (paths.has(extensionPath)) throw new Error(`${label} path '${extensionPath}' is duplicated.`);
46
+ ids.add(id);
47
+ paths.add(extensionPath);
48
+ return Object.freeze({ id, path: extensionPath });
49
+ }));
50
+ }
51
+
52
+ interface Registry { version: 1; bySession: Map<string, RequiredChildExtensionSnapshot> }
53
+
54
+ function registry(): Registry {
55
+ const key = Symbol.for("pi-subagents.required-child-extensions.v1");
56
+ const root = globalThis as Record<PropertyKey, unknown>;
57
+ const existing = root[key];
58
+ if (existing === undefined) {
59
+ const created: Registry = { version: 1, bySession: new Map() };
60
+ root[key] = created;
61
+ return created;
62
+ }
63
+ if (!existing || typeof existing !== "object" || !("version" in existing) || existing.version !== 1 || !("bySession" in existing) || !(existing.bySession instanceof Map)) throw new Error("Malformed or unsupported required child extension registry.");
64
+ return { version: 1, bySession: existing.bySession };
65
+ }
66
+
67
+ /** Register one immutable host-required extension snapshot for a parent session. */
68
+ export function registerRequiredChildExtensions(input: RegisterRequiredChildExtensionsInput): RequiredChildExtensionRegistration {
69
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => key !== "sessionId" && key !== "extensions")) throw new Error("Required child extension registration requires only sessionId and extensions.");
70
+ if (typeof input.sessionId !== "string" || !input.sessionId || input.sessionId.trim() !== input.sessionId || input.sessionId.length > 256 || input.sessionId.includes("\0")) throw new Error("Required child extension registration requires a non-empty trimmed sessionId of at most 256 characters without NUL.");
71
+ const frozen = snapshotRequiredChildExtensions(input.extensions, "Required child extensions", true);
72
+ const store = registry();
73
+ if (store.bySession.has(input.sessionId)) throw new Error(`Required child extensions are already registered for session '${input.sessionId}'; dispose them first.`);
74
+ store.bySession.set(input.sessionId, frozen);
75
+ return { dispose() { if (store.bySession.get(input.sessionId) === frozen) store.bySession.delete(input.sessionId); } };
76
+ }
77
+
78
+ export function resolveRequiredChildExtensions(sessionId: string | undefined): RequiredChildExtensionSnapshot {
79
+ if (!sessionId) return EMPTY_SNAPSHOT;
80
+ return registry().bySession.get(sessionId) ?? EMPTY_SNAPSHOT;
81
+ }
@@ -32,8 +32,9 @@ export interface SequentialStep {
32
32
  phase?: string;
33
33
  label?: string;
34
34
  as?: string;
35
- outputSchema?: JsonSchemaObject;
35
+ outputSchema?: JsonSchemaObject | false;
36
36
  cwd?: string;
37
+ machine?: string;
37
38
  output?: OutputOverrideInput;
38
39
  outputMode?: OutputMode;
39
40
  reads?: string[] | false;
@@ -56,8 +57,9 @@ export interface ParallelTaskItem {
56
57
  phase?: string;
57
58
  label?: string;
58
59
  as?: string;
59
- outputSchema?: JsonSchemaObject;
60
+ outputSchema?: JsonSchemaObject | false;
60
61
  cwd?: string;
62
+ machine?: string;
61
63
  count?: number;
62
64
  output?: OutputOverrideInput;
63
65
  outputMode?: OutputMode;
@@ -110,6 +112,7 @@ export interface ParallelStep {
110
112
  failFast?: boolean;
111
113
  worktree?: boolean;
112
114
  cwd?: string;
115
+ machine?: string;
113
116
  agentContract?: AgentContract;
114
117
  gateOn?: ChainGateLayer;
115
118
  }
@@ -1,7 +1,3 @@
1
- import { Key, type KeyId } from "@earendil-works/pi-tui";
2
-
3
- export const FLEET_OPEN_SHORTCUT: KeyId = Key.ctrlAlt("f");
4
-
5
1
  export function formatShortcutLabel(shortcut: string): string {
6
2
  return shortcut
7
3
  .split("+")