@xzzpig/pi-subagents 0.20.0 → 0.21.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 (140) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { Key } from "@earendil-works/pi-tui";
5
- import { FLEET_KEYBINDING_ACTIONS, type ArtifactDirPreference, type ExtensionConfig } from "../shared/types.ts";
5
+ import { FLEET_KEYBINDING_ACTIONS, RUNNER_LAUNCHER_NAME_PATTERN, RUNNER_LAUNCHER_NAME_RULE, type ArtifactDirPreference, type ExtensionConfig } from "../shared/types.ts";
6
6
  import { validateMissionStoreConfig } from "../missions/store.ts";
7
7
  import { validateAuthorityPolicy } from "../policy/authority.ts";
8
8
  import { getAgentDir } from "../shared/utils.ts";
@@ -14,7 +14,7 @@ import { validateDisabledFeatures } from "../shared/disabled-features.ts";
14
14
 
15
15
  // Explicit route identity, worktree, checkpoint, and tool-surface policies must not be silently
16
16
  // discarded and replaced by the built-in defaults after validation fails.
17
- const FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation", "authorityPolicy", "permissions", "toolBudget"];
17
+ const FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation", "authorityPolicy", "permissions", "toolBudget", "runnerLaunchers"];
18
18
 
19
19
  const ARTIFACT_DIR_PREFERENCES = new Set<ArtifactDirPreference>(["project", "session", "temp"]);
20
20
  const FLEET_KEYBINDING_ACTION_SET = new Set<string>(FLEET_KEYBINDING_ACTIONS);
@@ -103,6 +103,18 @@ function validateCapacityConfig(value: unknown): void {
103
103
  }
104
104
  }
105
105
 
