@xzzpig/pi-subagents 0.20.0 → 0.22.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 (144) hide show
  1. package/CHANGELOG.md +164 -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/fork-supervisor-routing.md +77 -0
  13. package/docs/missions.md +34 -17
  14. package/docs/models.md +1 -1
  15. package/docs/observability.md +10 -5
  16. package/docs/tool-reference.md +117 -84
  17. package/docs/watchdog.md +8 -6
  18. package/docs/workflows.md +16 -7
  19. package/index.ts +5 -0
  20. package/package.json +6 -3
  21. package/prompts/council.md +1 -1
  22. package/skills/pi-subagents/SKILL.md +1 -1
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  24. package/skills/pi-subagents/references/execution-controls.md +16 -16
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  26. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  27. package/src/agents/advertised-agent-prompt.ts +9 -1
  28. package/src/agents/agent-management.ts +4 -0
  29. package/src/agents/agent-memory.ts +3 -3
  30. package/src/agents/agent-scope.ts +4 -0
  31. package/src/agents/agent-serializer.ts +8 -1
  32. package/src/agents/agents.ts +191 -145
  33. package/src/api/preflight.ts +8 -4
  34. package/src/api/supervisor-routing.ts +196 -0
  35. package/src/extension/config.ts +21 -2
  36. package/src/extension/context-injection.ts +6 -1
  37. package/src/extension/control-notices.ts +1 -9
  38. package/src/extension/declaration-pinning.ts +164 -0
  39. package/src/extension/doctor.ts +7 -10
  40. package/src/extension/fanout-child.ts +7 -8
  41. package/src/extension/index.ts +143 -134
  42. package/src/extension/reply-workflow-script.ts +20 -11
  43. package/src/extension/rpc.ts +11 -6
  44. package/src/extension/schemas.ts +34 -30
  45. package/src/extension/subagent-guide.ts +86 -6
  46. package/src/extension/subagent-options.ts +47 -0
  47. package/src/extension/tool-activation.ts +3 -2
  48. package/src/extension/tool-description.ts +51 -68
  49. package/src/inspectors/actions.ts +37 -11
  50. package/src/inspectors/plugins.ts +3 -2
  51. package/src/inspectors/tmux/actions.ts +204 -0
  52. package/src/inspectors/tmux/client.ts +85 -0
  53. package/src/inspectors/tmux/plugin.ts +21 -0
  54. package/src/integrations/herdr-status.ts +18 -49
  55. package/src/integrations/program-status.ts +215 -0
  56. package/src/intercom/fork-supervisor-routing.ts +533 -0
  57. package/src/intercom/native-supervisor-channel.ts +152 -13
  58. package/src/intercom/result-intercom.ts +3 -2
  59. package/src/intercom/supervisor-ui.ts +2 -174
  60. package/src/missions/store.ts +25 -5
  61. package/src/profiles/profiles.ts +24 -21
  62. package/src/runs/background/active-async-capacity.ts +58 -8
  63. package/src/runs/background/async-execution.ts +143 -38
  64. package/src/runs/background/async-job-tracker.ts +11 -4
  65. package/src/runs/background/async-resume.ts +5 -2
  66. package/src/runs/background/await-async-run.ts +14 -9
  67. package/src/runs/background/binary-bootstrap.ts +2 -1
  68. package/src/runs/background/calendar-schedule.ts +90 -0
  69. package/src/runs/background/chain-root-attachment.ts +9 -5
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +16 -2
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-child-launch.ts +1 -0
  79. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  80. package/src/runs/background/scheduled-runs.ts +256 -61
  81. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  82. package/src/runs/background/subagent-runner.ts +32 -12
  83. package/src/runs/background/subagent-wait.ts +38 -19
  84. package/src/runs/background/terminal-run-index.ts +46 -1
  85. package/src/runs/background/wait-completions.ts +1 -0
  86. package/src/runs/background/wait-tool.ts +33 -23
  87. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  88. package/src/runs/foreground/async-stop-action.ts +48 -22
  89. package/src/runs/foreground/execution.ts +94 -52
  90. package/src/runs/foreground/foreground-history.ts +1 -0
  91. package/src/runs/foreground/subagent-executor.ts +232 -77
  92. package/src/runs/shared/child-commands.ts +2 -1
  93. package/src/runs/shared/child-hooks.ts +4 -3
  94. package/src/runs/shared/child-launch.ts +3 -0
  95. package/src/runs/shared/child-session.ts +41 -24
  96. package/src/runs/shared/child-tool-plan.ts +13 -26
  97. package/src/runs/shared/dynamic-fanout.ts +1 -1
  98. package/src/runs/shared/fork-command-result.ts +10 -0
  99. package/src/runs/shared/herdr-placed-run.ts +5 -4
  100. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  101. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  102. package/src/runs/shared/model-resolution.ts +30 -1
  103. package/src/runs/shared/nested-events.ts +5 -0
  104. package/src/runs/shared/parallel-handoff.ts +56 -8
  105. package/src/runs/shared/parallel-utils.ts +2 -0
  106. package/src/runs/shared/partial-output.ts +48 -0
  107. package/src/runs/shared/runner-launcher.ts +25 -0
  108. package/src/runs/shared/single-output.ts +53 -0
  109. package/src/runs/shared/structured-output.ts +14 -7
  110. package/src/runs/shared/subagent-control.ts +3 -3
  111. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  112. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  113. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  114. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  115. package/src/runs/shared/worktree-lock.ts +29 -0
  116. package/src/runs/shared/worktree.ts +12 -1
  117. package/src/shared/atomic-json.ts +4 -2
  118. package/src/shared/edit-distance.ts +33 -0
  119. package/src/shared/file-lease.ts +74 -0
  120. package/src/shared/formatters.ts +1 -5
  121. package/src/shared/model-info.ts +22 -0
  122. package/src/shared/package-version.ts +17 -0
  123. package/src/shared/parent-wake.ts +79 -0
  124. package/src/shared/pruned-fork.ts +7 -1
  125. package/src/shared/runtime-module-path.ts +19 -0
  126. package/src/shared/settings-file-lease.ts +36 -0
  127. package/src/shared/types.ts +36 -2
  128. package/src/shared/utils.ts +8 -6
  129. package/src/slash/prompt-template-bridge.ts +21 -20
  130. package/src/slash/slash-commands.ts +3 -3
  131. package/src/slash/subagents-admin.ts +2 -1
  132. package/src/tui/fleet-native-transcript.ts +2 -0
  133. package/src/tui/fleet-transcript.ts +12 -3
  134. package/src/tui/fleet.ts +11 -8
  135. package/src/tui/render.ts +27 -19
  136. package/src/tui/subagent-messages.ts +305 -0
  137. package/src/watchdog/diff-tool.ts +2 -2
  138. package/src/watchdog/register-main.ts +2 -22
  139. package/src/watchdog/render.ts +2 -24
  140. package/src/watchdog/runtime.ts +6 -4
  141. package/src/watchdog/settings.ts +18 -13
  142. package/src/watchdog/tool-actions.ts +2 -2
  143. package/src/workflows/scripted-workflow.ts +20 -6
  144. package/src/workflows/workflow-resources.ts +11 -0
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Versioned cross-extension supervisor-responder routing API (fork-only).
3
+ *
4
+ * A consumer extension (pi-goal-x's completion audit) registers one responder
5
+ * for ONE exact delegation attempt before the request is emitted. The
6
+ * pi-subagents owner binds that registration to the real child route (runId +
7
+ * canonical agent + childIndex) before the child's first prompt, and then
8
+ * hands that attempt's `need_decision` / `interview_request` asks to the
9
+ * responder instead of waking the parent model or detaching the child.
10
+ *
11
+ * The registration travels through the same synchronous, in-process event
12
+ * contract as `runtime-agent-events.ts`: the client emits a request object and
13
+ * reads the owner's result back out of that same object, so an owner that is
14
+ * missing, not ready, or older than this API fails closed with an actionable
15
+ * error instead of silently degrading to native wake/detach.
16
+ *
17
+ * This module is deliberately types + constants + the client call only. The
18
+ * owner-side registry, launch binding and ask dispatcher live in
19
+ * `../intercom/fork-supervisor-routing.ts` so the model-facing surface stays
20
+ * unchanged.
21
+ */
22
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
23
+
24
+ export const SUPERVISOR_RESPONDER_REGISTER_EVENT = "pi-subagents:supervisor-responder-register:v1";
25
+ export const SUPERVISOR_RESPONDER_REGISTER_VERSION = 1;
26
+
27
+ /**
28
+ * Identity of the one delegation attempt a responder owns.
29
+ *
30
+ * `requestId` is the DELEGATION attempt id (the id the structured delegation
31
+ * request was emitted with), never the supervisor ask id. `agent` is the agent
32
+ * name the request asked for; the owner binds the canonical resolved agent
33
+ * separately, so an alias can never be used to take over another agent's asks.
34
+ */
35
+ export interface SupervisorResponderScope {
36
+ sessionId: string;
37
+ requestId: string;
38
+ ownerRunId: string;
39
+ nodeId: string;
40
+ agent: string;
41
+ }
42
+
43
+ export type SupervisorResponderReason = "need_decision" | "interview_request" | "progress_update";
44
+
45
+ /**
46
+ * One supervisor ask routed to a responder.
47
+ *
48
+ * `requestId` here is the ASK id (the native supervisor request id); consumers
49
+ * that keep a coordination record rename it to `supervisorRequestId` to keep it
50
+ * distinct from `SupervisorResponderScope.requestId`.
51
+ */
52
+ export interface SupervisorResponderRequest {
53
+ requestId: string;
54
+ reason: SupervisorResponderReason;
55
+ message: string;
56
+ interview?: unknown;
57
+ runId: string;
58
+ agent: string;
59
+ childIndex: number;
60
+ /** Absolute deadline for this ask; absent means only the audit deadline applies. */
61
+ deadlineAt?: number;
62
+ signal: AbortSignal;
63
+ }
64
+
65
+ export type SupervisorResponderOutcome =
66
+ | { kind: "reply"; message: string }
67
+ | { kind: "error"; code: string; message: string };
68
+
69
+ export type SupervisorResponder = (
70
+ request: SupervisorResponderRequest,
71
+ ) => SupervisorResponderOutcome | Promise<SupervisorResponderOutcome>;
72
+
73
+ /** Owner-side handle returned through the registration event. */
74
+ export interface SupervisorResponderRegistration {
75
+ /** Idempotent; removes only this registration. */
76
+ dispose(): void;
77
+ }
78
+
79
+ export type SupervisorResponderRegistrationResult =
80
+ | { ok: true; registration: SupervisorResponderRegistration }
81
+ | { ok: false; error: Error };
82
+
83
+ export interface SupervisorResponderRegistrationRequest {
84
+ version: 1;
85
+ scope: SupervisorResponderScope;
86
+ respond: SupervisorResponder;
87
+ /** Called at most once per scope when a claimed ask cannot be answered or delivered. */
88
+ onFailure?: (error: Error) => void;
89
+ result?: SupervisorResponderRegistrationResult;
90
+ }
91
+
92
+ export interface RegisterSupervisorResponderViaEventsInput {
93
+ pi: Pick<ExtensionAPI, "events">;
94
+ scope: SupervisorResponderScope;
95
+ respond: SupervisorResponder;
96
+ onFailure?: (error: Error) => void;
97
+ }
98
+
99
+ const MAX_IDENTITY_LENGTH = 256;
100
+ const IDENTITY_FIELDS = ["sessionId", "requestId", "ownerRunId", "nodeId", "agent"] as const;
101
+
102
+ function identityError(field: string, reason: string): string {
103
+ return `Supervisor responder scope.${field} ${reason}.`;
104
+ }
105
+
106
+ /**
107
+ * Validate a scope strictly: every identity field must be present, non-empty,
108
+ * CR/LF-free and within the delegation identity byte budget. A scope that only
109
+ * names an agent (the "take over every ask of this agent" shape) is refused.
110
+ */
111
+ export function validateSupervisorResponderScope(
112
+ scope: unknown,
113
+ ): { scope: SupervisorResponderScope } | { error: string } {
114
+ if (!scope || typeof scope !== "object" || Array.isArray(scope)) {
115
+ return { error: "Supervisor responder scope must be an object." };
116
+ }
117
+ const candidate = scope as Record<string, unknown>;
118
+ for (const field of IDENTITY_FIELDS) {
119
+ const value = candidate[field];
120
+ if (typeof value !== "string") return { error: identityError(field, "must be a string") };
121
+ if (!value.trim()) return { error: identityError(field, "must not be empty") };
122
+ if (value.length > MAX_IDENTITY_LENGTH) {
123
+ return { error: identityError(field, `must be at most ${MAX_IDENTITY_LENGTH} characters`) };
124
+ }
125
+ if (/[\r\n]/.test(value)) return { error: identityError(field, "must not contain CR or LF") };
126
+ }
127
+ if (candidate.agent === "*") {
128
+ return { error: "Supervisor responder scope.agent must name one agent; wildcard takeover is not supported." };
129
+ }
130
+ return {
131
+ scope: {
132
+ sessionId: candidate.sessionId as string,
133
+ requestId: candidate.requestId as string,
134
+ ownerRunId: candidate.ownerRunId as string,
135
+ nodeId: candidate.nodeId as string,
136
+ agent: candidate.agent as string,
137
+ },
138
+ };
139
+ }
140
+
141
+ function errorFrom(value: unknown): Error {
142
+ return value instanceof Error ? value : new Error(String(value));
143
+ }
144
+
145
+ /**
146
+ * Register a responder for one exact delegation attempt through the installed
147
+ * pi-subagents owner in this Pi process. Throws an actionable error when the
148
+ * owner is missing, older than this API, or refuses the registration.
149
+ */
150
+ export function registerSupervisorResponderViaEvents(
151
+ input: RegisterSupervisorResponderViaEventsInput,
152
+ ): SupervisorResponderRegistration {
153
+ const validated = validateSupervisorResponderScope(input.scope);
154
+ if ("error" in validated) throw new Error(validated.error);
155
+ if (typeof input.respond !== "function") {
156
+ throw new Error("Supervisor responder must be a function: (request) => outcome.");
157
+ }
158
+ if (input.onFailure !== undefined && typeof input.onFailure !== "function") {
159
+ throw new Error("Supervisor responder onFailure must be a function when provided.");
160
+ }
161
+ const request: SupervisorResponderRegistrationRequest = {
162
+ version: SUPERVISOR_RESPONDER_REGISTER_VERSION,
163
+ scope: validated.scope,
164
+ respond: input.respond,
165
+ ...(input.onFailure ? { onFailure: input.onFailure } : {}),
166
+ };
167
+ input.pi.events.emit(SUPERVISOR_RESPONDER_REGISTER_EVENT, request);
168
+ const result = request.result as unknown;
169
+ if (result === undefined) {
170
+ throw new Error(
171
+ "pi-subagents is not installed, not ready, or does not support supervisor responder event registration.",
172
+ );
173
+ }
174
+ if (result && typeof result === "object" && !Array.isArray(result)) {
175
+ const candidate = result as Record<string, unknown>;
176
+ if (
177
+ candidate.ok === true &&
178
+ candidate.registration &&
179
+ typeof candidate.registration === "object" &&
180
+ typeof (candidate.registration as { dispose?: unknown }).dispose === "function"
181
+ ) {
182
+ const registration = candidate.registration as SupervisorResponderRegistration;
183
+ let disposed = false;
184
+ return {
185
+ dispose: () => {
186
+ if (disposed) return;
187
+ disposed = true;
188
+ registration.dispose();
189
+ },
190
+ };
191
+ }
192
+ if (candidate.ok === false && candidate.error instanceof Error) throw candidate.error;
193
+ if (candidate.ok === false) throw errorFrom(candidate.error);
194
+ }
195
+ throw new Error("pi-subagents returned a malformed supervisor responder registration result.");
196
+ }
@@ -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;