@xzzpig/pi-subagents 0.1.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 (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,653 @@
1
+ import * as path from "node:path";
2
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
3
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { Compile } from "typebox/compile";
5
+ import { resolveAsyncRunLocation } from "../runs/background/async-resume.ts";
6
+ import { deliverStopRequest } from "../runs/background/control-channel.ts";
7
+ import { reconcileAsyncRun } from "../runs/background/stale-run-reconciler.ts";
8
+ import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
9
+ import { resolveCurrentSessionId } from "../shared/session-identity.ts";
10
+ import {
11
+ type AsyncJobStep,
12
+ type Details,
13
+ type SubagentState,
14
+ DIRS,
15
+ SUBAGENT_ASYNC_COMPLETE_EVENT,
16
+ SUBAGENT_PROCESS_TERMINAL_EVENT,
17
+ SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
18
+ } from "../shared/types.ts";
19
+ import { readStatus } from "../shared/utils.ts";
20
+ import { SubagentParams } from "./schemas.ts";
21
+ import { formatWorkflowJsonPreview } from "../workflows/scripted-workflow.ts";
22
+ import { normalizePublicSubagentExecution } from "./public-execution.ts";
23
+
24
+ export const SUBAGENT_RPC_PROTOCOL_VERSION = 1;
25
+ export const SUBAGENT_RPC_REQUEST_EVENT = "subagents:rpc:v1:request";
26
+ export const SUBAGENT_RPC_READY_EVENT = "subagents:rpc:v1:ready";
27
+ export const SUBAGENT_RPC_REPLY_EVENT_PREFIX = "subagents:rpc:v1:reply:";
28
+
29
+ export const SUBAGENT_RPC_METHODS = ["ping", "status", "spawn", "steer", "interrupt", "stop", "resume"] as const;
30
+ export type SubagentRpcMethod = typeof SUBAGENT_RPC_METHODS[number];
31
+
32
+ export interface SubagentRpcRequestEnvelope {
33
+ version: typeof SUBAGENT_RPC_PROTOCOL_VERSION;
34
+ requestId: string;
35
+ method: SubagentRpcMethod;
36
+ params?: unknown;
37
+ source?: {
38
+ extension?: string;
39
+ [key: string]: unknown;
40
+ };
41
+ }
42
+
43
+ export type SubagentRpcReplyEnvelope<T = unknown> = {
44
+ version: typeof SUBAGENT_RPC_PROTOCOL_VERSION;
45
+ requestId: string;
46
+ method?: SubagentRpcMethod;
47
+ success: true;
48
+ data: T;
49
+ } | {
50
+ version: typeof SUBAGENT_RPC_PROTOCOL_VERSION;
51
+ requestId: string;
52
+ method?: SubagentRpcMethod;
53
+ success: false;
54
+ error: {
55
+ code: SubagentRpcErrorCode;
56
+ message: string;
57
+ };
58
+ };
59
+
60
+ type SubagentRpcErrorCode =
61
+ | "invalid_request"
62
+ | "invalid_params"
63
+ | "unsupported_version"
64
+ | "unsupported_method"
65
+ | "no_active_session"
66
+ | "execution_failed"
67
+ | "not_found"
68
+ | "invalid_state";
69
+
70
+ interface EventBus {
71
+ on(event: string, handler: (data: unknown) => void): (() => void) | void;
72
+ emit(event: string, data: unknown): void;
73
+ }
74
+
75
+ export interface SubagentRpcFleetEntry {
76
+ /** Opaque key for client-side reconciliation; never a run or async identifier. */
77
+ key: string;
78
+ /** Resolved child agent/role name. */
79
+ agent: string;
80
+ role?: string;
81
+ model?: string;
82
+ effort?: string;
83
+ startedAt: number;
84
+ tokens: { input: number; output: number; total: number };
85
+ goal?: string;
86
+ }
87
+
88
+ export interface SubagentRpcFleetStatus {
89
+ version: 1;
90
+ entries: SubagentRpcFleetEntry[];
91
+ /** Total active children before the bounded entries window. */
92
+ totalActive: number;
93
+ omitted: number;
94
+ }
95
+
96
+ const MAX_FLEET_ENTRIES = 16;
97
+ const MAX_FLEET_CANDIDATES = 256;
98
+ const MAX_AGENT_LENGTH = 96;
99
+ const MAX_GOAL_LENGTH = 512;
100
+ const MAX_METADATA_LENGTH = 128;
101
+
102
+ function displayText(value: unknown, maxLength: number): string | undefined {
103
+ if (typeof value !== "string") return undefined;
104
+ // Strip complete CSI/OSC/DCS/APC/PM strings and C1 controls before collapsing
105
+ // whitespace; never leave CSI parameters behind after removing ESC.
106
+ const normalized = value.slice(0, 4_096)
107
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x9b[0-?]*[ -/]*[@-~]|\x1b][\s\S]*?(?:\x07|\x1b\\)|\x1b[PX^_][\s\S]*?\x1b\\|[\u0000-\u001f\u007f-\u009f]/g, " ")
108
+ .replace(/\s+/g, " ").trim();
109
+ return normalized ? normalized.slice(0, maxLength) : undefined;
110
+ }
111
+
112
+ function publicTokens(value: unknown): { input: number; output: number; total: number } {
113
+ const record = isRecord(value) ? value : {};
114
+ const count = (field: "input" | "output" | "total") => {
115
+ const raw = record[field];
116
+ return typeof raw === "number" && Number.isFinite(raw) && raw >= 0
117
+ ? Math.min(Number.MAX_SAFE_INTEGER, Math.floor(raw))
118
+ : 0;
119
+ };
120
+ const input = count("input");
121
+ const output = count("output");
122
+ const sum = Math.min(Number.MAX_SAFE_INTEGER, input + output);
123
+ return { input, output, total: Math.max(sum, count("total")) };
124
+ }
125
+
126
+ function activeState(value: unknown): boolean {
127
+ return value === "running" || value === "queued" || value === "pending";
128
+ }
129
+
130
+ interface FleetKeyState {
131
+ sessionId: string | null;
132
+ next: number;
133
+ keys: Map<string, string>;
134
+ }
135
+
136
+ interface FleetCandidate {
137
+ internalKey: string;
138
+ agent: unknown;
139
+ role?: unknown;
140
+ model?: unknown;
141
+ effort?: unknown;
142
+ startedAt: unknown;
143
+ tokens?: unknown;
144
+ goal?: unknown;
145
+ }
146
+
147
+ function buildFleetStatus(
148
+ state: SubagentState | undefined,
149
+ keyState: FleetKeyState,
150
+ sessionId: string | null | undefined,
151
+ ): SubagentRpcFleetStatus {
152
+ const authoritativeSessionId = sessionId ?? null;
153
+ if (keyState.sessionId !== authoritativeSessionId) {
154
+ keyState.sessionId = authoritativeSessionId;
155
+ keyState.next = 0;
156
+ keyState.keys.clear();
157
+ }
158
+ if (!state || !authoritativeSessionId || state.currentSessionId !== authoritativeSessionId) {
159
+ keyState.keys.clear();
160
+ return { version: 1, entries: [], totalActive: 0, omitted: 0 };
161
+ }
162
+
163
+ let totalActive = 0;
164
+ const candidates: FleetCandidate[] = [];
165
+ const addCandidate = (candidate: FleetCandidate) => {
166
+ totalActive += 1;
167
+ if (candidates.length < MAX_FLEET_CANDIDATES) candidates.push(candidate);
168
+ };
169
+ for (const control of state.foregroundControls.values()) {
170
+ if (control.sessionId !== authoritativeSessionId) continue;
171
+ if (control.activeChildren?.size) {
172
+ for (const child of control.activeChildren.values()) addCandidate({
173
+ internalKey: `foreground:${control.runId}:${child.index}`,
174
+ agent: child.agent,
175
+ model: child.model,
176
+ effort: child.thinking,
177
+ startedAt: child.startedAt,
178
+ tokens: { input: child.inputTokens ?? 0, output: child.outputTokens ?? 0, total: child.tokens ?? 0 },
179
+ goal: child.description ?? control.description,
180
+ });
181
+ } else {
182
+ addCandidate({
183
+ internalKey: `foreground:${control.runId}:${control.currentIndex ?? 0}`,
184
+ agent: control.currentAgent ?? control.mode,
185
+ model: control.model,
186
+ effort: control.thinking,
187
+ startedAt: control.startedAt,
188
+ tokens: { input: control.inputTokens ?? 0, output: control.outputTokens ?? 0, total: control.tokens ?? 0 },
189
+ goal: control.description,
190
+ });
191
+ }
192
+ }
193
+ for (const job of state.asyncJobs.values()) {
194
+ if (job.sessionId !== authoritativeSessionId || !activeState(job.status)) continue;
195
+ const startedAt = job.startedAt ?? job.updatedAt;
196
+ if (job.mode === "workflow") {
197
+ const latestEmit = job.workflow?.emits?.length ? formatWorkflowJsonPreview(job.workflow.emits.at(-1), 120) : undefined;
198
+ addCandidate({
199
+ internalKey: `async:${job.asyncId}`,
200
+ agent: "workflow",
201
+ startedAt,
202
+ tokens: job.totalTokens,
203
+ goal: latestEmit !== undefined ? `latest emit: ${latestEmit}` : job.description,
204
+ });
205
+ continue;
206
+ }
207
+ const steps: AsyncJobStep[] | undefined = job.steps?.length
208
+ ? job.steps
209
+ : job.agents?.map((agent, index) => ({
210
+ agent,
211
+ index,
212
+ status: job.status === "queued" ? "pending" : "running",
213
+ }));
214
+ if (!steps?.length) {
215
+ addCandidate({
216
+ internalKey: `async:${job.asyncId}`,
217
+ agent: job.mode ?? "subagent",
218
+ startedAt,
219
+ tokens: job.totalTokens,
220
+ goal: job.description,
221
+ });
222
+ continue;
223
+ }
224
+ for (const [offset, step] of steps.entries()) {
225
+ if (!activeState(step.status)) continue;
226
+ const index = step.index ?? offset;
227
+ if (step.status === "pending" && job.mode === "chain" && !job.activeParallelGroup && index !== (job.currentStep ?? 0)) continue;
228
+ addCandidate({
229
+ internalKey: `async:${job.asyncId}:${index}`,
230
+ agent: step.agent,
231
+ role: step.label,
232
+ model: step.model,
233
+ effort: step.thinking,
234
+ startedAt: step.startedAt ?? startedAt,
235
+ tokens: step.tokens ?? (steps.length === 1 ? job.totalTokens : undefined),
236
+ goal: job.description,
237
+ });
238
+ }
239
+ }
240
+
241
+ candidates.sort((left, right) => {
242
+ const leftStarted = typeof left.startedAt === "number" ? left.startedAt : Number.MAX_SAFE_INTEGER;
243
+ const rightStarted = typeof right.startedAt === "number" ? right.startedAt : Number.MAX_SAFE_INTEGER;
244
+ return leftStarted - rightStarted || left.internalKey.localeCompare(right.internalKey);
245
+ });
246
+ const activeKeys = new Set(candidates.map((candidate) => candidate.internalKey));
247
+ const entries: SubagentRpcFleetEntry[] = [];
248
+ for (const candidate of candidates) {
249
+ if (entries.length >= MAX_FLEET_ENTRIES) break;
250
+ const agent = displayText(candidate.agent, MAX_AGENT_LENGTH);
251
+ const startedAt = candidate.startedAt;
252
+ if (!agent || typeof startedAt !== "number" || !Number.isSafeInteger(startedAt) || startedAt < 0) continue;
253
+ let key = keyState.keys.get(candidate.internalKey);
254
+ if (!key) {
255
+ key = `fleet-${++keyState.next}`;
256
+ keyState.keys.set(candidate.internalKey, key);
257
+ }
258
+ const role = displayText(candidate.role, MAX_AGENT_LENGTH);
259
+ const model = displayText(candidate.model, MAX_METADATA_LENGTH);
260
+ const effort = displayText(candidate.effort, MAX_METADATA_LENGTH);
261
+ const goal = displayText(candidate.goal, MAX_GOAL_LENGTH);
262
+ entries.push({
263
+ key,
264
+ agent,
265
+ ...(role ? { role } : {}),
266
+ ...(model ? { model } : {}),
267
+ ...(effort ? { effort } : {}),
268
+ startedAt,
269
+ tokens: publicTokens(candidate.tokens),
270
+ ...(goal ? { goal } : {}),
271
+ });
272
+ }
273
+ for (const internalKey of keyState.keys.keys()) {
274
+ if (!activeKeys.has(internalKey)) keyState.keys.delete(internalKey);
275
+ }
276
+ const omitted = Math.max(0, totalActive - entries.length);
277
+ return { version: 1, entries, totalActive, omitted };
278
+ }
279
+
280
+ interface RegisterSubagentRpcBridgeOptions {
281
+ events: EventBus;
282
+ getContext: () => ExtensionContext | null;
283
+ execute: (
284
+ id: string,
285
+ params: SubagentParamsLike,
286
+ signal: AbortSignal,
287
+ onUpdate: ((result: AgentToolResult<Details>) => void) | undefined,
288
+ ctx: ExtensionContext,
289
+ ) => Promise<AgentToolResult<Details>>;
290
+ asyncDirRoot?: string;
291
+ resultsDir?: string;
292
+ kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
293
+ now?: () => number;
294
+ /** Native live state, projected into the optional public fleet-status capability. */
295
+ state?: SubagentState;
296
+ }
297
+
298
+ class SubagentRpcError extends Error {
299
+ readonly code: SubagentRpcErrorCode;
300
+
301
+ constructor(code: SubagentRpcErrorCode, message: string) {
302
+ super(message);
303
+ this.name = "SubagentRpcError";
304
+ this.code = code;
305
+ }
306
+ }
307
+
308
+ const subagentParamsValidator = Compile(SubagentParams);
309
+
310
+ export function subagentRpcReplyEvent(requestId: string): string {
311
+ return `${SUBAGENT_RPC_REPLY_EVENT_PREFIX}${requestId}`;
312
+ }
313
+
314
+ function isRecord(value: unknown): value is Record<string, unknown> {
315
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
316
+ }
317
+
318
+ function assertRequestId(value: unknown): string {
319
+ if (typeof value !== "string" || value.trim().length === 0 || /[\r\n]/.test(value)) {
320
+ throw new SubagentRpcError("invalid_request", "RPC requestId must be a non-empty string without newlines.");
321
+ }
322
+ return value;
323
+ }
324
+
325
+ function assertRecordParams(params: unknown, method: SubagentRpcMethod): Record<string, unknown> {
326
+ if (params === undefined) return {};
327
+ if (!isRecord(params)) throw new SubagentRpcError("invalid_params", `RPC ${method} params must be an object.`);
328
+ return params;
329
+ }
330
+
331
+ function assertSubagentParams(params: SubagentParamsLike, label: string): void {
332
+ if (subagentParamsValidator.Check(params)) return;
333
+ const messages = [...subagentParamsValidator.Errors(params)]
334
+ .slice(0, 4)
335
+ .map((error) => error.message);
336
+ throw new SubagentRpcError("invalid_params", `${label}: ${messages.join("; ") || "invalid subagent parameters"}`);
337
+ }
338
+
339
+ function textFromToolResult(result: AgentToolResult<Details>): string {
340
+ return result.content
341
+ .filter((part): part is { type: "text"; text: string } => part.type === "text")
342
+ .map((part) => part.text)
343
+ .join("\n");
344
+ }
345
+
346
+ type ToolResultWithError = AgentToolResult<Details> & { isError?: boolean };
347
+
348
+ function dataFromToolResult(result: ToolResultWithError): { text: string; details?: Details; isError?: boolean } {
349
+ return {
350
+ text: textFromToolResult(result),
351
+ ...(result.details ? { details: result.details } : {}),
352
+ ...(result.isError ? { isError: true } : {}),
353
+ };
354
+ }
355
+
356
+ function failIfToolError(result: ToolResultWithError): void {
357
+ if (!result.isError) return;
358
+ throw new SubagentRpcError("execution_failed", textFromToolResult(result) || "Subagent RPC execution failed.");
359
+ }
360
+
361
+ function normalizeTargetParams(params: unknown, method: SubagentRpcMethod): Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> {
362
+ const input = assertRecordParams(params, method);
363
+ const output: Pick<SubagentParamsLike, "id" | "runId" | "dir" | "index"> = {};
364
+ if (input.id !== undefined) output.id = input.id as string;
365
+ if (input.runId !== undefined) output.runId = input.runId as string;
366
+ if (input.dir !== undefined) output.dir = input.dir as string;
367
+ if (input.index !== undefined) output.index = input.index as number;
368
+ return output;
369
+ }
370
+
371
+ function sessionData(ctx: ExtensionContext | null): { cwd?: string; sessionId?: string; sessionFile?: string | null } {
372
+ if (!ctx) return {};
373
+ return {
374
+ cwd: ctx.cwd,
375
+ sessionId: ctx.sessionManager.getSessionId() ?? undefined,
376
+ sessionFile: ctx.sessionManager.getSessionFile() ?? null,
377
+ };
378
+ }
379
+
380
+ function pingData(ctx: ExtensionContext | null) {
381
+ return {
382
+ version: SUBAGENT_RPC_PROTOCOL_VERSION,
383
+ methods: [...SUBAGENT_RPC_METHODS],
384
+ capabilities: {
385
+ status: true,
386
+ fleetStatus: { version: 1 },
387
+ asyncSpawn: true,
388
+ steer: true,
389
+ nonRecoveringSteer: true,
390
+ interrupt: true,
391
+ stop: true,
392
+ resume: true,
393
+ launchResolvedExtensions: { version: 1, source: "launch-resolved" },
394
+ runtimeAcknowledgedExtensions: { version: 1, source: "child-runtime", event: "subagent:acknowledge-extension" },
395
+ processTerminalProof: { version: 1, lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION },
396
+ },
397
+ events: {
398
+ ready: SUBAGENT_RPC_READY_EVENT,
399
+ request: SUBAGENT_RPC_REQUEST_EVENT,
400
+ replyPrefix: SUBAGENT_RPC_REPLY_EVENT_PREFIX,
401
+ asyncComplete: SUBAGENT_ASYNC_COMPLETE_EVENT,
402
+ processTerminal: SUBAGENT_PROCESS_TERMINAL_EVENT,
403
+ },
404
+ session: sessionData(ctx),
405
+ };
406
+ }
407
+
408
+ async function executeChecked(
409
+ options: RegisterSubagentRpcBridgeOptions,
410
+ ctx: ExtensionContext,
411
+ requestId: string,
412
+ method: SubagentRpcMethod,
413
+ params: SubagentParamsLike,
414
+ ): Promise<{ text: string; details?: Details; isError?: boolean }> {
415
+ assertSubagentParams(params, `RPC ${method} params`);
416
+ const controller = new AbortController();
417
+ const result = await options.execute(`rpc-${method}-${requestId}`, params, controller.signal, undefined, ctx);
418
+ failIfToolError(result);
419
+ return dataFromToolResult(result);
420
+ }
421
+
422
+ function spawnParams(params: unknown): SubagentParamsLike {
423
+ const input = assertRecordParams(params, "spawn");
424
+ const normalized = normalizePublicSubagentExecution(input);
425
+ if (!normalized.ok) throw new SubagentRpcError("invalid_params", normalized.error);
426
+ if (normalized.params.action !== undefined) {
427
+ throw new SubagentRpcError("invalid_params", "RPC spawn does not accept management/control actions. Use status or interrupt RPC methods instead.");
428
+ }
429
+ if (input.async === false) {
430
+ throw new SubagentRpcError("invalid_params", "RPC spawn only supports detached async launches; omit async or set async: true.");
431
+ }
432
+ return { ...(normalized.params as SubagentParamsLike), async: true };
433
+ }
434
+
435
+ function steerParams(params: unknown): SubagentParamsLike {
436
+ const input = assertRecordParams(params, "steer");
437
+ if (typeof input.message !== "string" || !input.message.trim())
438
+ throw new SubagentRpcError("invalid_params", "RPC steer requires a non-empty message.");
439
+ const target = normalizeTargetParams(input, "steer");
440
+ if (!target.id && !target.runId && !target.dir) throw new SubagentRpcError("invalid_params", "RPC steer requires id, runId, or dir.");
441
+ if (input.mode !== undefined && input.mode !== "steer" && input.mode !== "follow_up" && input.mode !== "auto") throw new SubagentRpcError("invalid_params", "RPC steer mode must be steer, follow_up, or auto.");
442
+ return {
443
+ action: "steer",
444
+ ...target,
445
+ message: input.message.trim(),
446
+ ...(typeof input.mode === "string" ? { mode: input.mode as "steer" | "follow_up" | "auto" } : {}),
447
+ steeringRecovery: false,
448
+ };
449
+ }
450
+
451
+ function resumeParams(params: unknown): SubagentParamsLike {
452
+ const input = assertRecordParams(params, "resume");
453
+ if (typeof input.message !== "string" || !input.message.trim())
454
+ throw new SubagentRpcError("invalid_params", "RPC resume requires a non-empty message.");
455
+ const target = normalizeTargetParams(input, "resume");
456
+ if (!target.id && !target.runId && !target.dir) throw new SubagentRpcError("invalid_params", "RPC resume requires id, runId, or dir.");
457
+ if (input.output !== undefined && (typeof input.output !== "string" || !input.output.trim()))
458
+ throw new SubagentRpcError("invalid_params", "RPC resume output must be a non-empty path.");
459
+ if (input.outputMode !== undefined && input.outputMode !== "file-only")
460
+ throw new SubagentRpcError("invalid_params", "RPC resume supports only file-only output mode.");
461
+ return {
462
+ action: "resume",
463
+ ...target,
464
+ message: input.message.trim(),
465
+ ...(typeof input.output === "string" ? { output: input.output.trim(), outputMode: "file-only" } : {}),
466
+ };
467
+ }
468
+
469
+ function stopAsyncRun(
470
+ params: unknown,
471
+ options: RegisterSubagentRpcBridgeOptions,
472
+ ctx: ExtensionContext,
473
+ ): { runId: string; asyncDir: string; previousState: string; state: "stopping"; message: string } {
474
+ const target = normalizeTargetParams(params, "stop");
475
+ assertSubagentParams({ action: "status", ...target }, "RPC stop target params");
476
+ const asyncDirRoot = options.asyncDirRoot ?? DIRS.async;
477
+ const resultsDir = options.resultsDir ?? DIRS.results;
478
+ let location;
479
+ try {
480
+ location = resolveAsyncRunLocation(target, asyncDirRoot, resultsDir);
481
+ } catch (error) {
482
+ throw new SubagentRpcError("invalid_params", error instanceof Error ? error.message : String(error));
483
+ }
484
+ if (!location.asyncDir) {
485
+ throw new SubagentRpcError("not_found", "Async run not found or already completed; stop requires a live async run directory.");
486
+ }
487
+
488
+ const currentSessionId = resolveCurrentSessionId(ctx.sessionManager);
489
+ const initialStatus = readStatus(location.asyncDir);
490
+ const initialRunId = initialStatus?.runId ?? location.resolvedId ?? path.basename(location.asyncDir);
491
+ if (!initialStatus) throw new SubagentRpcError("not_found", `Status file not found for async run '${initialRunId}'.`);
492
+ if (!currentSessionId || initialStatus.sessionId !== currentSessionId) {
493
+ throw new SubagentRpcError("not_found", `Async run '${initialRunId}' was not found in the active session.`);
494
+ }
495
+
496
+ let status;
497
+ try {
498
+ status = reconcileAsyncRun(location.asyncDir, { resultsDir, kill: options.kill, now: options.now }).status;
499
+ } catch (error) {
500
+ throw new SubagentRpcError("execution_failed", error instanceof Error ? error.message : String(error));
501
+ }
502
+ const runId = status?.runId ?? initialRunId;
503
+ if (!status) throw new SubagentRpcError("not_found", `Status file not found for async run '${runId}'.`);
504
+ if (status.sessionId !== currentSessionId) {
505
+ throw new SubagentRpcError("not_found", `Async run '${runId}' was not found in the active session.`);
506
+ }
507
+ if (status.state !== "running") {
508
+ throw new SubagentRpcError("invalid_state", `Async run ${runId} is ${status.state}; stop only supports running async runs.`);
509
+ }
510
+
511
+ try {
512
+ deliverStopRequest({
513
+ asyncDir: location.asyncDir,
514
+ pid: status.pid,
515
+ kill: options.kill,
516
+ now: options.now,
517
+ source: "rpc-stop",
518
+ });
519
+ } catch (error) {
520
+ throw new SubagentRpcError("execution_failed", error instanceof Error ? error.message : String(error));
521
+ }
522
+
523
+ return {
524
+ runId,
525
+ asyncDir: location.asyncDir,
526
+ previousState: status.state,
527
+ state: "stopping",
528
+ message: `Stop requested for async run ${runId}.`,
529
+ };
530
+ }
531
+
532
+ async function handleRequest(
533
+ request: SubagentRpcRequestEnvelope,
534
+ options: RegisterSubagentRpcBridgeOptions,
535
+ fleetKeys: FleetKeyState,
536
+ ): Promise<unknown> {
537
+ const ctx = options.getContext();
538
+ if (request.method === "ping") return pingData(ctx);
539
+ if (!ctx) throw new SubagentRpcError("no_active_session", "No active extension context for subagent RPC.");
540
+
541
+ if (request.method === "spawn") {
542
+ return executeChecked(options, ctx, request.requestId, request.method, spawnParams(request.params));
543
+ }
544
+ if (request.method === "status") {
545
+ const status = await executeChecked(
546
+ options,
547
+ ctx,
548
+ request.requestId,
549
+ request.method,
550
+ { action: "status", ...normalizeTargetParams(request.params, "status") },
551
+ );
552
+ return {
553
+ ...status,
554
+ fleet: buildFleetStatus(
555
+ options.state,
556
+ fleetKeys,
557
+ resolveCurrentSessionId(ctx.sessionManager),
558
+ ),
559
+ };
560
+ }
561
+ if (request.method === "steer") {
562
+ return executeChecked(options, ctx, request.requestId, request.method, steerParams(request.params));
563
+ }
564
+ if (request.method === "interrupt") {
565
+ return executeChecked(options, ctx, request.requestId, request.method, { action: "interrupt", ...normalizeTargetParams(request.params, "interrupt") });
566
+ }
567
+ if (request.method === "stop") {
568
+ return stopAsyncRun(request.params, options, ctx);
569
+ }
570
+ if (request.method === "resume") {
571
+ return executeChecked(options, ctx, request.requestId, request.method, resumeParams(request.params));
572
+ }
573
+ throw new SubagentRpcError("unsupported_method", `Unsupported subagent RPC method: ${String(request.method)}`);
574
+ }
575
+
576
+ function parseRequest(raw: unknown): SubagentRpcRequestEnvelope {
577
+ if (!isRecord(raw)) throw new SubagentRpcError("invalid_request", "Subagent RPC request must be an object.");
578
+ const requestId = assertRequestId(raw.requestId);
579
+ if (raw.version !== SUBAGENT_RPC_PROTOCOL_VERSION) {
580
+ throw new SubagentRpcError("unsupported_version", `Unsupported subagent RPC version: ${String(raw.version)}.`);
581
+ }
582
+ if (typeof raw.method !== "string" || !(SUBAGENT_RPC_METHODS as readonly string[]).includes(raw.method)) {
583
+ throw new SubagentRpcError("unsupported_method", `Unsupported subagent RPC method: ${String(raw.method)}.`);
584
+ }
585
+ return {
586
+ version: SUBAGENT_RPC_PROTOCOL_VERSION,
587
+ requestId,
588
+ method: raw.method as SubagentRpcMethod,
589
+ ...(raw.params !== undefined ? { params: raw.params } : {}),
590
+ ...(isRecord(raw.source) ? { source: raw.source as SubagentRpcRequestEnvelope["source"] } : {}),
591
+ };
592
+ }
593
+
594
+ function safeReplyRequestId(raw: unknown): string {
595
+ if (!isRecord(raw)) return "unknown";
596
+ const requestId = raw.requestId;
597
+ return typeof requestId === "string" && requestId.trim().length > 0 && !/[\r\n]/.test(requestId)
598
+ ? requestId
599
+ : "unknown";
600
+ }
601
+
602
+ function errorReply(raw: unknown, error: unknown): SubagentRpcReplyEnvelope {
603
+ const requestId = safeReplyRequestId(raw);
604
+ const method = isRecord(raw) && typeof raw.method === "string" && (SUBAGENT_RPC_METHODS as readonly string[]).includes(raw.method)
605
+ ? raw.method as SubagentRpcMethod
606
+ : undefined;
607
+ const rpcError = error instanceof SubagentRpcError
608
+ ? error
609
+ : new SubagentRpcError("execution_failed", error instanceof Error ? error.message : String(error));
610
+ return {
611
+ version: SUBAGENT_RPC_PROTOCOL_VERSION,
612
+ requestId,
613
+ ...(method ? { method } : {}),
614
+ success: false,
615
+ error: {
616
+ code: rpcError.code,
617
+ message: rpcError.message,
618
+ },
619
+ };
620
+ }
621
+
622
+ export function registerSubagentRpcBridge(options: RegisterSubagentRpcBridgeOptions): {
623
+ emitReady: (ctx?: ExtensionContext | null) => void;
624
+ dispose: () => void;
625
+ } {
626
+ const fleetKeys: FleetKeyState = { sessionId: null, next: 0, keys: new Map() };
627
+ const unsubscribe = options.events.on(SUBAGENT_RPC_REQUEST_EVENT, async (raw) => {
628
+ let request: SubagentRpcRequestEnvelope | undefined;
629
+ try {
630
+ request = parseRequest(raw);
631
+ const data = await handleRequest(request, options, fleetKeys);
632
+ options.events.emit(subagentRpcReplyEvent(request.requestId), {
633
+ version: SUBAGENT_RPC_PROTOCOL_VERSION,
634
+ requestId: request.requestId,
635
+ method: request.method,
636
+ success: true,
637
+ data,
638
+ } satisfies SubagentRpcReplyEnvelope);
639
+ } catch (error) {
640
+ const reply = errorReply(request ?? raw, error);
641
+ options.events.emit(subagentRpcReplyEvent(reply.requestId), reply);
642
+ }
643
+ });
644
+
645
+ return {
646
+ emitReady: (ctx) => {
647
+ options.events.emit(SUBAGENT_RPC_READY_EVENT, pingData(ctx ?? options.getContext()));
648
+ },
649
+ dispose: () => {
650
+ if (typeof unsubscribe === "function") unsubscribe();
651
+ },
652
+ };
653
+ }