106
+ function validateRunnerLaunchersConfig(value: unknown): void {
107
+ if (value === undefined) return;
108
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.runnerLaunchers must be a JSON object mapping launcher names to argv arrays");
109
+ for (const [name, argv] of Object.entries(value)) {
110
+ const label = `config.runnerLaunchers[${JSON.stringify(name)}]`;
111
+ if (!RUNNER_LAUNCHER_NAME_PATTERN.test(name)) throw new Error(`${label} has an invalid name; launcher names ${RUNNER_LAUNCHER_NAME_RULE}`);
112
+ if (!Array.isArray(argv) || argv.length === 0 || argv.some((arg) => typeof arg !== "string" || !arg.trim() || arg.includes("\u0000"))) {
113
+ throw new Error(`${label} must be a non-empty argv array of non-blank strings without NUL characters`);
114
+ }
115
+ }
116
+ }
117
+
106
118
  function validateOrcaProgressTabsConfig(value: unknown): void {
107
119
  if (value === undefined) return;
108
120
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.orcaProgressTabs must be a JSON object");
@@ -175,6 +187,12 @@ function validateConfig(config: Record<string, unknown>): void {
175
187
  if (config.asyncWidgetCollapsed !== undefined && typeof config.asyncWidgetCollapsed !== "boolean") {
176
188
  throw new Error("config.asyncWidgetCollapsed must be a boolean");
177
189
  }
190
+ if (config.asyncWidgetLayout !== undefined && config.asyncWidgetLayout !== "adaptive" && config.asyncWidgetLayout !== "rows") {
191
+ throw new Error('config.asyncWidgetLayout must be "adaptive" or "rows"');
192
+ }
193
+ if (config.programStatus !== undefined && typeof config.programStatus !== "boolean") {
194
+ throw new Error("config.programStatus must be a boolean");
195
+ }
178
196
  if (config.toolActivation !== undefined && config.toolActivation !== "auto" && config.toolActivation !== "dynamic" && config.toolActivation !== "eager") {
179
197
  throw new Error('config.toolActivation must be "auto", "dynamic", or "eager"');
180
198
  }
@@ -190,6 +208,7 @@ function validateConfig(config: Record<string, unknown>): void {
190
208
  validateModelResponseAliases(config.modelResponseAliases);
191
209
  validateMainWindowRendererConfig(config.mainWindowRenderer);
192
210
  validateOrcaProgressTabsConfig(config.orcaProgressTabs);
211
+ validateRunnerLaunchersConfig(config.runnerLaunchers);
193
212
  }
194
213
 
195
214
  export function getConfigPath(): string {
@@ -89,8 +89,13 @@ export function resolveInjectableAgents(input: ResolveInjectableAgentsInput): Re
89
89
  * Returns `undefined` when nothing should change: empty block, or a prompt
90
90
  * that already carries the marker (forked/resumed chains replaying history).
91
91
  */
92
- export function applyInjectionBlock(input: { systemPrompt: string; block: string }): string | undefined {
92
+ export function applyInjectionBlock(input: { systemPrompt: string; block: string; replaceExisting?: boolean }): string | undefined {
93
93
  const { systemPrompt, block } = input;
94
+ if (input.replaceExisting) {
95
+ const base = systemPrompt.replace(/\n*<available_subagents>[\s\S]*<\/available_subagents>/g, "");
96
+ const next = block ? `${base}\n\n${block}` : base;
97
+ return next === systemPrompt ? undefined : next;
98
+ }
94
99
  if (!block) return undefined;
95
100
  if (systemPrompt.includes(SUBAGENT_INJECTION_MARKER)) return undefined;
96
101
  return `${systemPrompt}\n\n${block}`;
@@ -14,20 +14,12 @@ export interface SubagentControlMessageDetails {
14
14
  noticeDeferred?: boolean;
15
15
  }
16
16
 
17
- export function controlNoticeTarget(details: SubagentControlMessageDetails): string | undefined {
18
- return details.childIntercomTarget;
19
- }
20
-
21
- export function formatSubagentControlNotice(details: SubagentControlMessageDetails, content?: string): string {
22
- return details.noticeText ?? content ?? formatControlNoticeMessage(details.event, controlNoticeTarget(details));
23
- }
24
-
25
17
  function deliverControlNotice(input: {
26
18
  pi: Pick<ExtensionAPI, "sendMessage">;
27
19
  visibleControlNotices: Set<string>;
28
20
  details: SubagentControlMessageDetails;
29
21
  }): void {
30
- const childIntercomTarget = controlNoticeTarget(input.details);
22
+ const childIntercomTarget = input.details.childIntercomTarget;
31
23
  const key = controlNotificationKey(input.details.event, childIntercomTarget);
32
24
  if (input.visibleControlNotices.has(key)) return;
33
25
  input.visibleControlNotices.add(key);
@@ -0,0 +1,164 @@
1
+ import { declarationsEqual, getCurrentSystemMessage, toToolDeclaration, type Message, type SystemMessage, type Tool } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ import type { TSchema } from "typebox";
4
+
5
+ // Pi records each declared tool definition and prompt section in the session transcript and
6
+ // re-declares any difference before the next request. A changed tool or prompt section makes
7
+ // the provider re-read the whole conversation without its prompt cache, so a session keeps the
8
+ // pi-subagents definitions and prompt text it already declared. Only a session that never
9
+ // declared a tool gets its current definition.
10
+
11
+ type PinnableTool = ToolDefinition<TSchema, unknown>;
12
+
13
+ /** What a session declared for one tool; an absent snippet or guidelines keeps the current value. */
14
+ interface DeclaredPin {
15
+ declaration: Tool;
16
+ snippet?: { text?: string };
17
+ guidelines?: string[];
18
+ }
19
+
20
+ interface Pins {
21
+ current: Map<string, PinnableTool>;
22
+ declared: Map<string, DeclaredPin>;
23
+ registered: Map<string, string>;
24
+ /** The prompt sections the session transcript recorded, read on session events only. */
25
+ sections: Record<string, string | null>;
26
+ }
27
+
28
+ const pinsByApi = new WeakMap<ExtensionAPI, Pins>();
29
+ const GUIDELINES_PLACEHOLDER = "\u0000pi-subagents guidelines";
30
+
31
+ function pinnedDefinition(tool: PinnableTool, pin: DeclaredPin | undefined): PinnableTool {
32
+ const { constrainedSampling, promptSnippet, promptGuidelines, ...rest } = tool;
33
+ // An unchanged declaration keeps the registered schema object rather than its JSON copy.
34
+ const declaration = pin && !declarationsEqual(pin.declaration, tool) ? pin.declaration : undefined;
35
+ const definition: PinnableTool = { ...rest, description: declaration?.description ?? rest.description, parameters: declaration?.parameters ?? rest.parameters };
36
+ const sampling = declaration ? declaration.constrainedSampling : constrainedSampling;
37
+ if (sampling !== undefined) definition.constrainedSampling = sampling;
38
+ const snippet = pin?.snippet ? pin.snippet.text : promptSnippet;
39
+ if (snippet !== undefined) definition.promptSnippet = snippet;
40
+ const guidelines = pin?.guidelines ?? promptGuidelines;
41
+ if (guidelines !== undefined) definition.promptGuidelines = guidelines;
42
+ return definition;
43
+ }
44
+
45
+ function register(pi: ExtensionAPI, pins: Pins, name: string): void {
46
+ const definition = pinnedDefinition(pins.current.get(name)!, pins.declared.get(name));
47
+ const key = JSON.stringify([toToolDeclaration(definition), definition.promptSnippet, definition.promptGuidelines]);
48
+ if (pins.registered.get(name) === key) return;
49
+ pins.registered.set(name, key);
50
+ pi.registerTool(definition);
51
+ }
52
+
53
+ function sectionLines(text: string | undefined, name: string): string[] | undefined {
54
+ const lines = text?.split("\n") ?? [];
55
+ const start = lines.indexOf(`<${name}>`);
56
+ const end = lines.indexOf(`</${name}>`, start + 1);
57
+ return start >= 0 && end > start ? lines.slice(start + 1, end) : undefined;
58
+ }
59
+
60
+ /** Mirrors the unexported buildRules of Pi's default system prompt, without prompt-level guidelines. */
61
+ function ruleLines(activeTools: string[], guidelines: Map<string, string[]>): string[] {
62
+ const lines: string[] = [];
63
+ const add = (rule: string): void => {
64
+ const line = `- ${rule.trim()}`;
65
+ if (line !== "- " && !lines.includes(line)) lines.push(line);
66
+ };
67
+ const active = (name: string) => activeTools.includes(name);
68
+ if ((active("bash") || active("powershell")) && !active("grep") && !active("find") && !active("ls")) {
69
+ if (active("bash") && active("powershell")) add("Use bash or PowerShell for file operations like listing, searching, and finding files");
70
+ else if (active("powershell")) add("Use PowerShell for file operations like listing, searching, and finding files");
71
+ else add("Use bash for file operations like ls, rg, find");
72
+ }
73
+ for (const name of activeTools) for (const rule of guidelines.get(name) ?? []) add(rule);
74
+ add("Be concise in your responses");
75
+ add("Show file paths clearly when working with files");
76
+ return lines;
77
+ }
78
+
79
+ const sameLines = (left: string[], right: string[]) => left.length === right.length && left.every((line, index) => line === right[index]);
80
+
81
+ /**
82
+ * The rules section does not say which tool contributed a bullet, so a declared tool's guidelines
83
+ * are recovered by rebuilding the recorded rules with candidate bullets at that tool's position.
84
+ * Nothing is recovered unless the rebuild first reproduces Pi's current rules.
85
+ */
86
+ function recordedGuidelines(pi: ExtensionAPI, ctx: ExtensionContext, recorded: string[], names: string[]): Map<string, string[]> {
87
+ const recovered = new Map<string, string[]>();
88
+ const activeTools = pi.getActiveTools();
89
+ const guidelines = new Map(pi.getAllTools().map((tool) => [tool.name, tool.promptGuidelines ?? []]));
90
+ const current = sectionLines(ctx.getSystemPrompt(), "rules");
91
+ if (!current || !sameLines(ruleLines(activeTools, guidelines), current)) return recovered;
92
+ const rebuild = (name: string, candidate: string[]) => ruleLines(activeTools, new Map(guidelines).set(name, candidate));
93
+ for (const name of names) {
94
+ const start = rebuild(name, [GUIDELINES_PLACEHOLDER]).indexOf(`- ${GUIDELINES_PLACEHOLDER}`);
95
+ if (start < 0) continue;
96
+ const candidate = recorded.slice(start, start + recorded.length - rebuild(name, []).length).map((line) => line.slice(2));
97
+ if (!sameLines(rebuild(name, candidate), recorded)) continue;
98
+ guidelines.set(name, candidate);
99
+ recovered.set(name, candidate);
100
+ }
101
+ return recovered;
102
+ }
103
+
104
+ function recordedSystemMessage(ctx: ExtensionContext | undefined): SystemMessage | undefined {
105
+ // SAFETY: Pi's session manager exposes buildSessionContext, but its read-only extension type omits it.
106
+ const sessionManager = ctx?.sessionManager as (ExtensionContext["sessionManager"] & { buildSessionContext?(): { messages: Message[] } }) | undefined;
107
+ // A host without a readable transcript, such as a test double, declares nothing to keep.
108
+ if (typeof sessionManager?.buildSessionContext !== "function") return undefined;
109
+ return getCurrentSystemMessage(sessionManager.buildSessionContext().messages);
110
+ }
111
+
112
+ function declaredPins(pi: ExtensionAPI, pins: Pins, ctx: ExtensionContext | undefined, system: SystemMessage | undefined): Map<string, DeclaredPin> {
113
+ if (!ctx || !system) return new Map();
114
+ const declarations = system.toolsAdded ?? [];
115
+ const snippets = sectionLines(system.sections?.tools ?? undefined, "tools");
116
+ const rules = sectionLines(system.sections?.rules ?? undefined, "rules");
117
+ const guidelines = rules ? recordedGuidelines(pi, ctx, rules, declarations.map((tool) => tool.name).filter((name) => pins.current.has(name))) : new Map<string, string[]>();
118
+ return new Map(declarations.map((declaration) => {
119
+ const pin: DeclaredPin = { declaration };
120
+ // Pi renders each snippet on one line as "- <tool>: <snippet>".
121
+ if (snippets) pin.snippet = { text: snippets.find((line) => line.startsWith(`- ${declaration.name}: `))?.slice(declaration.name.length + 4) };
122
+ const recovered = guidelines.get(declaration.name);
123
+ if (recovered) pin.guidelines = recovered;
124
+ return [declaration.name, pin];
125
+ }));
126
+ }
127
+
128
+ function pinsFor(pi: ExtensionAPI): Pins {
129
+ const existing = pinsByApi.get(pi);
130
+ if (existing) return existing;
131
+ const pins: Pins = { current: new Map(), declared: new Map(), registered: new Map(), sections: {} };
132
+ pinsByApi.set(pi, pins);
133
+ // Pi restores the transcript's active tools before both events, so handler order does not matter.
134
+ const refresh = (ctx: ExtensionContext | undefined) => {
135
+ const system = recordedSystemMessage(ctx);
136
+ pins.sections = system?.sections ?? {};
137
+ pins.declared = declaredPins(pi, pins, ctx, system);
138
+ for (const name of pins.current.keys()) register(pi, pins, name);
139
+ };
140
+ pi.on("session_start", (_event, ctx) => refresh(ctx));
141
+ pi.on("session_tree", (_event, ctx) => refresh(ctx));
142
+ return pins;
143
+ }
144
+
145
+ /**
146
+ * The text, without its tags, that the session transcript recorded for one of the prompt sections
147
+ * pi-subagents adds, so that section can keep the wording the session already sent.
148
+ * A session that never recorded the section gets undefined.
149
+ */
150
+ export function recordedPromptSection(pi: ExtensionAPI, name: string): string | undefined {
151
+ return sectionLines(pinsFor(pi).sections[name] ?? undefined, name)?.join("\n");
152
+ }
153
+
154
+ /**
155
+ * Register a pi-subagents tool so a session keeps the definition, prompt snippet and guidelines
156
+ * its transcript already declared. Only a session that never declared the tool gets this definition.
157
+ */
158
+ export function registerPinnedTool<TParams extends TSchema, TDetails>(pi: ExtensionAPI, tool: ToolDefinition<TParams, TDetails>): void {
159
+ const pins = pinsFor(pi);
160
+ // SAFETY: Pinning reads only model-facing fields and re-registers every runtime field unchanged.
161
+ pins.current.set(tool.name, tool as unknown as PinnableTool);
162
+ pins.registered.delete(tool.name);
163
+ register(pi, pins, tool.name);
164
+ }
@@ -4,16 +4,16 @@ import { discoverAgentsAll, type AgentSource } from "../agents/agents.ts";
4
4
  import { mergeAgentsForScope } from "../agents/agent-selection.ts";
5
5
  import { resolveInjectableAgents } from "./context-injection.ts";
6
6
  import { isAsyncAvailable } from "../runs/background/async-execution.ts";
7
- import { formatSpawnBudgetSummary, getSpawnBudgetSnapshot } from "../runs/shared/spawn-budget.ts";
8
- import { getActiveAsyncCapacitySnapshot, resolveAbandonedSlotReleaseAfterMs, resolveMaxActiveAsyncRunsPerSession } from "../runs/background/active-async-capacity.ts";
9
-
7
+ import { formatSpawnBudgetSummary } from "../runs/shared/spawn-budget.ts";
10
8
  import { diagnoseIntercomBridge, type IntercomBridgeDiagnostic } from "../intercom/intercom-bridge.ts";
11
9
  import { discoverAvailableSkills, type SkillSource } from "../agents/skills.ts";
12
10
  import {
13
11
  DIRS,
14
12
  CHAIN_RUNS_DIR,
15
13
  TEMP_ROOT_DIR,
14
+ type ActiveAsyncCapacitySnapshot,
16
15
  type ExtensionConfig,
16
+ type SpawnBudgetSnapshot,
17
17
  type SubagentState,
18
18
  normalizeMaxSubagentSpawnsPerRun,
19
19
  resolveMaxSubagentSpawnsPerRun,
@@ -41,6 +41,8 @@ interface DoctorReportInput {
41
41
  requestedSessionDir?: string;
42
42
  currentSessionFile?: string | null;
43
43
  currentSessionId?: string | null;
44
+ spawnBudget: SpawnBudgetSnapshot;
45
+ activeAsyncCapacity: ActiveAsyncCapacitySnapshot;
44
46
  orchestratorTarget?: string;
45
47
  sessionError?: string;
46
48
  expandTilde?: (value: string) => string;
@@ -178,7 +180,7 @@ function formatIntercomDiagnostic(diagnostic: IntercomBridgeDiagnostic, context:
178
180
  }
179
181
 
180
182
  function formatSpawnBudgetSection(input: DoctorReportInput): string[] {
181
- const snapshot = getSpawnBudgetSnapshot(input.state, input.config, input.currentSessionId ?? input.state.currentSessionId);
183
+ const snapshot = input.spawnBudget;
182
184
  return [
183
185
  `- usage: ${formatSpawnBudgetSummary(snapshot)}`,
184
186
  `- recent grants: ${snapshot.grantHistory.length === 0
@@ -197,12 +199,7 @@ function formatRunFanoutSection(input: DoctorReportInput): string[] {
197
199
  }
198
200
 
199
201
  function formatActiveAsyncCapacitySection(input: DoctorReportInput): string[] {
200
- const limit = resolveMaxActiveAsyncRunsPerSession(input.config.maxActiveAsyncRunsPerSession);
201
- const sessionId = input.currentSessionId ?? input.state.currentSessionId;
202
- const snapshot = sessionId
203
- ? getActiveAsyncCapacitySnapshot(sessionId, limit, { liveWorkflowRunIds: new Set(input.state.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(input.config.capacity?.abandonedSlotReleaseAfterMs) })
204
- : { used: 0, limit: limit ?? 0 };
205
- input.state.activeAsyncCapacity = snapshot;
202
+ const snapshot = input.activeAsyncCapacity;
206
203
  return [
207
204
  `- usage: ${snapshot.used}/${snapshot.limit || "unlimited"} used`,
208
205
  "- scope: top-level async runs in the current parent session; foreground and nested workflow children are not charged again",
@@ -4,18 +4,19 @@ import * as path from "node:path";
4
4
  import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
5
5
  import { discoverAgents } from "../agents/agents.ts";
6
6
  import { getArtifactsDir } from "../shared/artifacts.ts";
7
- import { createSubagentExecutor, type SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
7
+ import { createSubagentExecutor } from "../runs/foreground/subagent-executor.ts";
8
8
  import { resolveWaitToolConfig } from "../runs/background/wait-config.ts";
9
9
  import type { ChildRuntimeConfig } from "../runs/shared/child-runtime-config.ts";
10
- import { readNestedControlRequests, resolveInheritedNestedRoute, type NestedRoute, writeNestedControlResult } from "../runs/shared/nested-events.ts";
10
+ import { nestedRunNotActiveMessage, readNestedControlRequests, resolveInheritedNestedRoute, type NestedRoute, writeNestedControlResult } from "../runs/shared/nested-events.ts";
11
11
  import { deliverSubagentIntercomMessageEvent } from "../intercom/result-intercom.ts";
12
12
  import { createNativeSupervisorChannel, NATIVE_SUPERVISOR_TOOL_NAME, resolveSupervisorChannelDir } from "../intercom/native-supervisor-channel.ts";
13
13
  import { readStatus } from "../shared/utils.ts";
14
14
  import { resolveSubagentIntercomTarget } from "../intercom/intercom-bridge.ts";
15
15
  import { createSubagentParamsSchema } from "./schemas.ts";
16
+ import { registerPinnedTool } from "./declaration-pinning.ts";
16
17
  import { resolveDisabledFeatureSurface } from "../shared/disabled-features.ts";
17
18
  import { finalizeToolResult } from "./tool-result.ts";
18
- import { removedModelWorkflowFieldError } from "./public-execution.ts";
19
+ import { flattenSubagentToolOptions } from "./subagent-options.ts";
19
20
  import { loadConfig, resolveAsyncByDefault } from "./config.ts";
20
21
  import { SUBAGENT_ASYNC_STARTED_EVENT, type AsyncStartedEvent, type Details, type SubagentState } from "../shared/types.ts";
21
22
  import { createChildExternalJobBridgeSweeper } from "../runs/shared/external-job-bridge.ts";
@@ -95,7 +96,7 @@ function startNestedControlInboxListener(pi: ExtensionAPI, state: SubagentState,
95
96
  try {
96
97
  const control = state.foregroundControls.get(request.targetRunId);
97
98
  if (!control) {
98
- message = `Nested run ${request.targetRunId} is not active in this fanout child.`;
99
+ message = nestedRunNotActiveMessage(request.targetRunId);
99
100
  } else if (request.action === "interrupt") {
100
101
  ok = control.interrupt?.() === true;
101
102
  message = ok
@@ -229,13 +230,11 @@ export default function registerFanoutChildSubagentExtension(pi: ExtensionAPI, c
229
230
  ].join("\n"),
230
231
  parameters: params,
231
232
  async execute(id, params, signal, onUpdate, ctx) {
232
- const removedField = removedModelWorkflowFieldError(params);
233
- if (removedField) throw new Error(removedField);
234
- return finalizeToolResult(await executor.executePublic(id, params as SubagentParamsLike, signal ?? new AbortController().signal, onUpdate, ctx));
233
+ return finalizeToolResult(await executor.executePublic(id, flattenSubagentToolOptions(params, disabledFeatures), signal ?? new AbortController().signal, onUpdate, ctx));
235
234
  },
236
235
  };
237
236
 
238
- pi.registerTool(tool);
237
+ registerPinnedTool(pi, tool);
239
238
  const bridgeSweeper = createChildExternalJobBridgeSweeper();
240
239
  const unsubscribeBridgeStarted = pi.events.on(SUBAGENT_ASYNC_STARTED_EVENT, (payload: unknown) => {
241
240
  const info = payload as AsyncStartedEvent;