@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,403 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { discoverAgents, discoverAgentsAll, resolveAgentName, type AgentConfig, type AgentScope, type AgentSource } from "../agents/agents.ts";
6
+ import { resolveExecutionAgentScope } from "../agents/agent-scope.ts";
7
+ import { buildSkillInjection, normalizeSkillInput, resolveSkillsWithFallback } from "../agents/skills.ts";
8
+ import { buildAgentMemoryInjection } from "../agents/agent-memory.ts";
9
+ import { buildModelCandidates, resolveEffectiveSubagentModel, type AvailableModelInfo, type ParentModel } from "../runs/shared/model-fallback.ts";
10
+ import { applyThinkingSuffix, resolvePiLaunchToolPlan, type PiLaunchToolPlan } from "../runs/shared/pi-args.ts";
11
+ import { injectOutputPathSystemPrompt, normalizeSingleOutputOverride, resolveSingleOutputPath } from "../runs/shared/single-output.ts";
12
+ import { getArtifactPaths, getArtifactsDir } from "../shared/artifacts.ts";
13
+ import { resolveEffectiveThinking } from "../shared/model-info.ts";
14
+ import { SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, type ArtifactDirPreference, type ArtifactPaths, type JsonSchemaObject, type OutputMode } from "../shared/types.ts";
15
+ import { capabilityCeilingAgentRestrictionMessage, intersectSubagentCapabilityCeilings, type ResolvedSubagentCapabilityCeiling, type SubagentCapabilityAudit } from "../runs/shared/capability-ceiling.ts";
16
+ import { appendTurnBudgetSystemPrompt } from "../runs/shared/turn-budget.ts";
17
+ import type { ResolvedTurnBudget } from "../shared/types.ts";
18
+ import type { ResolvedMcpDirectToolSelection } from "../runs/shared/mcp-direct-tool-allowlist.ts";
19
+ import { resolveStepBehavior } from "../shared/settings.ts";
20
+ import { agentDefinitionDigest, AGENT_DEFINITION_PROJECTION_VERSION, launchBindingDigest } from "../shared/launch-contract.ts";
21
+ import { DIRS, TEMP_ROOT_DIR } from "../shared/types.ts";
22
+ import { processTerminalCandidatePath, processTerminalPath } from "../runs/background/process-terminal.ts";
23
+ import { nestedResultsPath } from "../runs/shared/nested-events.ts";
24
+
25
+ export const SUBAGENT_LAUNCH_CONTRACT_VERSION = 2 as const;
26
+
27
+ export type SubagentLaunchContractReasonCode =
28
+ | "missing_agent"
29
+ | "ambiguous_agent"
30
+ | "missing_skill"
31
+ | "denied_required_tool"
32
+ | "invalid_artifact_dir"
33
+ | "invalid_cwd"
34
+ | "unsupported_mode"
35
+ | "restricted_agent";
36
+
37
+ export interface SubagentLaunchContractDiagnostic {
38
+ code: SubagentLaunchContractReasonCode | "host_required" | "snapshot_warning";
39
+ severity: "error" | "warning" | "host-required";
40
+ message: string;
41
+ }
42
+
43
+ export interface SubagentLaunchContractInput {
44
+ agent: string;
45
+ cwd: string;
46
+ task?: string;
47
+ agentScope?: AgentScope;
48
+ context?: "fresh" | "fork";
49
+ model?: string;
50
+ thinking?: string | false;
51
+ parentModel?: ParentModel;
52
+ availableModels?: ReadonlyArray<AvailableModelInfo | { provider: string; id: string; fullId?: string; reasoning?: boolean }>;
53
+ preferredProvider?: string;
54
+ skill?: string | string[] | boolean;
55
+ output?: string | boolean;
56
+ outputMode?: OutputMode;
57
+ outputSchema?: JsonSchemaObject;
58
+ turnBudget?: ResolvedTurnBudget;
59
+ artifacts?: boolean;
60
+ artifactDir?: ArtifactDirPreference;
61
+ parentSessionFile?: string | null;
62
+ sessionRoot?: string;
63
+ sessionDir?: string;
64
+ runId?: string;
65
+ /** Root run id supplied by a host when projecting nested async lifecycle paths. */
66
+ nestedRootRunId?: string;
67
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
68
+ inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
69
+ }
70
+
71
+ export interface SubagentLaunchContractAgentCandidate {
72
+ name: string;
73
+ localName?: string;
74
+ packageName?: string;
75
+ source: AgentSource;
76
+ filePath: string;
77
+ disabled?: boolean;
78
+ selected: boolean;
79
+ }
80
+
81
+ export interface SubagentLaunchContractAgent {
82
+ name: string;
83
+ localName?: string;
84
+ packageName?: string;
85
+ source: AgentSource;
86
+ filePath: string;
87
+ definitionProjectionVersion: typeof AGENT_DEFINITION_PROJECTION_VERSION;
88
+ definitionDigest: string;
89
+ shadowedCandidates: SubagentLaunchContractAgentCandidate[];
90
+ }
91
+
92
+ export interface SubagentLaunchContractSkills {
93
+ requested: string[];
94
+ resolved: Array<{ name: string; path: string; source: string }>;
95
+ missing: string[];
96
+ }
97
+
98
+ export interface SubagentLaunchContractTools {
99
+ requestedBuiltin: string[];
100
+ declaredBuiltin: string[];
101
+ effectiveAllowlist: string[];
102
+ explicitAllowlist: boolean;
103
+ requiredChildTools: string[];
104
+ internalTools: string[];
105
+ mcp: ResolvedMcpDirectToolSelection[];
106
+ effectiveMcpTools: string[];
107
+ toolExtensionPaths: string[];
108
+ runtimeExtensions: string[];
109
+ configuredExtensions: string[];
110
+ extensionArgs: string[];
111
+ disableAmbientExtensions: boolean;
112
+ fanoutAuthorized: boolean;
113
+ capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
114
+ capabilityAudit?: SubagentCapabilityAudit;
115
+ }
116
+
117
+ export interface SubagentLaunchContractRoots {
118
+ cwd: string;
119
+ sessionRoot?: string;
120
+ sessionDir?: string;
121
+ sessionFile?: string;
122
+ artifactsDir?: string;
123
+ artifactPaths?: ArtifactPaths;
124
+ outputPath?: string;
125
+ lifecycle?: {
126
+ asyncDir: string;
127
+ resultPath: string;
128
+ statusPath: string;
129
+ eventsPath: string;
130
+ processTerminalPath: string;
131
+ processTerminalCandidatePath: string;
132
+ };
133
+ }
134
+
135
+ export interface SubagentLaunchContract {
136
+ version: typeof SUBAGENT_LAUNCH_CONTRACT_VERSION;
137
+ runId: string;
138
+ agent: SubagentLaunchContractAgent;
139
+ context: "fresh" | "fork";
140
+ model?: string;
141
+ modelCandidates: string[];
142
+ thinking?: string;
143
+ systemPromptMode: AgentConfig["systemPromptMode"];
144
+ inheritProjectContext: boolean;
145
+ inheritSkills: boolean;
146
+ skills: SubagentLaunchContractSkills;
147
+ tools: SubagentLaunchContractTools;
148
+ roots: SubagentLaunchContractRoots;
149
+ protocol: {
150
+ lifecycleArtifactVersion: number;
151
+ packageVersion: string;
152
+ };
153
+ diagnostics: SubagentLaunchContractDiagnostic[];
154
+ /** Digest of the resolved child inputs, recomputed by execution paths. */
155
+ launchContractDigest: string;
156
+ digest: string;
157
+ }
158
+
159
+ export type SubagentLaunchContractResult =
160
+ | { ok: true; contract: SubagentLaunchContract }
161
+ | { ok: false; code: SubagentLaunchContractReasonCode; message: string; diagnostics: SubagentLaunchContractDiagnostic[] };
162
+
163
+ function packageVersion(): string {
164
+ const packagePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "package.json");
165
+ const parsed = JSON.parse(fs.readFileSync(packagePath, "utf-8")) as { version?: unknown };
166
+ if (typeof parsed.version !== "string" || !parsed.version.trim()) {
167
+ throw new Error(`Invalid package version in '${packagePath}'.`);
168
+ }
169
+ return parsed.version;
170
+ }
171
+
172
+ function stableJson(value: unknown): string {
173
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
174
+ if (value && typeof value === "object") {
175
+ return `{${Object.entries(value as Record<string, unknown>)
176
+ .filter(([, entry]) => entry !== undefined)
177
+ .sort(([a], [b]) => a.localeCompare(b))
178
+ .map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
179
+ .join(",")}}`;
180
+ }
181
+ return JSON.stringify(value);
182
+ }
183
+
184
+ function digestContract(contract: Omit<SubagentLaunchContract, "digest">): string {
185
+ return createHash("sha256").update(stableJson(contract)).digest("hex");
186
+ }
187
+
188
+ function normalizeAvailableModels(models: SubagentLaunchContractInput["availableModels"]): AvailableModelInfo[] {
189
+ return (models ?? []).map((model) => ({ ...model, fullId: model.fullId ?? `${model.provider}/${model.id}` }));
190
+ }
191
+
192
+ function candidateList(inputAgent: string, selected: AgentConfig | undefined, cwd: string): SubagentLaunchContractAgentCandidate[] {
193
+ const all = discoverAgentsAll(cwd);
194
+ return [...all.builtin, ...all.package, ...all.user, ...all.project]
195
+ .filter((agent) => Boolean(resolveAgentName(inputAgent, [agent]).agent))
196
+ .map((agent) => ({
197
+ name: agent.name,
198
+ ...(agent.localName ? { localName: agent.localName } : {}),
199
+ ...(agent.packageName ? { packageName: agent.packageName } : {}),
200
+ source: agent.source,
201
+ filePath: agent.filePath,
202
+ ...(agent.disabled === true ? { disabled: true } : {}),
203
+ selected: Boolean(selected && agent.filePath === selected.filePath && agent.name === selected.name),
204
+ }));
205
+ }
206
+
207
+ export async function resolveSubagentLaunchContract(input: SubagentLaunchContractInput): Promise<SubagentLaunchContractResult> {
208
+ const diagnostics: SubagentLaunchContractDiagnostic[] = [];
209
+ const effectiveCwd = path.resolve(input.cwd);
210
+ try {
211
+ if (!fs.statSync(effectiveCwd).isDirectory()) {
212
+ return { ok: false, code: "invalid_cwd", message: `cwd '${effectiveCwd}' is not a directory.`, diagnostics };
213
+ }
214
+ } catch (error) {
215
+ const detail = error instanceof Error ? ` ${error.message}` : "";
216
+ return { ok: false, code: "invalid_cwd", message: `cwd '${effectiveCwd}' is not a directory.${detail}`, diagnostics };
217
+ }
218
+ if (input.context !== undefined && input.context !== "fresh" && input.context !== "fork") {
219
+ return { ok: false, code: "unsupported_mode", message: `Unsupported context '${String(input.context)}'; expected 'fresh' or 'fork'.`, diagnostics };
220
+ }
221
+ if (input.artifactDir !== undefined && input.artifactDir !== "project" && input.artifactDir !== "session" && input.artifactDir !== "temp") {
222
+ return { ok: false, code: "invalid_artifact_dir", message: `Unsupported artifactDir '${String(input.artifactDir)}'; expected 'project', 'session', or 'temp'.`, diagnostics };
223
+ }
224
+ if (input.context === "fork") {
225
+ diagnostics.push({ code: "host_required", severity: "host-required", message: "Exact fork session branching and fork-thinking downgrade checks require Pi host session and model-registry snapshots." });
226
+ }
227
+ const scope = resolveExecutionAgentScope(input.agentScope);
228
+ const discovered = discoverAgents(effectiveCwd, scope);
229
+ const resolvedAgent = resolveAgentName(input.agent, discovered.agents);
230
+ if (resolvedAgent.error) {
231
+ return { ok: false, code: "ambiguous_agent", message: resolvedAgent.error, diagnostics };
232
+ }
233
+ if (!resolvedAgent.agent) {
234
+ return { ok: false, code: "missing_agent", message: `Unknown agent: ${input.agent}`, diagnostics };
235
+ }
236
+ const agent = resolvedAgent.agent;
237
+ const effectiveCapabilityCeiling = intersectSubagentCapabilityCeilings(input.capabilityCeiling, input.inheritedCapabilityCeiling);
238
+ const restrictionMessage = capabilityCeilingAgentRestrictionMessage(agent.name, effectiveCapabilityCeiling);
239
+ if (restrictionMessage) return { ok: false, code: "restricted_agent", message: restrictionMessage, diagnostics };
240
+ const runId = input.runId ?? "preflight";
241
+ const skillInput = normalizeSkillInput(input.skill);
242
+ const outputOverride = normalizeSingleOutputOverride(input.output, agent.output);
243
+ const behavior = resolveStepBehavior(agent, {
244
+ ...(outputOverride !== undefined ? { output: outputOverride } : {}),
245
+ ...(input.outputMode !== undefined ? { outputMode: input.outputMode } : {}),
246
+ ...(skillInput !== undefined ? { skills: skillInput } : {}),
247
+ ...(input.model !== undefined ? { model: input.model } : {}),
248
+ });
249
+ const requestedSkills = behavior.skills === false ? [] : behavior.skills;
250
+ const resolvedSkills = resolveSkillsWithFallback(
251
+ requestedSkills,
252
+ effectiveCwd,
253
+ effectiveCwd,
254
+ agent.skillPath,
255
+ agent.filePath ? path.dirname(agent.filePath) : effectiveCwd,
256
+ );
257
+ if (resolvedSkills.missing.includes("pi-subagents")) {
258
+ return { ok: false, code: "missing_skill", message: "The pi-subagents orchestration skill is not child-injectable.", diagnostics };
259
+ }
260
+ if (resolvedSkills.missing.length > 0) diagnostics.push({ code: "missing_skill", severity: "error", message: `Missing skills: ${resolvedSkills.missing.join(", ")}` });
261
+
262
+ const availableModels = normalizeAvailableModels(input.availableModels);
263
+ const preferredProvider = input.preferredProvider ?? input.parentModel?.provider;
264
+ const primaryModel = resolveEffectiveSubagentModel(input.model, agent.model, input.parentModel, availableModels, preferredProvider, { scope: discovered.modelScope });
265
+ const effectiveThinkingConfig = input.thinking !== undefined ? input.thinking : agent.thinking;
266
+ const model = applyThinkingSuffix(primaryModel, effectiveThinkingConfig, input.thinking !== undefined);
267
+ const modelCandidates = buildModelCandidates(primaryModel, agent.fallbackModels, availableModels, preferredProvider, { scope: discovered.modelScope })
268
+ .map((candidate) => applyThinkingSuffix(candidate, effectiveThinkingConfig, input.thinking !== undefined) ?? candidate);
269
+ let toolPlan: PiLaunchToolPlan;
270
+ try {
271
+ toolPlan = resolvePiLaunchToolPlan({
272
+ tools: agent.tools,
273
+ extensions: agent.extensions,
274
+ subagentOnlyExtensions: agent.subagentOnlyExtensions,
275
+ mcpDirectTools: agent.mcpDirectTools,
276
+ cwd: effectiveCwd,
277
+ requireReadTool: resolvedSkills.resolved.length > 0,
278
+ structuredOutput: Boolean(input.outputSchema),
279
+ capabilityCeiling: effectiveCapabilityCeiling,
280
+ agentName: agent.name,
281
+ });
282
+ } catch (error) {
283
+ const message = error instanceof Error ? error.message : String(error);
284
+ diagnostics.push({ code: "denied_required_tool", severity: "error", message });
285
+ return { ok: false, code: "denied_required_tool", message, diagnostics };
286
+ }
287
+ const artifactsEnabled = input.artifacts !== false;
288
+ const artifactsDir = artifactsEnabled ? getArtifactsDir(input.parentSessionFile ?? null, effectiveCwd, input.artifactDir ?? "project") : undefined;
289
+ const artifactPaths = artifactsDir ? getArtifactPaths(artifactsDir, runId, agent.name, 0) : undefined;
290
+ const outputPath = resolveSingleOutputPath(behavior.output, effectiveCwd, effectiveCwd, artifactsDir ? path.join(artifactsDir, "outputs", runId) : undefined);
291
+ const sessionRoot = input.sessionDir ? path.resolve(input.sessionDir) : input.sessionRoot ? path.join(path.resolve(input.sessionRoot), runId) : undefined;
292
+ const sessionDir = sessionRoot ? path.join(sessionRoot, "run-0") : undefined;
293
+ const lifecycleAsyncDir = input.nestedRootRunId
294
+ ? path.join(TEMP_ROOT_DIR, "nested-subagent-runs", input.nestedRootRunId, runId)
295
+ : path.join(DIRS.async, runId);
296
+ const lifecycleResultPath = input.nestedRootRunId
297
+ ? nestedResultsPath(input.nestedRootRunId, runId)
298
+ : path.join(DIRS.results, `${runId}.json`);
299
+ if (!sessionDir) diagnostics.push({ code: "host_required", severity: "host-required", message: "No sessionRoot/sessionDir was supplied; exact child session paths require the Pi host session-root policy." });
300
+ if (input.availableModels === undefined && (input.model || agent.model || input.parentModel)) {
301
+ diagnostics.push({ code: "host_required", severity: "host-required", message: "No availableModels snapshot was supplied; model resolution may differ from the active Pi host registry." });
302
+ }
303
+ if (resolvedSkills.missing.length > 0) {
304
+ return { ok: false, code: "missing_skill", message: `Missing skills: ${resolvedSkills.missing.join(", ")}`, diagnostics };
305
+ }
306
+ let effectiveSystemPrompt = agent.systemPrompt?.trim() ?? "";
307
+ if (resolvedSkills.resolved.length > 0) {
308
+ const skillInjection = buildSkillInjection(resolvedSkills.resolved);
309
+ effectiveSystemPrompt = effectiveSystemPrompt ? `${effectiveSystemPrompt}\n\n${skillInjection}` : skillInjection;
310
+ }
311
+ const memoryInjection = buildAgentMemoryInjection(agent, effectiveCwd);
312
+ if (memoryInjection) effectiveSystemPrompt = effectiveSystemPrompt ? `${effectiveSystemPrompt}\n\n${memoryInjection}` : memoryInjection;
313
+ effectiveSystemPrompt = injectOutputPathSystemPrompt(effectiveSystemPrompt, outputPath, agent);
314
+ const turnBudget = input.turnBudget ?? agent.defaultTurnBudget;
315
+ effectiveSystemPrompt = appendTurnBudgetSystemPrompt(effectiveSystemPrompt, turnBudget);
316
+ const candidates = candidateList(input.agent, agent, effectiveCwd);
317
+ const shadowedCandidates = candidates.filter((candidate) => !candidate.selected);
318
+ const definitionDigest = agentDefinitionDigest(agent);
319
+ const contractBase: Omit<SubagentLaunchContract, "digest"> = {
320
+ version: SUBAGENT_LAUNCH_CONTRACT_VERSION,
321
+ runId,
322
+ agent: {
323
+ name: agent.name,
324
+ ...(agent.localName ? { localName: agent.localName } : {}),
325
+ ...(agent.packageName ? { packageName: agent.packageName } : {}),
326
+ source: agent.source,
327
+ filePath: agent.filePath,
328
+ definitionProjectionVersion: AGENT_DEFINITION_PROJECTION_VERSION,
329
+ definitionDigest,
330
+ shadowedCandidates,
331
+ },
332
+ context: input.context ?? agent.defaultContext ?? "fresh",
333
+ ...(model ? { model } : {}),
334
+ modelCandidates,
335
+ ...(resolveEffectiveThinking(model, effectiveThinkingConfig) ? { thinking: resolveEffectiveThinking(model, effectiveThinkingConfig) } : {}),
336
+ systemPromptMode: agent.systemPromptMode,
337
+ inheritProjectContext: agent.inheritProjectContext,
338
+ inheritSkills: agent.inheritSkills,
339
+ skills: {
340
+ requested: requestedSkills,
341
+ resolved: resolvedSkills.resolved.map((skill) => ({ name: skill.name, path: skill.path, source: skill.source })),
342
+ missing: resolvedSkills.missing,
343
+ },
344
+ tools: {
345
+ requestedBuiltin: toolPlan.requestedBuiltinTools,
346
+ declaredBuiltin: toolPlan.declaredBuiltinTools,
347
+ effectiveAllowlist: toolPlan.effectiveToolAllowlist,
348
+ explicitAllowlist: toolPlan.explicitToolAllowlist,
349
+ requiredChildTools: toolPlan.requiredChildTools,
350
+ internalTools: toolPlan.internalTools,
351
+ mcp: toolPlan.effectiveMcpSelections,
352
+ effectiveMcpTools: toolPlan.effectiveMcpTools,
353
+ toolExtensionPaths: toolPlan.toolExtensionPaths,
354
+ runtimeExtensions: toolPlan.runtimeExtensions,
355
+ configuredExtensions: toolPlan.configuredExtensions,
356
+ extensionArgs: toolPlan.extensionArgs,
357
+ disableAmbientExtensions: toolPlan.disableAmbientExtensions,
358
+ fanoutAuthorized: toolPlan.fanoutAuthorized,
359
+ ...(toolPlan.capabilityCeiling ? { capabilityCeiling: toolPlan.capabilityCeiling } : {}),
360
+ ...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
361
+ },
362
+ roots: {
363
+ cwd: effectiveCwd,
364
+ ...(sessionRoot ? { sessionRoot } : {}),
365
+ ...(sessionDir ? { sessionDir, sessionFile: path.join(sessionDir, "session.jsonl") } : {}),
366
+ ...(artifactsDir ? { artifactsDir } : {}),
367
+ ...(artifactPaths ? { artifactPaths } : {}),
368
+ ...(outputPath ? { outputPath } : {}),
369
+ lifecycle: {
370
+ asyncDir: lifecycleAsyncDir,
371
+ resultPath: lifecycleResultPath,
372
+ statusPath: path.join(lifecycleAsyncDir, "status.json"),
373
+ eventsPath: path.join(lifecycleAsyncDir, "events.jsonl"),
374
+ processTerminalPath: processTerminalPath(lifecycleAsyncDir),
375
+ processTerminalCandidatePath: processTerminalCandidatePath(lifecycleAsyncDir),
376
+ },
377
+ },
378
+ protocol: {
379
+ lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
380
+ packageVersion: packageVersion(),
381
+ },
382
+ diagnostics,
383
+ launchContractDigest: launchBindingDigest({
384
+ task: input.task ?? "",
385
+ definitionDigest,
386
+ ...(model ? { model } : {}),
387
+ modelCandidates,
388
+ ...(resolveEffectiveThinking(model, effectiveThinkingConfig) ? { thinking: resolveEffectiveThinking(model, effectiveThinkingConfig) } : {}),
389
+ systemPrompt: effectiveSystemPrompt,
390
+ systemPromptMode: agent.systemPromptMode,
391
+ inheritProjectContext: agent.inheritProjectContext,
392
+ inheritSkills: agent.inheritSkills,
393
+ skills: requestedSkills,
394
+ tools: toolPlan.effectiveToolAllowlist,
395
+ extensions: toolPlan.extensionArgs,
396
+ mcpDirectTools: toolPlan.effectiveMcpTools,
397
+ ...(outputPath ? { outputPath } : {}),
398
+ outputMode: input.outputMode ?? "inline",
399
+ ...(input.outputSchema ? { structuredOutputSchema: input.outputSchema } : {}),
400
+ }),
401
+ };
402
+ return { ok: true, contract: { ...contractBase, digest: digestContract(contractBase) } };
403
+ }
@@ -0,0 +1,19 @@
1
+ export {
2
+ DEFAULT_FORK_PREAMBLE,
3
+ wrapForkTask,
4
+ type AcceptanceEvidenceKind,
5
+ type AcceptanceInput,
6
+ type AcceptanceLedger,
7
+ type AcceptanceLevel,
8
+ type AsyncStartedEvent,
9
+ type ControlEvent,
10
+ type Details,
11
+ type ExecutionProjection,
12
+ type JsonSchemaObject,
13
+ type OutputMode,
14
+ type ReviewProjection,
15
+ type SingleResult,
16
+ type SubagentResultStatus,
17
+ type SubagentRunMode,
18
+ type Usage,
19
+ } from "../shared/types.ts";
@@ -0,0 +1,76 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import type { ArtifactDirPreference, ExtensionConfig } from "../shared/types.ts";
5
+ import { validateMissionStoreConfig } from "../missions/store.ts";
6
+ import { validateAuthorityPolicy } from "../policy/authority.ts";
7
+ import { getAgentDir } from "../shared/utils.ts";
8
+ import { validatePermissionConfig } from "../runs/shared/permissions.ts";
9
+
10
+ const ARTIFACT_DIR_PREFERENCES = new Set<ArtifactDirPreference>(["project", "session", "temp"]);
11
+
12
+ export function resolveScheduledStoreRoot(value: string): string {
13
+ const expanded = value.startsWith("~/") ? path.join(os.homedir(), value.slice(2)) : value;
14
+ if (!path.isAbsolute(expanded)) throw new Error(`config.scheduledRuns.storeRoot must be an absolute path or "~/...", got ${JSON.stringify(value)}`);
15
+ return path.normalize(expanded);
16
+ }
17
+
18
+ function validateScheduledRunsConfig(value: unknown): void {
19
+ if (value === undefined) return;
20
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("config.scheduledRuns must be a JSON object");
21
+ const storeRoot = (value as Record<string, unknown>).storeRoot;
22
+ if (storeRoot === undefined) return;
23
+ if (typeof storeRoot !== "string" || !storeRoot.trim()) throw new Error("config.scheduledRuns.storeRoot must be a non-empty string");
24
+ resolveScheduledStoreRoot(storeRoot);
25
+ }
26
+
27
+ function validateConfig(config: Record<string, unknown>): void {
28
+ if (config.artifactDir !== undefined && !ARTIFACT_DIR_PREFERENCES.has(config.artifactDir as ArtifactDirPreference)) {
29
+ throw new Error(`config.artifactDir must be "project", "session", or "temp"`);
30
+ }
31
+ validateMissionStoreConfig(config.missions);
32
+ validateAuthorityPolicy(config.authorityPolicy);
33
+ validatePermissionConfig(config.permissions);
34
+ validateScheduledRunsConfig(config.scheduledRuns);
35
+ }
36
+
37
+ export function getConfigPath(): string {
38
+ return path.join(getAgentDir(), "extensions", "subagent", "config.json");
39
+ }
40
+
41
+ function readConfigForUpdate(configPath = getConfigPath()): ExtensionConfig {
42
+ if (!fs.existsSync(configPath)) return {};
43
+ const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8")) as unknown;
44
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
45
+ throw new Error(`Subagent config at '${configPath}' must be a JSON object`);
46
+ }
47
+ validateConfig(parsed as Record<string, unknown>);
48
+ return parsed as ExtensionConfig;
49
+ }
50
+
51
+ export function saveConfig(config: ExtensionConfig, configPath = getConfigPath()): void {
52
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
53
+ fs.writeFileSync(configPath, `${JSON.stringify(config, null, "\t")}\n`, "utf-8");
54
+ }
55
+
56
+ export function updateConfig(updater: (config: ExtensionConfig) => ExtensionConfig): ExtensionConfig {
57
+ const configPath = getConfigPath();
58
+ const next = updater(readConfigForUpdate(configPath));
59
+ validateConfig(next as Record<string, unknown>);
60
+ saveConfig(next, configPath);
61
+ return next;
62
+ }
63
+
64
+ export function resolveAsyncByDefault(config: Pick<ExtensionConfig, "asyncByDefault">): boolean {
65
+ return config.asyncByDefault !== false;
66
+ }
67
+
68
+ export function loadConfig(): ExtensionConfig {
69
+ const configPath = getConfigPath();
70
+ try {
71
+ return readConfigForUpdate(configPath);
72
+ } catch (error) {
73
+ console.error(`Failed to load subagent config from '${configPath}':`, error);
74
+ }
75
+ return {};
76
+ }
@@ -0,0 +1,58 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { controlNotificationKey, formatControlNoticeMessage } from "../runs/shared/subagent-control.ts";
3
+ import type { ControlEvent, SubagentState } from "../shared/types.ts";
4
+
5
+ export const SUBAGENT_CONTROL_MESSAGE_TYPE = "subagent_control_notice";
6
+
7
+ export interface SubagentControlMessageDetails {
8
+ event: ControlEvent;
9
+ source?: "foreground" | "async" | "goal";
10
+ asyncDir?: string;
11
+ childIntercomTarget?: string;
12
+ noticeText?: string;
13
+ }
14
+
15
+ export function controlNoticeTarget(details: SubagentControlMessageDetails): string | undefined {
16
+ return details.childIntercomTarget;
17
+ }
18
+
19
+ export function formatSubagentControlNotice(details: SubagentControlMessageDetails, content?: string): string {
20
+ return details.noticeText ?? content ?? formatControlNoticeMessage(details.event, controlNoticeTarget(details));
21
+ }
22
+
23
+ function deliverControlNotice(input: {
24
+ pi: Pick<ExtensionAPI, "sendMessage">;
25
+ visibleControlNotices: Set<string>;
26
+ details: SubagentControlMessageDetails;
27
+ }): void {
28
+ const childIntercomTarget = controlNoticeTarget(input.details);
29
+ const key = controlNotificationKey(input.details.event, childIntercomTarget);
30
+ if (input.visibleControlNotices.has(key)) return;
31
+ input.visibleControlNotices.add(key);
32
+ const noticeText = input.details.noticeText ?? formatControlNoticeMessage(input.details.event, childIntercomTarget);
33
+ input.pi.sendMessage(
34
+ {
35
+ customType: SUBAGENT_CONTROL_MESSAGE_TYPE,
36
+ content: noticeText,
37
+ display: true,
38
+ details: { ...input.details, childIntercomTarget, noticeText },
39
+ },
40
+ { triggerTurn: input.details.source === "async" },
41
+ );
42
+ }
43
+
44
+ export function handleSubagentControlNotice(input: {
45
+ pi: Pick<ExtensionAPI, "sendMessage">;
46
+ state: SubagentState;
47
+ visibleControlNotices: Set<string>;
48
+ details: SubagentControlMessageDetails;
49
+ }): void {
50
+ if (!input.details?.event || input.details.event.type === "active_long_running") return;
51
+ if (input.details.source === "foreground") {
52
+ // A foreground tool blocks Pi from displaying this message. The run can
53
+ // finish before Pi flushes it, and queued messages cannot be withdrawn.
54
+ // Foreground control remains available through the live tool and fleet state.
55
+ return;
56
+ }
57
+ deliverControlNotice(input);
58
+ }