@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Package-owned workflow scripts for the data-only `tasks` and `chain` inputs.
3
+ * Callers supply only data; every caller string is embedded with JSON.stringify
4
+ * and never becomes code. Scripts run on the ordinary workflow runtime.
5
+ */
6
+
7
+ export type StructuredWorkflowKind = "tasks" | "chain";
8
+
9
+ const OUTPUT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
10
+ const PLACEHOLDER_PATTERN = /\{(?:task|previous|outputs\.([A-Za-z_][A-Za-z0-9_]*))\}/g;
11
+
12
+ interface TemplateScope {
13
+ path: string;
14
+ /** Whether the script declares `originalTask` for {task}. */
15
+ hasOriginalTask: boolean;
16
+ /** Script variable holding the previous step's output, or the reason {previous} is unavailable. */
17
+ previous: { variable: string } | { unavailable: string };
18
+ /** Script variables for outputs named by earlier sequential steps; undefined when named outputs are unavailable. */
19
+ outputs?: ReadonlyMap<string, string>;
20
+ outputsUnavailable?: string;
21
+ }
22
+
23
+ interface StepChild {
24
+ key: string;
25
+ agent: string;
26
+ taskExpression: string;
27
+ }
28
+
29
+ export function isPlainRecord(value: unknown): value is Record<string, unknown> {
30
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
31
+ const prototype = Object.getPrototypeOf(value);
32
+ return prototype === Object.prototype || prototype === null;
33
+ }
34
+
35
+ function nonEmptyString(value: unknown, path: string): string {
36
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${path} must be a non-empty string.`);
37
+ return value;
38
+ }
39
+
40
+ function exactFields(value: unknown, path: string, allowed: readonly string[], hint: string): Record<string, unknown> {
41
+ if (!isPlainRecord(value)) throw new Error(`${path} must be an object.`);
42
+ const unsupported = Object.keys(value).filter((key) => !allowed.includes(key));
43
+ if (unsupported.length > 0) throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint}`);
44
+ return value;
45
+ }
46
+
47
+ /** Single pass: text inserted for a placeholder is never scanned again. Unrecognized brace text stays literal. */
48
+ function compileTemplate(template: string, scope: TemplateScope): string {
49
+ const parts: string[] = [];
50
+ let cursor = 0;
51
+ for (const match of template.matchAll(PLACEHOLDER_PATTERN)) {
52
+ const literal = template.slice(cursor, match.index);
53
+ cursor = match.index + match[0].length;
54
+ let variable: string;
55
+ if (match[0] === "{task}") {
56
+ if (!scope.hasOriginalTask) throw new Error(`${scope.path} references {task}, but no top-level task was provided.`);
57
+ variable = "originalTask";
58
+ } else if (match[0] === "{previous}") {
59
+ if ("unavailable" in scope.previous) throw new Error(`${scope.path} cannot use {previous}; ${scope.previous.unavailable}`);
60
+ variable = scope.previous.variable;
61
+ } else {
62
+ const name = match[1]!;
63
+ if (!scope.outputs) throw new Error(`${scope.path} cannot use {outputs.${name}}; ${scope.outputsUnavailable}`);
64
+ const named = scope.outputs.get(name);
65
+ if (!named) throw new Error(`${scope.path} references {outputs.${name}}, but no earlier sequential step sets as: "${name}".`);
66
+ variable = named;
67
+ }
68
+ if (literal) parts.push(JSON.stringify(literal));
69
+ parts.push(variable);
70
+ }
71
+ const literal = template.slice(cursor);
72
+ if (literal || parts.length === 0) parts.push(JSON.stringify(literal));
73
+ return parts.join(" + ");
74
+ }
75
+
76
+ function prelude(originalTask: string | undefined): string[] {
77
+ return originalTask === undefined ? [SETTLE_HELPER] : [SETTLE_HELPER, `const originalTask = ${JSON.stringify(originalTask)};`];
78
+ }
79
+
80
+ function runsAllCall(children: readonly StepChild[]): string {
81
+ return `await runs.all([${children.map((child) => `{ key: ${JSON.stringify(child.key)}, agent: ${JSON.stringify(child.agent)}, task: ${child.taskExpression} }`).join(", ")}])`;
82
+ }
83
+
84
+ const SETTLE_HELPER = [
85
+ "function settle(results, agents) {",
86
+ " return results.map(function (result, index) {",
87
+ " const child = { key: result.key, agent: agents[index], ok: result.ok === true, output: typeof result.output === \"string\" ? result.output : \"\" };",
88
+ " if (!child.ok && typeof result.error === \"string\") child.error = result.error;",
89
+ " return child;",
90
+ " });",
91
+ "}",
92
+ // A failed child fails the workflow; the runtime keeps every settled child in the partial results.
93
+ "function failure(label, children) {",
94
+ " return new Error(label + \": \" + children.filter(function (child) { return !child.ok; }).map(function (child) { return child.key + \" (\" + child.agent + \") failed\" + (child.error ? \": \" + child.error : \"\"); }).join(\"; \"));",
95
+ "}",
96
+ ].join("\n");
97
+
98
+ function buildTasksScript(steps: unknown, originalTask: string | undefined): string {
99
+ if (!Array.isArray(steps) || steps.length === 0) throw new Error("tasks must be a non-empty array of { agent, task } items.");
100
+ const children = steps.map((item, index): StepChild => {
101
+ const path = `tasks[${index}]`;
102
+ const record = exactFields(item, path, ["agent", "task"], "Each tasks item accepts only agent and task.");
103
+ const agent = nonEmptyString(record.agent, `${path}.agent`);
104
+ const task = nonEmptyString(record.task, `${path}.task`);
105
+ const taskExpression = compileTemplate(task, {
106
+ path: `${path}.task`,
107
+ hasOriginalTask: originalTask !== undefined,
108
+ previous: { unavailable: "tasks items may only use {task}." },
109
+ outputsUnavailable: "tasks items may only use {task}.",
110
+ });
111
+ return { key: `task-${index + 1}`, agent, taskExpression };
112
+ });
113
+ return [
114
+ ...prelude(originalTask),
115
+ `const run1 = ${runsAllCall(children)};`,
116
+ `const children = settle(run1, ${JSON.stringify(children.map((child) => child.agent))});`,
117
+ "if (!children.every(function (child) { return child.ok; })) throw failure(\"tasks failed\", children);",
118
+ "return { ok: true, children };",
119
+ ].join("\n");
120
+ }
121
+
122
+ function buildChainScript(steps: unknown, originalTask: string | undefined): string {
123
+ if (!Array.isArray(steps) || steps.length === 0) throw new Error("chain must be a non-empty array of steps.");
124
+ const lines = [...prelude(originalTask), "const children = [];"];
125
+ const hasOriginalTask = originalTask !== undefined;
126
+ const outputs = new Map<string, string>();
127
+ for (const [index, step] of steps.entries()) {
128
+ const number = index + 1;
129
+ const path = `chain[${index}]`;
130
+ const previous: TemplateScope["previous"] = index === 0
131
+ ? { unavailable: "the first chain step has no previous output." }
132
+ : { variable: `output${index}` };
133
+ let stepChildren: StepChild[];
134
+ let outputName: string | undefined;
135
+ if (isPlainRecord(step) && Object.hasOwn(step, "parallel")) {
136
+ const record = exactFields(step, path, ["parallel"], "A parallel step accepts only parallel; as is supported on sequential steps only.");
137
+ const items = record.parallel;
138
+ if (!Array.isArray(items) || items.length === 0) throw new Error(`${path}.parallel must be a non-empty array of { agent, task } items.`);
139
+ stepChildren = items.map((item, itemIndex): StepChild => {
140
+ const itemPath = `${path}.parallel[${itemIndex}]`;
141
+ const itemRecord = exactFields(item, itemPath, ["agent", "task"], "Each parallel item accepts only agent and task.");
142
+ const agent = nonEmptyString(itemRecord.agent, `${itemPath}.agent`);
143
+ const task = nonEmptyString(itemRecord.task, `${itemPath}.task`);
144
+ return { key: `step-${number}-${itemIndex + 1}`, agent, taskExpression: compileTemplate(task, { path: `${itemPath}.task`, hasOriginalTask, previous, outputs }) };
145
+ });
146
+ } else {
147
+ const record = exactFields(step, path, ["agent", "task", "as"], "A sequential step accepts only agent, task and as; a parallel step accepts only parallel.");
148
+ const agent = nonEmptyString(record.agent, `${path}.agent`);
149
+ let task: string;
150
+ if (record.task === undefined) {
151
+ if (index === 0) throw new Error(`${path}.task is required; the first chain step has no previous output.`);
152
+ task = "{previous}";
153
+ } else task = nonEmptyString(record.task, `${path}.task`);
154
+ if (record.as !== undefined) {
155
+ if (typeof record.as !== "string" || !OUTPUT_NAME_PATTERN.test(record.as)) throw new Error(`${path}.as must be an identifier matching ${OUTPUT_NAME_PATTERN}.`);
156
+ if (outputs.has(record.as)) throw new Error(`${path}.as '${record.as}' is already used by an earlier step.`);
157
+ outputName = record.as;
158
+ }
159
+ stepChildren = [{ key: `step-${number}`, agent, taskExpression: compileTemplate(task, { path: `${path}.task`, hasOriginalTask, previous, outputs }) }];
160
+ }
161
+ lines.push(
162
+ `const run${number} = ${runsAllCall(stepChildren)};`,
163
+ `const step${number} = settle(run${number}, ${JSON.stringify(stepChildren.map((child) => child.agent))});`,
164
+ `children.push(...step${number});`,
165
+ `if (!step${number}.every(function (child) { return child.ok; })) throw failure(${JSON.stringify(`chain stopped at step ${number}`)}, step${number});`,
166
+ );
167
+ if (index < steps.length - 1) lines.push(`const output${number} = step${number}.map(function (child) { return child.output; }).join("\\n\\n");`);
168
+ if (outputName !== undefined) outputs.set(outputName, `output${number}`);
169
+ }
170
+ lines.push("return { ok: true, children };");
171
+ return lines.join("\n");
172
+ }
173
+
174
+ /** Validate exact data shapes and expand them into a package-owned workflow script. */
175
+ export function buildStructuredWorkflowScript(kind: StructuredWorkflowKind, steps: unknown, originalTask: string | undefined): string {
176
+ return kind === "tasks" ? buildTasksScript(steps, originalTask) : buildChainScript(steps, originalTask);
177
+ }
@@ -1,4 +1,5 @@
1
1
  import type { AsyncJobStep, HostStepNode, WorkflowGraphNode, WorkflowGraphSnapshot, WorkflowPreflightLane, WorkflowPreflight } from "../shared/types.ts";
