@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -0,0 +1,150 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { stableJsonDigest } from "../shared/launch-contract.ts";
3
+ import {
4
+ createWorkflowResourcePermit,
5
+ type WorkflowResourceAuthority,
6
+ type WorkflowResourcePermit,
7
+ } from "../shared/workflow-child-permit.ts";
8
+ import type { WorkflowResourceProvenanceV1 } from "../shared/types.ts";
9
+
10
+ const RESOURCE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
11
+ const MAX_ARGS_BYTES = 16 * 1024;
12
+ const MAX_STRING_BYTES = 16 * 1024;
13
+
14
+ export interface ResolvedWorkflowResource {
15
+ script: string;
16
+ permit: WorkflowResourcePermit;
17
+ provenance: WorkflowResourceProvenanceV1;
18
+ }
19
+
20
+ export type WorkflowResourceResolution =
21
+ | { ok: true; resource: ResolvedWorkflowResource }
22
+ | { ok: false; error: string };
23
+
24
+ type WorkflowResourceDefinition = {
25
+ name: string;
26
+ version: number;
27
+ resolve: (args: Record<string, unknown>) => { script: string; authority: WorkflowResourceAuthority } | { error: string };
28
+ };
29
+
30
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
31
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
32
+ const prototype = Object.getPrototypeOf(value);
33
+ return prototype === Object.prototype || prototype === null;
34
+ }
35
+
36
+ function jsonByteLength(value: unknown): number {
37
+ try {
38
+ const encoded = JSON.stringify(value);
39
+ if (encoded === undefined) throw new Error("must contain JSON data");
40
+ return Buffer.byteLength(encoded, "utf8");
41
+ } catch (error) {
42
+ throw new Error(`must contain plain JSON data: ${error instanceof Error ? error.message : String(error)}`);
43
+ }
44
+ }
45
+
46
+ function validatePlainJson(value: unknown, path: string, depth = 0): void {
47
+ if (depth > 8) throw new Error(`${path} is too deeply nested.`);
48
+ if (value === null || typeof value === "boolean") return;
49
+ if (typeof value === "string") {
50
+ if (!value.trim()) throw new Error(`${path} must not be empty.`);
51
+ if (Buffer.byteLength(value, "utf8") > MAX_STRING_BYTES) throw new Error(`${path} exceeds ${MAX_STRING_BYTES} bytes.`);
52
+ return;
53
+ }
54
+ if (typeof value === "number") {
55
+ if (!Number.isFinite(value)) throw new Error(`${path} must be finite.`);
56
+ return;
57
+ }
58
+ if (Array.isArray(value)) {
59
+ if (value.length > 64) throw new Error(`${path} contains too many items.`);
60
+ for (const [index, entry] of value.entries()) validatePlainJson(entry, `${path}[${index}]`, depth + 1);
61
+ return;
62
+ }
63
+ if (!isPlainRecord(value)) throw new Error(`${path} must contain plain JSON data.`);
64
+ if (Object.keys(value).length > 16) throw new Error(`${path} contains too many fields.`);
65
+ for (const [key, entry] of Object.entries(value)) {
66
+ if (!key.trim()) throw new Error(`${path} contains an empty field name.`);
67
+ validatePlainJson(entry, `${path}.${key}`, depth + 1);
68
+ }
69
+ }
70
+
71
+ function normalizeArgs(value: unknown): { args?: Record<string, unknown>; error?: string } {
72
+ if (value === undefined) return { args: {} };
73
+ if (!isPlainRecord(value)) return { error: "workflow args must be a plain JSON object." };
74
+ try {
75
+ validatePlainJson(value, "workflow args");
76
+ if (jsonByteLength(value) > MAX_ARGS_BYTES) return { error: `workflow args exceed ${MAX_ARGS_BYTES} bytes.` };
77
+ return { args: { ...value } };
78
+ } catch (error) {
79
+ return { error: error instanceof Error ? error.message : String(error) };
80
+ }
81
+ }
82
+
83
+ function resolveRunCi(args: Record<string, unknown>): { script: string; authority: WorkflowResourceAuthority } | { error: string } {
84
+ const allowed = new Set(["command", "timeoutMs"]);
85
+ const unsupported = Object.keys(args).filter((key) => !allowed.has(key));
86
+ if (unsupported.length > 0) return { error: `workflow 'run-ci' args contain unsupported fields: ${unsupported.join(", ")}.` };
87
+ const command = args.command === undefined ? "npm test" : args.command;
88
+ if (command !== "npm test" && command !== "npm run typecheck") return { error: "workflow 'run-ci' args.command must be 'npm test' or 'npm run typecheck'." };
89
+ const timeoutMs = args.timeoutMs === undefined ? 120_000 : args.timeoutMs;
90
+ if (typeof timeoutMs !== "number" || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 86_400_000) return { error: "workflow 'run-ci' args.timeoutMs must be an integer from 1 to 86400000." };
91
+ const params = { kind: "command", command, timeoutMs, role: "ci" };
92
+ return {
93
+ script: `return await runs.host("ci", ${JSON.stringify(params)});`,
94
+ authority: { host: { keys: ["ci"], commands: [command] } },
95
+ };
96
+ }
97
+
98
+ function resolveReview(args: Record<string, unknown>): { script: string; authority: WorkflowResourceAuthority } | { error: string } {
99
+ const unsupported = Object.keys(args).filter((key) => key !== "task");
100
+ if (unsupported.length > 0) return { error: `workflow 'review' args contain unsupported fields: ${unsupported.join(", ")}.` };
101
+ const task = args.task;
102
+ if (typeof task !== "string" || !task.trim()) return { error: "workflow 'review' requires a non-empty string args.task." };
103
+ return {
104
+ script: `return (await runs.run("review", { agent: "reviewer", task: ${JSON.stringify(task.trim())} })).output;`,
105
+ authority: {},
106
+ };
107
+ }
108
+
109
+ const WORKFLOW_RESOURCES: readonly WorkflowResourceDefinition[] = [
110
+ { name: "review", version: 1, resolve: resolveReview },
111
+ { name: "run-ci", version: 1, resolve: resolveRunCi },
112
+ ];
113
+
114
+ function findWorkflowResource(name: string): WorkflowResourceDefinition | undefined {
115
+ return WORKFLOW_RESOURCES.find((resource) => resource.name === name);
116
+ }
117
+
118
+ function listWorkflowResourceNames(): string[] {
119
+ return WORKFLOW_RESOURCES.map((resource) => resource.name);
120
+ }
121
+
122
+ /** Resolve only extension-owned resources so policy can distinguish them from raw scripts; caller-provided script text is never consulted. */
123
+ export function resolveWorkflowResource(nameValue: unknown, argsValue?: unknown): WorkflowResourceResolution {
124
+ if (typeof nameValue !== "string" || !nameValue.trim()) return { ok: false, error: "workflow must be a non-empty resource name." };
125
+ const name = nameValue.trim();
126
+ if (!RESOURCE_NAME_PATTERN.test(name)) return { ok: false, error: "workflow must use a safe resource name." };
127
+ const resource = findWorkflowResource(name);
128
+ if (!resource) return { ok: false, error: `Unknown workflow resource '${name}'. Available resources: ${listWorkflowResourceNames().join(", ")}.` };
129
+ const normalizedArgs = normalizeArgs(argsValue);
130
+ if (normalizedArgs.error) return { ok: false, error: normalizedArgs.error };
131
+ const resolved = resource.resolve(normalizedArgs.args!);
132
+ if ("error" in resolved) return { ok: false, error: resolved.error };
133
+ const resourceId = randomUUID();
134
+ const permit = createWorkflowResourcePermit({
135
+ resourceName: resource.name,
136
+ resourceVersion: resource.version,
137
+ resourceId,
138
+ scriptDigest: stableJsonDigest(resolved.script),
139
+ authority: resolved.authority,
140
+ });
141
+ const provenance: WorkflowResourceProvenanceV1 = Object.freeze({
142
+ kind: "workflow",
143
+ name: resource.name,
144
+ version: resource.version,
145
+ invocation: "named",
146
+ expansion: "resolved",
147
+ id: resourceId,
148
+ });
149
+ return { ok: true, resource: { script: resolved.script, permit, provenance } };
150
+ }
@@ -0,0 +1,246 @@
1
+ import type {
2
+ AsyncStatus,
3
+ WorkflowRecoveryAction,
4
+ WorkflowTerminalOutcome,
5
+ WorkflowTerminalResolution,
6
+ Usage,
7
+ } from "../shared/types.ts";
8
+ import type { WorkflowReceipt } from "./workflow-receipt.ts";
9
+ import { workflowChildSummary } from "./workflow-child-summary.ts";
10
+
11
+ export const UNSUPPORTED_DETACHED_WORKFLOW_CONTINUATION = "unsupported-continuation: detached workflow child settled, but JavaScript workflow continuation was not persisted. Resume the workflow explicitly instead of treating the completed child as top-level workflow completion.";
12
+ export const INTERRUPTED_DETACHED_CHILD = "Interrupted. Waiting for explicit next action.";
13
+ export const EVIDENCE_PERSISTENCE_FAILED = "evidence-persistence-failed";
14
+
15
+ export type WorkflowStatusStep = NonNullable<AsyncStatus["steps"]>[number] & {
16
+ outputPathMapping?: { requestedPath: string; savedPath: string };
17
+ interrupted?: boolean;
18
+ };
19
+
20
+ export interface WorkflowPublicChild {
21
+ workflowKey?: string;
22
+ agent?: string;
23
+ /** Human-readable display name for the child session, when derived at launch. */
24
+ sessionName?: string;
25
+ runId?: string;
26
+ usage?: Usage;
27
+ sessionFile?: string;
28
+ output: string;
29
+ outputState: "present" | "absent";
30
+ structuredOutput?: unknown;
31
+ success: boolean;
32
+ terminalOutcome?: WorkflowTerminalOutcome;
33
+ outputReference?: string;
34
+ outputPathMapping?: { requestedPath: string; savedPath: string };
35
+ stopped?: boolean;
36
+ interrupted?: boolean;
37
+ detached?: boolean;
38
+ error?: string;
39
+ artifactPaths?: { outputPath: string };
40
+ }
41
+
42
+ export interface WorkflowSettlementPlan {
43
+ status: AsyncStatus;
44
+ publicResult: Record<string, unknown>;
45
+ receipt?: WorkflowReceipt;
46
+ recovery: WorkflowRecoveryAction[];
47
+ completionEvent?: Record<string, unknown>;
48
+ }
49
+
50
+ function cloneWorkflowStatus(status: AsyncStatus): AsyncStatus {
51
+ return {
52
+ ...status,
53
+ steps: status.steps?.map((step) => ({ ...step })),
54
+ workflow: status.workflow ? { ...status.workflow, trace: [...(status.workflow.trace ?? [])] } : status.workflow,
55
+ };
56
+ }
57
+
58
+ function workflowState(status: AsyncStatus): "completed" | "failed" | "paused" | "stopped" {
59
+ return status.state === "complete" ? "completed" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
60
+ }
61
+
62
+ function withWorkflowChildren(status: AsyncStatus): AsyncStatus {
63
+ return {
64
+ ...status,
65
+ workflowChildren: workflowChildSummary({
66
+ parentToolCallId: status.toolCallId ?? status.runId,
67
+ workflowRunId: status.runId,
68
+ workflowState: workflowState(status),
69
+ inventoryComplete: true,
70
+ trace: status.workflow?.trace,
71
+ steps: status.steps,
72
+ }),
73
+ };
74
+ }
75
+
76
+ export function findWorkflowSettlementStep(status: AsyncStatus, childRunId: string, workflowKey?: string, sessionFile?: string): WorkflowStatusStep | undefined {
77
+ const exact = status.steps?.find((candidate) => candidate.runId === childRunId);
78
+ if (exact || !workflowKey || !sessionFile) return exact;
79
+ const candidates = status.steps?.filter((candidate) => candidate.runId === undefined
80
+ && candidate.workflowKey === workflowKey
81
+ && candidate.sessionFile === sessionFile) ?? [];
82
+ return candidates.length === 1 ? candidates[0] : undefined;
83
+ }
84
+
85
+ export function promoteSettledPausedWorkflow(status: AsyncStatus, now = Date.now()): AsyncStatus | undefined {
86
+ if (status.mode !== "workflow" || status.state !== "paused") return undefined;
87
+ const next = cloneWorkflowStatus(status);
88
+ const stillOpen = next.steps?.some((candidate) =>
89
+ candidate.status === "running"
90
+ || (candidate.status === "paused" && candidate.activityState === "needs_attention")
91
+ ) === true;
92
+ if (stillOpen || !next.steps?.length) return undefined;
93
+ const failed = next.steps.some((candidate) => candidate.status === "failed");
94
+ next.lastUpdate = now;
95
+ next.state = "failed";
96
+ next.endedAt = now;
97
+ delete next.activityState;
98
+ if (!failed) next.error = UNSUPPORTED_DETACHED_WORKFLOW_CONTINUATION;
99
+ return withWorkflowChildren(next);
100
+ }
101
+
102
+ export function applyDetachedChildSettlement(
103
+ status: AsyncStatus,
104
+ input: { childRunId: string; result: { exitCode: number | null; error?: string; interrupted?: boolean; sessionFile?: string; sessionName?: string; stopped?: boolean }; workflowKey?: string; now?: number },
105
+ ): AsyncStatus | undefined {
106
+ if (status.mode !== "workflow" || status.state !== "paused") return undefined;
107
+ const next = cloneWorkflowStatus(status);
108
+ const step = findWorkflowSettlementStep(next, input.childRunId, input.workflowKey, input.result.sessionFile);
109
+ if (!step) return undefined;
110
+ step.runId ??= input.childRunId;
111
+ const succeeded = input.result.exitCode === 0 && !input.result.error && !input.result.interrupted;
112
+ const failedSiblingError = next.steps?.find((candidate) => {
113
+ const candidateStep = candidate as WorkflowStatusStep;
114
+ return candidateStep !== step && candidateStep.status === "failed" && !candidateStep.interrupted && candidateStep.error;
115
+ })?.error;
116
+ const interruptedChildError = next.steps?.find((candidate) => {
117
+ const candidateStep = candidate as WorkflowStatusStep;
118
+ return candidateStep.status === "failed" && candidateStep.interrupted && candidateStep.error;
119
+ })?.error;
120
+ const now = input.now ?? Date.now();
121
+ step.status = succeeded ? "completed" : "failed";
122
+ step.endedAt = now;
123
+ delete step.activityState;
124
+ delete step.currentTool;
125
+ delete step.currentToolStartedAt;
126
+ if (input.result.sessionFile) step.sessionFile = input.result.sessionFile;
127
+ if (input.result.sessionName) step.sessionName = input.result.sessionName;
128
+ if (succeeded) {
129
+ delete step.error;
130
+ delete step.interrupted;
131
+ } else if (input.result.interrupted || input.result.stopped) {
132
+ step.error = input.result.error ?? INTERRUPTED_DETACHED_CHILD;
133
+ step.interrupted = true;
134
+ if (input.result.stopped) step.stopped = true;
135
+ } else {
136
+ delete step.interrupted;
137
+ delete step.stopped;
138
+ if (input.result.error) step.error = input.result.error;
139
+ }
140
+ next.lastUpdate = now;
141
+ const promoted = promoteSettledPausedWorkflow(next, now);
142
+ if (promoted?.state === "failed" && failedSiblingError) promoted.error = failedSiblingError;
143
+ else if (promoted?.state === "failed" && (input.result.interrupted || input.result.stopped)) promoted.error = input.result.error ?? INTERRUPTED_DETACHED_CHILD;
144
+ else if (promoted?.state === "failed" && input.result.error) promoted.error = input.result.error;
145
+ else if (promoted?.state === "failed" && interruptedChildError) promoted.error = interruptedChildError;
146
+ return withWorkflowChildren(promoted ?? next);
147
+ }
148
+
149
+ export function classifyWorkflowSettlement(status: AsyncStatus, interrupted = false): WorkflowTerminalResolution | undefined {
150
+ if (status.state !== "complete" && status.state !== "failed") return undefined;
151
+ if (status.steps?.some((step) => {
152
+ const candidate = step as WorkflowStatusStep;
153
+ return candidate.status === "failed" && !candidate.interrupted;
154
+ })) return "failed-child";
155
+ if (interrupted || status.steps?.some((step) => {
156
+ const candidate = step as WorkflowStatusStep;
157
+ return candidate.status === "stopped" || candidate.stopped || candidate.interrupted || candidate.error === INTERRUPTED_DETACHED_CHILD;
158
+ })) return "interrupted-child";
159
+ return "settled-awaiting-resume";
160
+ }
161
+
162
+ export function workflowRecoveryActions(receipt: WorkflowReceipt | undefined): WorkflowRecoveryAction[] {
163
+ if (!receipt) return [];
164
+ return Object.values(receipt.entries).flatMap((entry) => entry.resumability.state === "resumable"
165
+ ? [{ key: entry.key, call: "runs.run" as const, resume: { workflowRunId: receipt.workflowRunId, key: entry.key, latest: true as const }, taskRequired: true as const }]
166
+ : []);
167
+ }
168
+
169
+ export function workflowTerminalOutcomeForResult(result: { timedOut?: boolean; turnBudgetExceeded?: boolean; toolBudgetBlocked?: boolean }): WorkflowTerminalOutcome | undefined {
170
+ if (result.timedOut) return { state: "partial", reason: "timeout" };
171
+ if (result.turnBudgetExceeded || result.toolBudgetBlocked) return { state: "partial", reason: "budget_exhausted" };
172
+ return undefined;
173
+ }
174
+
175
+ export function workflowOutputPathMappingSummary(children: readonly unknown[]): string {
176
+ const mappings = children.flatMap((entry) => {
177
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
178
+ const child = entry as Partial<WorkflowPublicChild>;
179
+ return child.outputPathMapping
180
+ ? [`'${child.workflowKey ?? "child"}': requested ${child.outputPathMapping.requestedPath} -> saved ${child.outputPathMapping.savedPath}`]
181
+ : [];
182
+ });
183
+ return mappings.length > 0 ? ` Output path mappings: ${mappings.join("; ")}.` : "";
184
+ }
185
+
186
+ export function planWorkflowSettlement(input: {
187
+ status: AsyncStatus;
188
+ summary: string;
189
+ children: WorkflowPublicChild[];
190
+ baseResult: Record<string, unknown>;
191
+ receipt?: WorkflowReceipt;
192
+ receiptPath?: string;
193
+ receiptPersistenceError?: string;
194
+ resolution?: WorkflowTerminalResolution;
195
+ terminalOutcome?: WorkflowTerminalOutcome;
196
+ now?: number;
197
+ eventMetadata?: Record<string, unknown>;
198
+ }): WorkflowSettlementPlan {
199
+ const now = input.now ?? Date.now();
200
+ let status = withWorkflowChildren(cloneWorkflowStatus(input.status));
201
+ let summary = input.summary;
202
+ let receipt = input.receipt;
203
+ let resolution = input.resolution;
204
+ if (input.receiptPersistenceError) {
205
+ const diagnostic = `${EVIDENCE_PERSISTENCE_FAILED}: ${input.receiptPersistenceError}`;
206
+ status = withWorkflowChildren({ ...status, state: "failed", error: diagnostic, activityState: undefined, endedAt: now, lastUpdate: now });
207
+ summary = `${diagnostic} Available child evidence was preserved, but workflow completion was not accepted.`;
208
+ receipt = undefined;
209
+ if (!resolution) resolution = classifyWorkflowSettlement(status);
210
+ }
211
+ const recovery = workflowRecoveryActions(receipt);
212
+ if (receipt) {
213
+ receipt = {
214
+ ...receipt,
215
+ state: status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed",
216
+ workflowChildren: status.workflowChildren,
217
+ ...(resolution ? { workflowResolution: resolution, recovery } : {}),
218
+ };
219
+ }
220
+ const publicResult: Record<string, unknown> = {
221
+ ...input.baseResult,
222
+ success: status.state === "complete",
223
+ state: status.state,
224
+ summary,
225
+ error: status.state === "complete" ? undefined : status.error ?? summary,
226
+ stopped: status.stopped ? true : undefined,
227
+ activityState: status.activityState,
228
+ workflowChildren: status.workflowChildren,
229
+ results: input.children,
230
+ ...(input.terminalOutcome ? { terminalOutcome: input.terminalOutcome } : {}),
231
+ ...(resolution ? { workflowResolution: resolution, recovery } : {}),
232
+ ...(receipt && input.receiptPath ? { workflowReceipt: { path: input.receiptPath, receipt } } : {}),
233
+ timestamp: now,
234
+ };
235
+ const terminal = status.state === "complete" || status.state === "failed" || status.state === "partial" || status.state === "stopped";
236
+ const completionEvent = terminal ? {
237
+ type: "subagent.workflow.completed",
238
+ state: status.state,
239
+ ...(resolution ? { workflowResolution: resolution } : {}),
240
+ ...(input.terminalOutcome ? { terminalOutcome: input.terminalOutcome } : {}),
241
+ ...(status.error ? { error: status.error } : {}),
242
+ ...(status.activityState ? { activityState: status.activityState } : {}),
243
+ ...input.eventMetadata,
244
+ } : undefined;
245
+ return { status, publicResult, receipt, recovery, completionEvent };
246
+ }