@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,38 @@
1
+ import type { AgentContract, EffectsProjection, ExecutionProjection, ReviewProjection, SingleResult } from "../../shared/types.ts";
2
+
3
+ export function isAgentContractV1(contract: AgentContract | undefined): boolean {
4
+ return contract?.version === 1;
5
+ }
6
+
7
+ export function buildExecutionProjection(result: Pick<SingleResult, "exitCode" | "error" | "interrupted" | "timedOut" | "stopped" | "detached">): ExecutionProjection {
8
+ if (result.detached) {
9
+ return { status: "detached", success: false, exitCode: result.exitCode, detached: true, ...(result.error ? { error: result.error } : {}) };
10
+ }
11
+ if (result.stopped) {
12
+ return { status: "stopped", success: false, exitCode: result.exitCode, stopped: true, ...(result.error ? { error: result.error } : {}) };
13
+ }
14
+ if (result.interrupted) {
15
+ return { status: "paused", success: true, exitCode: result.exitCode, interrupted: true, ...(result.error ? { error: result.error } : {}) };
16
+ }
17
+ const success = result.exitCode === 0 && !result.error && !result.timedOut;
18
+ return {
19
+ status: success ? "completed" : "failed",
20
+ success,
21
+ exitCode: result.exitCode,
22
+ ...(result.error ? { error: result.error } : {}),
23
+ ...(result.timedOut ? { timedOut: true } : {}),
24
+ };
25
+ }
26
+
27
+ export function buildReviewProjection(result: Pick<SingleResult, "acceptance">): ReviewProjection {
28
+ const review = result.acceptance?.reviewResult;
29
+ if (!review) return { status: "not-requested" };
30
+ return { status: review.status, findings: review.findings };
31
+ }
32
+
33
+ export function attachContractProjections<T extends SingleResult>(result: T): T {
34
+ result.execution = buildExecutionProjection(result);
35
+ result.review = buildReviewProjection(result);
36
+ if (!result.effects) result.effects = {} satisfies EffectsProjection;
37
+ return result;
38
+ }
@@ -0,0 +1,209 @@
1
+ import { Buffer } from "node:buffer";
2
+
3
+ export const SUBAGENT_CAPABILITY_CEILING_VERSION = 1 as const;
4
+ export const SUBAGENT_CAPABILITY_CEILING_REGISTRY_KEY = "pi-subagents.capability-ceiling.v1";
5
+ export const SUBAGENT_CAPABILITY_CEILING_ENV = "PI_SUBAGENT_CAPABILITY_CEILING_V1";
6
+
7
+ export type SubagentCapabilityCeiling =
8
+ | { allowedTools: readonly string[]; allowedAgents?: readonly string[]; denyExtensions?: boolean }
9
+ | { allowedTools?: readonly string[]; allowedAgents?: readonly string[]; denyExtensions: boolean }
10
+ | { allowedTools?: readonly string[]; allowedAgents: readonly string[]; denyExtensions?: boolean };
11
+
12
+ export interface ResolvedSubagentCapabilityCeiling {
13
+ version: typeof SUBAGENT_CAPABILITY_CEILING_VERSION;
14
+ allowedTools?: string[];
15
+ allowedAgents?: string[];
16
+ denyExtensions: boolean;
17
+ sources: string[];
18
+ }
19
+
20
+ export interface SubagentCapabilityAudit {
21
+ ceiling: ResolvedSubagentCapabilityCeiling;
22
+ requestedTools?: string[];
23
+ effectiveTools: string[];
24
+ removedTools: string[];
25
+ internalTools: string[];
26
+ extensionsDenied: boolean;
27
+ removedExtensionCount: number;
28
+ requestedMcpToolCount: number;
29
+ effectiveMcpTools: string[];
30
+ agentAllowed: boolean;
31
+ agentRestrictionSources?: string[];
32
+ }
33
+
34
+ export interface RegisterSubagentCapabilityCeilingOptions {
35
+ sessionId: string;
36
+ source: string;
37
+ ceiling: SubagentCapabilityCeiling;
38
+ }
39
+
40
+ export interface SubagentCapabilityCeilingHandle {
41
+ update(ceiling: SubagentCapabilityCeiling): void;
42
+ dispose(): void;
43
+ }
44
+
45
+ type Registration = { source: string; ceiling: ResolvedSubagentCapabilityCeiling };
46
+ type Registry = Map<string, Map<symbol, Registration>>;
47
+
48
+ function registry(): Registry {
49
+ const key = Symbol.for(SUBAGENT_CAPABILITY_CEILING_REGISTRY_KEY);
50
+ const store = globalThis as typeof globalThis & { [key: symbol]: unknown };
51
+ const existing = store[key];
52
+ if (existing instanceof Map) return existing as Registry;
53
+ const created: Registry = new Map();
54
+ store[key] = created;
55
+ return created;
56
+ }
57
+
58
+ function validateText(value: unknown, field: string): string {
59
+ if (typeof value !== "string" || !value.trim() || /[\u0000-\u001f\u007f]/u.test(value) || Buffer.byteLength(value.trim(), "utf8") > 256) {
60
+ throw new Error(`Invalid capability ceiling ${field}; expected a non-empty string without control characters (max 256 UTF-8 bytes).`);
61
+ }
62
+ return value.trim();
63
+ }
64
+
65
+ function normalizeCeiling(ceiling: SubagentCapabilityCeiling): ResolvedSubagentCapabilityCeiling {
66
+ if (!ceiling || typeof ceiling !== "object" || Array.isArray(ceiling)) throw new Error("Invalid capability ceiling; expected an object.");
67
+ const hasAllowedTools = Object.hasOwn(ceiling, "allowedTools");
68
+ const hasAllowedAgents = Object.hasOwn(ceiling, "allowedAgents");
69
+ const hasDenyExtensions = Object.hasOwn(ceiling, "denyExtensions");
70
+ if (!hasAllowedTools && !hasAllowedAgents && !hasDenyExtensions) throw new Error("Invalid capability ceiling; expected allowedTools, allowedAgents, or denyExtensions.");
71
+ if (hasDenyExtensions && typeof ceiling.denyExtensions !== "boolean") throw new Error("Invalid capability ceiling denyExtensions; expected a boolean.");
72
+ const normalizeList = (field: "allowedTools" | "allowedAgents", pattern: RegExp): string[] | undefined => {
73
+ if (!Object.hasOwn(ceiling, field)) return undefined;
74
+ const values = ceiling[field];
75
+ if (!Array.isArray(values)) throw new Error(`Invalid capability ceiling ${field}; expected an array.`);
76
+ if (values.length > 256) throw new Error(`Invalid capability ceiling ${field}; expected at most 256 names.`);
77
+ return [...new Set(values.map((entry) => {
78
+ const name = validateText(entry, `${field} entry`);
79
+ if (!pattern.test(name)) throw new Error(`Invalid capability ceiling ${field} entry '${name}'.`);
80
+ if (Buffer.byteLength(name, "utf8") > 128) throw new Error(`Invalid capability ceiling ${field} entry '${name}'; max 128 UTF-8 bytes.`);
81
+ return name;
82
+ }))].sort();
83
+ };
84
+ const allowedTools = normalizeList("allowedTools", /^[A-Za-z0-9_.:-]+$/u);
85
+ const allowedAgents = normalizeList("allowedAgents", /^[A-Za-z0-9_.:-]+$/u);
86
+ return {
87
+ version: SUBAGENT_CAPABILITY_CEILING_VERSION,
88
+ ...(allowedTools !== undefined ? { allowedTools } : {}),
89
+ ...(allowedAgents !== undefined ? { allowedAgents } : {}),
90
+ denyExtensions: ceiling.denyExtensions === true,
91
+ sources: [],
92
+ };
93
+ }
94
+
95
+ export function parseSubagentCapabilityCeiling(value: unknown, field = "capability ceiling"): ResolvedSubagentCapabilityCeiling {
96
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid ${field}; expected an object.`);
97
+ const record = value as Record<string, unknown>;
98
+ if (record.version !== SUBAGENT_CAPABILITY_CEILING_VERSION) throw new Error(`Invalid ${field} version.`);
99
+ const normalized = normalizeCeiling(record as SubagentCapabilityCeiling);
100
+ const sources = record.sources;
101
+ if (!Array.isArray(sources) || sources.some((source) => typeof source !== "string")) throw new Error(`Invalid ${field} sources; expected an array of strings.`);
102
+ normalized.sources = [...new Set(sources.map((source) => validateText(source, `${field} source`)))].sort();
103
+ return normalized;
104
+ }
105
+
106
+ export function registerSubagentCapabilityCeiling(options: RegisterSubagentCapabilityCeilingOptions): SubagentCapabilityCeilingHandle {
107
+ const sessionId = validateText(options.sessionId, "sessionId");
108
+ const source = validateText(options.source, "source");
109
+ let normalized = normalizeCeiling(options.ceiling);
110
+ const token = Symbol(source);
111
+ const store = registry();
112
+ let session = store.get(sessionId);
113
+ if (!session) {
114
+ session = new Map();
115
+ store.set(sessionId, session);
116
+ }
117
+ const setRegistration = () => {
118
+ normalized = normalizeCeiling(normalized);
119
+ normalized.sources = [source];
120
+ session!.set(token, { source, ceiling: normalized });
121
+ };
122
+ setRegistration();
123
+ let disposed = false;
124
+ return {
125
+ update(ceiling) {
126
+ if (disposed) throw new Error("Cannot update a disposed capability ceiling handle.");
127
+ normalized = normalizeCeiling(ceiling);
128
+ normalized.sources = [source];
129
+ session!.set(token, { source, ceiling: normalized });
130
+ },
131
+ dispose() {
132
+ if (disposed) return;
133
+ disposed = true;
134
+ session!.delete(token);
135
+ if (session!.size === 0) store.delete(sessionId);
136
+ },
137
+ };
138
+ }
139
+
140
+ export function intersectSubagentCapabilityCeilings(...ceilings: Array<ResolvedSubagentCapabilityCeiling | undefined>): ResolvedSubagentCapabilityCeiling | undefined {
141
+ const active = ceilings.filter((ceiling): ceiling is ResolvedSubagentCapabilityCeiling => ceiling !== undefined);
142
+ if (active.length === 0) return undefined;
143
+ const intersectLists = (field: "allowedTools" | "allowedAgents"): string[] | undefined => {
144
+ const definedLists = active.filter((ceiling) => ceiling[field] !== undefined).map((ceiling) => new Set(ceiling[field]));
145
+ if (definedLists.length === 0) return undefined;
146
+ return [...definedLists[0]!].filter((entry) => definedLists.every((list) => list.has(entry))).sort();
147
+ };
148
+ const allowedTools = intersectLists("allowedTools");
149
+ const allowedAgents = intersectLists("allowedAgents");
150
+ return {
151
+ version: SUBAGENT_CAPABILITY_CEILING_VERSION,
152
+ ...(allowedTools !== undefined ? { allowedTools } : {}),
153
+ ...(allowedAgents !== undefined ? { allowedAgents } : {}),
154
+ denyExtensions: active.some((ceiling) => ceiling.denyExtensions),
155
+ sources: [...new Set(active.flatMap((ceiling) => ceiling.sources))].sort(),
156
+ };
157
+ }
158
+
159
+ export function resolveSubagentCapabilityCeiling(sessionId: string | undefined, inherited?: ResolvedSubagentCapabilityCeiling): ResolvedSubagentCapabilityCeiling | undefined {
160
+ const active: ResolvedSubagentCapabilityCeiling[] = [];
161
+ if (sessionId) {
162
+ const registrations = registry().get(sessionId);
163
+ if (registrations) active.push(...Array.from(registrations.values(), ({ ceiling }) => ceiling));
164
+ }
165
+ return intersectSubagentCapabilityCeilings(inherited, ...active);
166
+ }
167
+
168
+ export function resolveCurrentSubagentCapabilityCeiling(sessionId: string | undefined): ResolvedSubagentCapabilityCeiling | undefined {
169
+ return resolveSubagentCapabilityCeiling(sessionId, decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]));
170
+ }
171
+
172
+ export function isAgentAllowedByCapabilityCeiling(agentName: string, ceiling: ResolvedSubagentCapabilityCeiling | undefined): boolean {
173
+ return ceiling?.allowedAgents === undefined || ceiling.allowedAgents.includes(agentName);
174
+ }
175
+
176
+ export function capabilityCeilingAgentRestrictionMessage(agentName: string, ceiling: ResolvedSubagentCapabilityCeiling | undefined): string | undefined {
177
+ if (isAgentAllowedByCapabilityCeiling(agentName, ceiling)) return undefined;
178
+ const sources = ceiling?.sources.length ? ceiling.sources.join(", ") : "unknown source";
179
+ const allowed = ceiling?.allowedAgents?.length ? ceiling.allowedAgents.join(", ") : "(none)";
180
+ return `Capability ceiling from ${sources} does not allow agent '${agentName}'. Allowed agents: ${allowed}.`;
181
+ }
182
+
183
+ export function assertAgentAllowedByCapabilityCeiling(agentName: string, ceiling: ResolvedSubagentCapabilityCeiling | undefined): void {
184
+ const message = capabilityCeilingAgentRestrictionMessage(agentName, ceiling);
185
+ if (message) throw new Error(message);
186
+ }
187
+
188
+ export function capabilityCeilingAgentRestrictionSources(ceiling: ResolvedSubagentCapabilityCeiling | undefined): string[] | undefined {
189
+ return ceiling?.allowedAgents === undefined ? undefined : [...ceiling.sources];
190
+ }
191
+
192
+ export function encodeSubagentCapabilityCeiling(ceiling: ResolvedSubagentCapabilityCeiling | undefined): string | undefined {
193
+ if (!ceiling) return undefined;
194
+ return Buffer.from(JSON.stringify(ceiling), "utf8").toString("base64url");
195
+ }
196
+
197
+ export function decodeSubagentCapabilityCeiling(value: string | undefined): ResolvedSubagentCapabilityCeiling | undefined {
198
+ if (value === undefined || value === "") return undefined;
199
+ let parsed: unknown;
200
+ try {
201
+ parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
202
+ } catch (error) {
203
+ throw new Error(`Invalid inherited capability ceiling: ${error instanceof Error ? error.message : String(error)}`);
204
+ }
205
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || (parsed as { version?: unknown }).version !== SUBAGENT_CAPABILITY_CEILING_VERSION) {
206
+ throw new Error("Invalid inherited capability ceiling version.");
207
+ }
208
+ return parseSubagentCapabilityCeiling(parsed, "inherited capability ceiling");
209
+ }
@@ -0,0 +1,118 @@
1
+ import { isCheckpointStep, isDynamicParallelStep, isParallelStep, type ChainStep, type SequentialStep } from "../../shared/settings.ts";
2
+ import type { ChainOutputMap, ChainOutputMapEntry, SingleResult } from "../../shared/types.ts";
3
+ import { getSingleResultOutput } from "../../shared/utils.ts";
4
+ import { DynamicFanoutError, hasDynamicFanoutFields, type DynamicFanoutConfig, validateDynamicStepShape } from "./dynamic-fanout.ts";
5
+
6
+ const OUTPUT_REF_PATTERN = /\{outputs\.([^}]*)\}/g;
7
+ const SAFE_OUTPUT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
8
+
9
+ export class ChainOutputValidationError extends Error {}
10
+
11
+ export interface ChainOutputValidationContext {
12
+ priorOutputNames?: Iterable<string>;
13
+ startStepIndex?: number;
14
+ }
15
+
16
+ function outputNamesForStep(step: ChainStep): string[] {
17
+ if (isCheckpointStep(step)) return [];
18
+ if (isParallelStep(step)) return step.parallel.map((task) => task.as).filter((name): name is string => Boolean(name));
19
+ if (isDynamicParallelStep(step)) return [step.collect.as];
20
+ const name = (step as SequentialStep).as;
21
+ return name ? [name] : [];
22
+ }
23
+
24
+ function taskTemplatesForStep(step: ChainStep): string[] {
25
+ if (isCheckpointStep(step)) return [];
26
+ if (isParallelStep(step)) return step.parallel.map((task) => task.task ?? "{previous}");
27
+ if (isDynamicParallelStep(step)) return [step.parallel.task ?? "{previous}", step.parallel.label ?? ""].filter(Boolean);
28
+ return [(step as SequentialStep).task ?? "{previous}"];
29
+ }
30
+
31
+ export function validateChainOutputBindings(steps: ChainStep[], dynamicFanoutConfig: DynamicFanoutConfig = {}): void {
32
+ validateChainOutputBindingsWithContext(steps, dynamicFanoutConfig);
33
+ }
34
+
35
+ export function validateChainOutputBindingsWithContext(
36
+ steps: ChainStep[],
37
+ dynamicFanoutConfig: DynamicFanoutConfig = {},
38
+ context: ChainOutputValidationContext = {},
39
+ ): void {
40
+ const priorOutputNames = [...(context.priorOutputNames ?? [])];
41
+ const available = new Set<string>(priorOutputNames);
42
+ const seen = new Set<string>(priorOutputNames);
43
+ for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
44
+ const displayStepIndex = (context.startStepIndex ?? 0) + stepIndex + 1;
45
+ const step = steps[stepIndex]!;
46
+ if (hasDynamicFanoutFields(step)) {
47
+ if (!isDynamicParallelStep(step)) {
48
+ throw new ChainOutputValidationError(`Dynamic chain step ${displayStepIndex} requires expand, a single parallel template object, and collect; dynamic expand/collect cannot be mixed with static parallel arrays.`);
49
+ }
50
+ try {
51
+ validateDynamicStepShape(step, displayStepIndex - 1, dynamicFanoutConfig);
52
+ } catch (error) {
53
+ if (error instanceof DynamicFanoutError) throw new ChainOutputValidationError(error.message);
54
+ throw error;
55
+ }
56
+ if (!available.has(step.expand.from.output)) {
57
+ throw new ChainOutputValidationError(`Dynamic chain step ${displayStepIndex} references unknown output '${step.expand.from.output}'. Named outputs are only available after producing step/group completes.`);
58
+ }
59
+ }
60
+ for (const name of outputNamesForStep(step)) {
61
+ if (!SAFE_OUTPUT_NAME_PATTERN.test(name)) {
62
+ throw new ChainOutputValidationError(`Invalid chain output name '${name}' at step ${displayStepIndex}. Use /^[A-Za-z_][A-Za-z0-9_]*$/.`);
63
+ }
64
+ if (seen.has(name)) {
65
+ throw new ChainOutputValidationError(`Duplicate chain output name '${name}'. Each as name must be unique.`);
66
+ }
67
+ seen.add(name);
68
+ }
69
+ for (const template of taskTemplatesForStep(step)) {
70
+ for (const match of template.matchAll(OUTPUT_REF_PATTERN)) {
71
+ const rawReference = match[0];
72
+ const name = match[1]!;
73
+ if (!SAFE_OUTPUT_NAME_PATTERN.test(name)) {
74
+ throw new ChainOutputValidationError(`Invalid chain output reference '${rawReference}' at step ${displayStepIndex}. Use {outputs.name} with /^[A-Za-z_][A-Za-z0-9_]*$/ names.`);
75
+ }
76
+ if (!available.has(name)) {
77
+ throw new ChainOutputValidationError(`Unknown chain output reference '${rawReference}' at step ${displayStepIndex}. Named outputs are only available after producing step/group completes.`);
78
+ }
79
+ }
80
+ }
81
+ for (const name of outputNamesForStep(step)) {
82
+ available.add(name);
83
+ }
84
+ }
85
+ }
86
+
87
+ export function resolveOutputReferences(template: string, outputs: ChainOutputMap): string {
88
+ return template.replace(OUTPUT_REF_PATTERN, (rawReference, name: string) => {
89
+ if (!SAFE_OUTPUT_NAME_PATTERN.test(name)) {
90
+ throw new ChainOutputValidationError(`Invalid chain output reference '${rawReference}'. Use {outputs.name} with /^[A-Za-z_][A-Za-z0-9_]*$/ names.`);
91
+ }
92
+ const entry = outputs[name];
93
+ if (!entry) throw new ChainOutputValidationError(`Unknown chain output reference '${rawReference}'.`);
94
+ return entry.text;
95
+ });
96
+ }
97
+
98
+ function compactStructuredText(value: unknown): string {
99
+ return JSON.stringify(value);
100
+ }
101
+
102
+ export function outputEntryFromResult(result: SingleResult, stepIndex: number): ChainOutputMapEntry {
103
+ return {
104
+ text: result.structuredOutput !== undefined ? compactStructuredText(result.structuredOutput) : getSingleResultOutput(result),
105
+ ...(result.structuredOutput !== undefined ? { structured: result.structuredOutput } : {}),
106
+ agent: result.agent,
107
+ stepIndex,
108
+ };
109
+ }
110
+
111
+ export function outputEntryFromAsyncResult(result: { agent: string; output: string; structuredOutput?: unknown }, stepIndex: number): ChainOutputMapEntry {
112
+ return {
113
+ text: result.structuredOutput !== undefined ? compactStructuredText(result.structuredOutput) : result.output,
114
+ ...(result.structuredOutput !== undefined ? { structured: result.structuredOutput } : {}),
115
+ agent: result.agent,
116
+ stepIndex,
117
+ };
118
+ }