2
+ import { childThinkingLevel, type ThinkingLevel } from "../shared/model-info.ts";
2
3
  import { sanitizeDisplayText } from "../shared/display-text.ts";
3
4
  import { workflowPreflightLaneForRuntimeKey as laneFor } from "./workflow-preflight.ts";
4
5
 
@@ -6,6 +7,7 @@ export type WorkflowChecklistState = "complete" | "running" | "queued" | "blocke
6
7
 
7
8
  export interface WorkflowChecklistStep {
8
9
  key?: string;
10
+ thinking?: string;
9
11
  workflowKey?: string;
10
12
  runId?: string;
11
13
  label?: string;
@@ -53,6 +55,8 @@ export interface WorkflowChecklistItem {
53
55
  phase: string;
54
56
  state: WorkflowChecklistState;
55
57
  agent?: string;
58
+ /** Thinking level of the child this item stands for. */
59
+ thinking?: ThinkingLevel;
56
60
  context?: "fresh" | "fork";
57
61
  startedAt?: number;
58
62
  durationMs?: number;
@@ -196,12 +200,14 @@ function stepKey(step: WorkflowChecklistStep): string | undefined {
196
200
 
197
201
  function stepItem(step: WorkflowChecklistStep, index: number, phase: string, key = stepKey(step) ?? `step-${index + 1}`, label = step.label ?? step.description ?? stepKey(step) ?? step.agent ?? key, preflight?: WorkflowPreflightLane): WorkflowChecklistItem {
198
202
  const state = checklistState(step);
203
+ const thinking = childThinkingLevel(step);
199
204
  return {
200
205
  key: keyText(key, `step-${index + 1}`),
201
206
  label: keyText(label, key),
202
207
  phase,
203
208
  state,
204
209
  ...(text(step.agent) ? { agent: text(step.agent) } : {}),
210
+ ...(thinking ? { thinking } : {}),
205
211
  ...(step.context ? { context: step.context } : {}),
206
212
  ...(finite(step.startedAt) !== undefined ? { startedAt: finite(step.startedAt) } : {}),
207
213
  ...(duration(step, undefined, state) !== undefined ? { durationMs: duration(step, undefined, state) } : {}),
@@ -61,6 +61,7 @@ export function workflowChildSummary(input: {
61
61
  progress?: ReadonlyMap<string, WorkflowChildLiveProgress>;
62
62
  }): WorkflowChildSummary {
63
63
  const rows = new Map<string, WorkflowChildSummary["children"][number]>();
64
+ const runningAsyncKeys = new Set(input.children?.filter((child) => child.state === "running").map((child) => child.key));
64
65
  for (const entry of input.trace ?? []) {
65
66
  if (entry.operation !== "run" || !KEY_PATTERN.test(entry.key)) continue;
66
67
  const previous = rows.get(entry.key);
@@ -82,6 +83,7 @@ export function workflowChildSummary(input: {
82
83
  for (const step of input.steps ?? []) {
83
84
  const key = step.workflowKey;
84
85
  if (!key || !KEY_PATTERN.test(key)) continue;
86
+ if (step.async && step.runId && step.status === "running") runningAsyncKeys.add(key);
85
87
  const state = step.status === "complete" || step.status === "completed" ? "completed"
86
88
  : step.status === "failed" ? "failed"
87
89
  : step.status === "paused" ? "paused"
@@ -102,7 +104,7 @@ export function workflowChildSummary(input: {
102
104
  for (const child of input.children ?? []) {
103
105
  if (!KEY_PATTERN.test(child.key)) continue;
104
106
  const result = Array.isArray(child.results) ? child.results.find((value) => value && typeof value === "object") as Record<string, unknown> | undefined : undefined;
105
- const state = child.detached ? "detached" : child.stopped ? "stopped" : child.interrupted ? "paused" : child.ok ? "completed" : result?.acceptance && typeof result.acceptance === "object" && (result.acceptance as { status?: unknown }).status === "rejected" ? "rejected" : "failed";
107
+ const state = child.state === "running" ? "running" : child.detached ? "detached" : child.stopped ? "stopped" : child.interrupted ? "paused" : child.ok ? "completed" : result?.acceptance && typeof result.acceptance === "object" && (result.acceptance as { status?: unknown }).status === "rejected" ? "rejected" : "failed";
106
108
  rows.set(child.key, {
107
109
  childId: child.key,
108
110
  state,
@@ -115,7 +117,7 @@ export function workflowChildSummary(input: {
115
117
  }
116
118
  if (input.inventoryComplete) {
117
119
  for (const [key, row] of rows) {
118
- if (!TERMINAL_STATES.has(row.state)) rows.set(key, { ...row, state: input.workflowState === "stopped" ? "stopped" : "failed" });
120
+ if (!TERMINAL_STATES.has(row.state) && !runningAsyncKeys.has(key)) rows.set(key, { ...row, state: input.workflowState === "stopped" ? "stopped" : "failed" });
119
121
  }
120
122
  }
121
123
  for (const [key, progress] of input.progress ?? []) {
@@ -6,6 +6,7 @@ import type { WorkflowReceiptResumeReference, WorkflowScriptChildResult } from "
6
6
  import { parseWorkflowChildSummary } from "./workflow-child-summary.ts";
7
7
  import { HOST_STEP_MAX_COUNT, assertUniqueHostStepIds, parseHostStepNode } from "../runs/shared/host-step-status.ts";
8
8
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../runs/shared/lane-metadata.ts";
9
+ import { projectWorkflowKeyRevival } from "./workflow-revival.ts";
9
10
 
10
11
  export type { WorkflowReceipt, WorkflowReceiptEntry, WorkflowReceiptState } from "../shared/types.ts";
11
12
 
@@ -362,8 +363,13 @@ export function resolveWorkflowReceiptResumeEntry(input: {
362
363
  if (input.reference.latest !== true) throw new Error("Keyed workflow receipt resume requires latest: true.");
363
364
  const key = assertKey(input.reference.key, "keyed resume key");
364
365
  const receipt = readWorkflowReceipt(input.asyncDirRoot, input.reference.workflowRunId.trim());
365
- const entry = receipt.entries[key];
366
- if (!entry) throw new Error(`Workflow receipt '${receipt.workflowRunId}' has no child key '${key}'.`);
366
+ const recorded = receipt.entries[key];
367
+ if (!recorded) throw new Error(`Workflow receipt '${receipt.workflowRunId}' has no child key '${key}'.`);
368
+ // A detached top-level revival after the receipt was written continues this key's lineage.
369
+ const revival = recorded.latestRunId ? projectWorkflowKeyRevival(input.asyncDirRoot, receipt.workflowRunId, key, recorded.latestRunId) : undefined;
370
+ const entry = revival
371
+ ? { ...recorded, latestRunId: revival.latestRunId, continuation: { runIds: [...recorded.continuation.runIds, ...revival.revivedRunIds] } }
372
+ : recorded;
367
373
  assertResumableEntry(entry, receipt.workflowRunId, key);
368
374
  input.assertResumable?.(entry.latestRunId);
369
375
  return entry;
@@ -6,6 +6,7 @@ import {
6
6
  type WorkflowResourcePermit,
7
7
  } from "../shared/workflow-child-permit.ts";
8
8
  import type { WorkflowResourceProvenance } from "../shared/types.ts";
9
+ import { buildStructuredWorkflowScript, isPlainRecord } from "./structured-workflow-scripts.ts";
9
10
 
10
11
  const RESOURCE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
11
12
  const MAX_ARGS_BYTES = 16 * 1024;
@@ -65,7 +66,7 @@ export function registerWorkflowResource(input: RegisterWorkflowResourceInput):
65
66
  if (typeof name !== "string" || !RESOURCE_NAME_PATTERN.test(name)) throw new Error("Workflow definition requires a safe resource name.");
66
67
  if (!Number.isSafeInteger(version) || version < 1) throw new Error("Workflow definition version must be a positive safe integer.");
67
68
  if (typeof resolve !== "function") throw new Error("Workflow definition requires a synchronous resolve function.");
68
- if (findWorkflowResource(name)) throw new Error(`Workflow resource '${name}' is a protected builtin.`);
69
+ if (findWorkflowResource(name) || STRUCTURED_WORKFLOW_RESOURCE_NAMES.includes(name)) throw new Error(`Workflow resource '${name}' is a protected builtin.`);
69
70
  const current = registry();
70
71
  const bucket = current.bySession.get(sessionId) ?? new Map<string, WorkflowResourceDefinition>();
71
72
  if (!(bucket instanceof Map)) throw new Error("Malformed workflow resource session registry.");
@@ -84,12 +85,6 @@ export function registerWorkflowResource(input: RegisterWorkflowResourceInput):
84
85
  };
85
86
  }
86
87
 
87
- function isPlainRecord(value: unknown): value is Record<string, unknown> {
88
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
89
- const prototype = Object.getPrototypeOf(value);
90
- return prototype === Object.prototype || prototype === null;
91
- }
92
-
93
88
  function jsonByteLength(value: unknown): number {
94
89
  try {
95
90
  const encoded = JSON.stringify(value);
@@ -186,6 +181,32 @@ function listWorkflowResourceNames(): string[] {
186
181
  return WORKFLOW_RESOURCES.map((resource) => resource.name);
187
182
  }
188
183
 
184
+ /** Internal resources for the data-only tasks/chain inputs: reserved against registration, never resolvable or listed by name. */
185
+ const STRUCTURED_WORKFLOW_RESOURCE_NAMES: readonly string[] = ["tasks", "chain"];
186
+ const STRUCTURED_WORKFLOW_RESOURCE_VERSION = 1;
187
+
188
+ /**
189
+ * Expand data-only `tasks` or `chain` input into a package-owned workflow script with a one-use permit.
190
+ * Only the executor calls this, after its own feature and input checks; public named lookup cannot reach it.
191
+ */
192
+ export function resolveStructuredWorkflowResource(input: { kind: "tasks" | "chain"; steps: unknown; task?: unknown }): WorkflowResourceResolution {
193
+ try {
194
+ if (!isPlainRecord(input) || (input.kind !== "tasks" && input.kind !== "chain")) return { ok: false, error: "Structured workflow kind must be 'tasks' or 'chain'." };
195
+ const { kind, steps, task } = input;
196
+ if (!Array.isArray(steps) || steps.length === 0) return { ok: false, error: `${kind} must be a non-empty array.` };
197
+ validatePlainJson(steps, kind);
198
+ if (task !== undefined) {
199
+ if (typeof task !== "string" || !task.trim()) return { ok: false, error: "task must be a non-empty string when provided." };
200
+ validatePlainJson(task, "task");
201
+ }
202
+ if (jsonByteLength({ [kind]: steps, task }) > MAX_ARGS_BYTES) return { ok: false, error: `${kind} input exceeds ${MAX_ARGS_BYTES} bytes.` };
203
+ const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task);
204
+ return { ok: true, resource: issueWorkflowResource(kind, STRUCTURED_WORKFLOW_RESOURCE_VERSION, script) };
205
+ } catch (error) {
206
+ return { ok: false, error: error instanceof Error ? error.message.slice(0, 4096) : "Structured workflow resolution failed." };
207
+ }
208
+ }
209
+
189
210
  /** Resolve only extension-owned resources so policy can distinguish them from raw scripts; caller-provided script text is never consulted. */
190
211
  export function resolveWorkflowResource(nameValue: unknown, argsValue?: unknown, sessionId?: string): WorkflowResourceResolution {
191
212
  try {
@@ -216,21 +237,25 @@ function resolveResource(nameValue: unknown, argsValue?: unknown, sessionId?: st
216
237
  }
217
238
  const { script, hostCommands } = resolved;
218
239
  if (Object.keys(resolved).some((key) => key !== "script" && key !== "hostCommands") || typeof script !== "string" || !script.trim()) throw new Error("Workflow resource returned an invalid expansion.");
240
+ return { ok: true, resource: issueWorkflowResource(resource.name, resource.version, script, hostCommands) };
241
+ }
242
+
243
+ function issueWorkflowResource(name: string, version: number, script: string, hostCommands?: readonly WorkflowResourceHostAuthority[]): ResolvedWorkflowResource {
219
244
  const resourceId = randomUUID();
220
245
  const permit = createWorkflowResourcePermit({
221
- resourceName: resource.name,
222
- resourceVersion: resource.version,
246
+ resourceName: name,
247
+ resourceVersion: version,
223
248
  resourceId,
224
249
  scriptDigest: stableJsonDigest(script),
225
250
  authority: { host: hostCommands },
226
251
  });
227
252
  const provenance: WorkflowResourceProvenance = Object.freeze({
228
253
  kind: "workflow",
229
- name: resource.name,
230
- version: resource.version,
254
+ name,
255
+ version,
231
256
  invocation: "named",
232
257
  expansion: "resolved",
233
258
  id: resourceId,
234
259
  });
235
- return { ok: true, resource: { script, permit, provenance } };
260
+ return { script, permit, provenance };
236
261
  }
@@ -0,0 +1,120 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { readRecentTerminalRunIndex } from "../runs/background/terminal-run-index.ts";
5
+ import { readStatus } from "../shared/utils.ts";
6
+ import { workflowRunParamsFingerprint, type WorkflowScriptChildResult } from "./scripted-workflow.ts";
7
+
8
+ /** Stop cause recorded when the extension runtime that owned the workflow was replaced (/reload, resume, project switch). */
9
+ const WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED = "runtime-replaced";
10
+ type WorkflowStopCause = typeof WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED;
11
+
12
+ const WORKFLOW_CHILD_JOURNAL_FILE = "workflow-children.jsonl";
13
+
14
+ export const WORKFLOW_RUNTIME_REPLACED_RELAUNCH_NOTICE = "Async children that were still running keep running; relaunch the same workflow script with the same args to reuse finished children and re-attach to running ones.";
15
+
16
+ /** Abort reason for workflow controllers torn down by runtime replacement; carries the cause as data, not text. */
17
+ export function runtimeReplacedAbortReason(): Error {
18
+ return Object.assign(new Error("Workflow stopped because the extension session was replaced or reloaded."), { workflowStopCause: WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED });
19
+ }
20
+
21
+ export function workflowStopCause(reason: unknown): WorkflowStopCause | undefined {
22
+ return reason instanceof Error && "workflowStopCause" in reason && reason.workflowStopCause === WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED
23
+ ? WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED
24
+ : undefined;
25
+ }
26
+
27
+ function sha256(text: string): string {
28
+ return createHash("sha256").update(text).digest("hex");
29
+ }
30
+
31
+ export function workflowScriptDigest(script: string): string {
32
+ return sha256(script);
33
+ }
34
+
35
+ /** Hash of the canonical launch params the script host uses to detect duplicate keys. */
36
+ export function workflowChildFingerprint(params: Record<string, unknown>): string {
37
+ return sha256(workflowRunParamsFingerprint(params));
38
+ }
39
+
40
+ type WorkflowChildJournalRecord =
41
+ | { type: "start"; key: string; fingerprint: string; runId: string }
42
+ | { type: "settle"; key: string; fingerprint: string; result: WorkflowScriptChildResult };
43
+
44
+ /** Appends synchronously. A lost record only means a later relaunch runs that child again. */
45
+ export function appendWorkflowChildJournal(workflowAsyncDir: string, record: WorkflowChildJournalRecord): void {
46
+ const journalPath = path.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE);
47
+ try {
48
+ fs.appendFileSync(journalPath, `${JSON.stringify(record)}\n`, "utf-8");
49
+ } catch (error) {
50
+ console.error(`Failed to append workflow child journal '${journalPath}':`, error);
51
+ }
52
+ }
53
+
54
+ interface WorkflowReuseSource {
55
+ runId: string;
56
+ started: Map<string, { fingerprint: string; runId: string }>;
57
+ settled: Map<string, { fingerprint: string; result: WorkflowScriptChildResult }>;
58
+ }
59
+
60
+ type WorkflowReuseMatch =
61
+ | { kind: "settled"; result: WorkflowScriptChildResult }
62
+ | { kind: "started"; runId: string };
63
+
64
+ function readWorkflowChildJournal(runId: string, workflowAsyncDir: string): WorkflowReuseSource {
65
+ const source: WorkflowReuseSource = { runId, started: new Map(), settled: new Map() };
66
+ let text = "";
67
+ try {
68
+ text = fs.readFileSync(path.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE), "utf-8");
69
+ } catch {
70
+ return source;
71
+ }
72
+ for (const line of text.split("\n")) {
73
+ let record: Partial<WorkflowChildJournalRecord> | undefined;
74
+ try {
75
+ record = line.trim() ? JSON.parse(line) as Partial<WorkflowChildJournalRecord> : undefined;
76
+ } catch {
77
+ continue;
78
+ }
79
+ if (!record || typeof record.key !== "string" || typeof record.fingerprint !== "string") continue;
80
+ if (record.type === "start" && typeof record.runId === "string") {
81
+ source.started.set(record.key, { fingerprint: record.fingerprint, runId: record.runId });
82
+ } else if (record.type === "settle" && record.result && typeof record.result === "object") {
83
+ source.settled.set(record.key, { fingerprint: record.fingerprint, result: record.result });
84
+ }
85
+ }
86
+ return source;
87
+ }
88
+
89
+ /**
90
+ * The newest terminal workflow of this session with the same script and args,
91
+ * when that run stopped because its runtime was replaced.
92
+ */
93
+ export function findWorkflowReuseSource(asyncDirRoot: string, sessionId: string, scriptDigest: string, argsDigest: string | undefined): WorkflowReuseSource | undefined {
94
+ let runIds: string[];
95
+ try {
96
+ runIds = readRecentTerminalRunIndex(asyncDirRoot, { sessionId });
97
+ } catch {
98
+ return undefined;
99
+ }
100
+ for (const runId of runIds) {
101
+ const asyncDir = path.join(asyncDirRoot, runId);
102
+ let status: ReturnType<typeof readStatus>;
103
+ try {
104
+ status = readStatus(asyncDir);
105
+ } catch {
106
+ continue;
107
+ }
108
+ if (status?.mode !== "workflow" || status.workflow?.scriptDigest !== scriptDigest || status.workflow.argsDigest !== argsDigest) continue;
109
+ return status.workflow.stopCause === WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED ? readWorkflowChildJournal(runId, asyncDir) : undefined;
110
+ }
111
+ return undefined;
112
+ }
113
+
114
+ /** A settled match is reusable only when that child succeeded; failed or stopped children run again. */
115
+ export function matchWorkflowReuse(source: WorkflowReuseSource, key: string, fingerprint: string): WorkflowReuseMatch | undefined {
116
+ const settled = source.settled.get(key);
117
+ if (settled) return settled.fingerprint === fingerprint && settled.result.ok ? { kind: "settled", result: settled.result } : undefined;
118
+ const started = source.started.get(key);
119
+ return started?.fingerprint === fingerprint ? { kind: "started", runId: started.runId } : undefined;
120
+ }
@@ -0,0 +1,123 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { writePrivateAtomicJson } from "../shared/atomic-json.ts";
4
+ import type { AsyncStatus } from "../shared/types.ts";
5
+ import { readStatus } from "../shared/utils.ts";
6
+ import type { WorkflowScriptChildResult } from "./scripted-workflow.ts";
7
+
8
+ /**
9
+ * A top-level resume of a failed async workflow child starts a detached run. These records
10
+ * link that run back to its workflow key without writing the workflow's own status or receipt.
11
+ * The source run is terminal, so the live workflow host never writes its directory.
12
+ */
13
+ const REVIVAL_LINK_FILE = "workflow-revival.json";
14
+ /** The same link, kept in the revived run's directory so reviving it again keeps the key. */
15
+ export const REVIVAL_ORIGIN_FILE = "workflow-revival-origin.json";
16
+ /** Recording refuses a deeper link, so readers bounded by this always reach the chain's end. */
17
+ const MAX_REVIVAL_DEPTH = 16;
18
+ const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
19
+
20
+ interface WorkflowRevivalLink {
21
+ version: 1;
22
+ workflowRunId: string;
23
+ workflowKey: string;
24
+ sourceRunId: string;
25
+ revivedRunId: string;
26
+ /** 1 for a revival of the workflow's own child, one more for each revival of a revival. */
27
+ depth: number;
28
+ }
29
+
30
+ export interface WorkflowKeyRevival {
31
+ /** Revived runs after the given run, oldest first. */
32
+ revivedRunIds: string[];
33
+ latestRunId: string;
34
+ /** State of the latest revived run; undefined when its status is unreadable. */
35
+ state?: AsyncStatus["state"];
36
+ }
37
+
38
+ function isRunId(value: unknown): value is string {
39
+ return typeof value === "string" && value.length > 0 && value.length <= 255 && path.basename(value) === value && value !== "." && value !== "..";
40
+ }
41
+
42
+ function readLink(file: string): WorkflowRevivalLink | undefined {
43
+ let value: unknown;
44
+ try {
45
+ value = JSON.parse(fs.readFileSync(file, "utf-8"));
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
50
+ const link = value as Record<string, unknown>;
51
+ if (link.version !== 1 || !isRunId(link.workflowRunId) || typeof link.workflowKey !== "string" || !KEY_PATTERN.test(link.workflowKey) || !isRunId(link.sourceRunId) || !isRunId(link.revivedRunId)) return undefined;
52
+ if (!Number.isInteger(link.depth) || (link.depth as number) < 1 || (link.depth as number) > MAX_REVIVAL_DEPTH) return undefined;
53
+ return { version: 1, workflowRunId: link.workflowRunId, workflowKey: link.workflowKey, sourceRunId: link.sourceRunId, revivedRunId: link.revivedRunId, depth: link.depth as number };
54
+ }
55
+
56
+ /**
57
+ * Links a detached revival to the workflow key of its source run when the source failed and is
58
+ * an async workflow child or an earlier revival of one. Throws when the source status cannot be
59
+ * read or the key's revival chain is full; the caller reports that on the revive receipt.
60
+ */
61
+ export function recordWorkflowRevival(asyncDirRoot: string, sourceRunId: string, revivedRunId: string): void {
62
+ const sourceDir = path.join(asyncDirRoot, sourceRunId);
63
+ const status = readStatus(sourceDir);
64
+ if (status?.runId !== sourceRunId || status.state !== "failed") return;
65
+ const origin = isRunId(status.parentWorkflowRunId) && typeof status.workflowKey === "string" && KEY_PATTERN.test(status.workflowKey)
66
+ ? { workflowRunId: status.parentWorkflowRunId, workflowKey: status.workflowKey, depth: 0 }
67
+ : readLink(path.join(sourceDir, REVIVAL_ORIGIN_FILE));
68
+ if (!origin || ("revivedRunId" in origin && origin.revivedRunId !== sourceRunId)) return;
69
+ if (origin.depth >= MAX_REVIVAL_DEPTH) throw new Error(`workflow key '${origin.workflowKey}' of ${origin.workflowRunId} already has ${MAX_REVIVAL_DEPTH} chained revivals.`);
70
+ const link: WorkflowRevivalLink = { version: 1, workflowRunId: origin.workflowRunId, workflowKey: origin.workflowKey, sourceRunId, revivedRunId, depth: origin.depth + 1 };
71
+ const originFile = path.join(asyncDirRoot, revivedRunId, REVIVAL_ORIGIN_FILE);
72
+ writePrivateAtomicJson(originFile, link);
73
+ try {
74
+ writePrivateAtomicJson(path.join(sourceDir, REVIVAL_LINK_FILE), link);
75
+ } catch (error) {
76
+ // Keep the origin exactly when the published link names this revival: an unlinked origin
77
+ // would only pin the run against retention, and a linked one protects the key's chain.
78
+ if (readLink(path.join(sourceDir, REVIVAL_LINK_FILE))?.revivedRunId !== revivedRunId) fs.rmSync(originFile, { force: true });
79
+ throw error;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Follows revival links from one run of a workflow key by exact reads. Returns undefined when
85
+ * the run was never revived; malformed or mismatched links end the chain.
86
+ */
87
+ export function projectWorkflowKeyRevival(asyncDirRoot: string, workflowRunId: string, workflowKey: string, runId: string): WorkflowKeyRevival | undefined {
88
+ if (!isRunId(runId)) return undefined;
89
+ const revivedRunIds: string[] = [];
90
+ let current = runId;
91
+ while (revivedRunIds.length < MAX_REVIVAL_DEPTH) {
92
+ const link = readLink(path.join(asyncDirRoot, current, REVIVAL_LINK_FILE));
93
+ if (!link || link.sourceRunId !== current || link.workflowRunId !== workflowRunId || link.workflowKey !== workflowKey) break;
94
+ revivedRunIds.push(link.revivedRunId);
95
+ current = link.revivedRunId;
96
+ }
97
+ if (revivedRunIds.length === 0) return undefined;
98
+ let status: AsyncStatus | null = null;
99
+ try {
100
+ status = readStatus(path.join(asyncDirRoot, current));
101
+ } catch {
102
+ // Readers show "status unavailable" instead of failing the workflow's status or notice.
103
+ }
104
+ return { revivedRunIds, latestRunId: current, ...(status?.runId === current ? { state: status.state } : {}) };
105
+ }
106
+
107
+ /** `Revived → <run> [→ <run>]: <state>`, shown next to the key's original failure. */
108
+ export function formatWorkflowKeyRevival(revival: WorkflowKeyRevival): string {
109
+ return `Revived → ${revival.revivedRunIds.join(" → ")}: ${revival.state === "complete" ? "completed" : revival.state ?? "status unavailable"}`;
110
+ }
111
+
112
+ /**
113
+ * Adds each failed child's revivals to its lineage, so the receipt's latest run for that key is
114
+ * the newest revival. The child's own result and evidence stay as they were.
115
+ */
116
+ export function withWorkflowRevivals<T extends WorkflowScriptChildResult>(asyncDirRoot: string, workflowRunId: string, children: T[]): Array<T & { revival?: WorkflowKeyRevival }> {
117
+ return children.map((child) => {
118
+ if (child.ok || child.state === "running" || !child.runId) return child;
119
+ const lineage = child.continuation?.runIds ?? [child.runId];
120
+ const revival = projectWorkflowKeyRevival(asyncDirRoot, workflowRunId, child.key, lineage.at(-1) ?? child.runId);
121
+ return revival ? { ...child, continuation: { runIds: [...lineage, ...revival.revivedRunIds] }, revival } : child;
122
+ });
123
+ }
@@ -28,7 +28,10 @@ export interface WorkflowPublicChild {
28
28
  output: string;
29
29
  outputState: "present" | "absent";
30
30
  structuredOutput?: unknown;
31
- success: boolean;
31
+ /** Omitted for running launch receipts. */
32
+ success?: boolean;
33
+ state?: "running";
34
+ asyncDir?: string;
32
35
  terminalOutcome?: WorkflowTerminalOutcome;
33
36
  outputReference?: string;
34
37
  outputPathMapping?: { requestedPath: string; savedPath: string };