@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,85 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+
3
+ interface PostExitStdioGuardOptions {
4
+ idleMs: number;
5
+ hardMs: number;
6
+ }
7
+
8
+ interface ChildWithPipedStdio {
9
+ stdout: ChildProcess["stdout"];
10
+ stderr: ChildProcess["stderr"];
11
+ on: ChildProcess["on"];
12
+ }
13
+
14
+ interface ChildWithKill {
15
+ kill(signal?: NodeJS.Signals | number): boolean;
16
+ }
17
+
18
+ export function trySignalChild(child: ChildWithKill, signal: NodeJS.Signals): boolean {
19
+ try {
20
+ return child.kill(signal);
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ export function attachPostExitStdioGuard(
27
+ child: ChildWithPipedStdio,
28
+ options: PostExitStdioGuardOptions,
29
+ ): () => void {
30
+ const { idleMs, hardMs } = options;
31
+ let exited = false;
32
+ let stdoutEnded = false;
33
+ let stderrEnded = false;
34
+ let idleTimer: NodeJS.Timeout | undefined;
35
+ let hardTimer: NodeJS.Timeout | undefined;
36
+
37
+ const destroyUnendedStdio = () => {
38
+ if (!stdoutEnded) {
39
+ try { child.stdout?.destroy(); } catch {}
40
+ }
41
+ if (!stderrEnded) {
42
+ try { child.stderr?.destroy(); } catch {}
43
+ }
44
+ };
45
+
46
+ const clearTimers = () => {
47
+ if (idleTimer) {
48
+ clearTimeout(idleTimer);
49
+ idleTimer = undefined;
50
+ }
51
+ if (hardTimer) {
52
+ clearTimeout(hardTimer);
53
+ hardTimer = undefined;
54
+ }
55
+ };
56
+
57
+ const armIdleTimer = () => {
58
+ if (!exited) return;
59
+ if (idleTimer) clearTimeout(idleTimer);
60
+ idleTimer = setTimeout(destroyUnendedStdio, idleMs);
61
+ idleTimer.unref?.();
62
+ };
63
+
64
+ child.stdout?.on("data", armIdleTimer);
65
+ child.stderr?.on("data", armIdleTimer);
66
+ child.stdout?.on("end", () => {
67
+ stdoutEnded = true;
68
+ if (stdoutEnded && stderrEnded) clearTimers();
69
+ });
70
+ child.stderr?.on("end", () => {
71
+ stderrEnded = true;
72
+ if (stdoutEnded && stderrEnded) clearTimers();
73
+ });
74
+ child.on("exit", () => {
75
+ exited = true;
76
+ armIdleTimer();
77
+ if (hardTimer) return;
78
+ hardTimer = setTimeout(destroyUnendedStdio, hardMs);
79
+ hardTimer.unref?.();
80
+ });
81
+ child.on("close", clearTimers);
82
+ child.on("error", clearTimers);
83
+
84
+ return clearTimers;
85
+ }
@@ -0,0 +1,10 @@
1
+ interface SessionIdentityManager {
2
+ getSessionFile(): string | null | undefined;
3
+ getSessionId(): string | null | undefined;
4
+ }
5
+
6
+ export function resolveCurrentSessionId(sessionManager: SessionIdentityManager): string {
7
+ const sessionId = sessionManager.getSessionFile() ?? sessionManager.getSessionId();
8
+ if (!sessionId) throw new Error("Current session identity is unavailable.");
9
+ return sessionId;
10
+ }
@@ -0,0 +1,44 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { TokenUsage } from "./types.ts";
4
+
5
+ function findLatestSessionFile(sessionDir: string): string | null {
6
+ try {
7
+ const files = fs.readdirSync(sessionDir)
8
+ .filter((f) => f.endsWith(".jsonl"))
9
+ .map((f) => path.join(sessionDir, f));
10
+ if (files.length === 0) return null;
11
+ files.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
12
+ return files[0] ?? null;
13
+ } catch {
14
+ // Session token lookup is optional metadata.
15
+ return null;
16
+ }
17
+ }
18
+
19
+ export function parseSessionTokens(sessionDir: string): TokenUsage | null {
20
+ const sessionFile = findLatestSessionFile(sessionDir);
21
+ if (!sessionFile) return null;
22
+ try {
23
+ const content = fs.readFileSync(sessionFile, "utf-8");
24
+ let input = 0;
25
+ let output = 0;
26
+ for (const line of content.split("\n")) {
27
+ if (!line.trim()) continue;
28
+ try {
29
+ const entry = JSON.parse(line);
30
+ const usage = entry.usage ?? entry.message?.usage;
31
+ if (usage) {
32
+ input += usage.inputTokens ?? usage.input ?? 0;
33
+ output += usage.outputTokens ?? usage.output ?? 0;
34
+ }
35
+ } catch {
36
+ // Ignore malformed lines while scanning usage entries.
37
+ }
38
+ }
39
+ return { input, output, total: input + output };
40
+ } catch {
41
+ // Usage extraction should not fail the run.
42
+ return null;
43
+ }
44
+ }
@@ -0,0 +1,501 @@
1
+ /**
2
+ * Chain behavior, template resolution, and directory management
3
+ */
4
+
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import type { AgentConfig } from "../agents/agents.ts";
9
+ import { normalizeSkillInput } from "../agents/skills.ts";
10
+ import { CHAIN_RUNS_DIR, type AcceptanceInput, type AgentContract, type ChainGateLayer, type JsonSchemaObject, type OutputMode, type ToolBudgetConfig } from "./types.ts";
11
+ const CHAIN_DIR_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours
12
+ const INITIAL_PROGRESS_CONTENT = "# Progress\n\n## Status\nIn Progress\n\n## Tasks\n\n## Files Changed\n\n## Notes\n";
13
+
14
+ // =============================================================================
15
+ // Behavior Resolution Types
16
+ // =============================================================================
17
+
18
+ export interface ResolvedStepBehavior {
19
+ output: string | false;
20
+ outputMode: OutputMode;
21
+ reads: string[] | false;
22
+ progress: boolean;
23
+ skills: string[] | false;
24
+ model?: string;
25
+ }
26
+
27
+ export type OutputOverrideInput = string | boolean;
28
+
29
+ export interface StepOverrides {
30
+ output?: OutputOverrideInput;
31
+ outputMode?: OutputMode;
32
+ reads?: string[] | false;
33
+ progress?: boolean;
34
+ skills?: string[] | false;
35
+ model?: string;
36
+ }
37
+
38
+ function normalizeOutputOverride(output: unknown): string | false | undefined {
39
+ if (output === false || output === "false") return false;
40
+ if (output === true || output === "true") return undefined;
41
+ return typeof output === "string" && output.length > 0 ? output : undefined;
42
+ }
43
+
44
+ // =============================================================================
45
+ // Chain Step Types
46
+ // =============================================================================
47
+
48
+ /** Sequential step: single agent execution */
49
+ export interface SequentialStep {
50
+ agent: string;
51
+ task?: string;
52
+ phase?: string;
53
+ label?: string;
54
+ as?: string;
55
+ outputSchema?: JsonSchemaObject;
56
+ cwd?: string;
57
+ output?: OutputOverrideInput;
58
+ outputMode?: OutputMode;
59
+ reads?: string[] | false;
60
+ progress?: boolean;
61
+ skill?: string | string[] | false;
62
+ model?: string;
63
+ toolBudget?: ToolBudgetConfig;
64
+ acceptance?: AcceptanceInput;
65
+ agentContract?: AgentContract;
66
+ gateOn?: ChainGateLayer;
67
+ }
68
+
69
+ /** Parallel task item within a parallel step */
70
+ export interface ParallelTaskItem {
71
+ agent: string;
72
+ task?: string;
73
+ phase?: string;
74
+ label?: string;
75
+ as?: string;
76
+ outputSchema?: JsonSchemaObject;
77
+ cwd?: string;
78
+ count?: number;
79
+ output?: OutputOverrideInput;
80
+ outputMode?: OutputMode;
81
+ reads?: string[] | false;
82
+ progress?: boolean;
83
+ skill?: string | string[] | false;
84
+ model?: string;
85
+ toolBudget?: ToolBudgetConfig;
86
+ acceptance?: AcceptanceInput;
87
+ agentContract?: AgentContract;
88
+ gateOn?: ChainGateLayer;
89
+ }
90
+
91
+ export interface DynamicExpandSpec {
92
+ from: {
93
+ output: string;
94
+ path: string;
95
+ };
96
+ item?: string;
97
+ key?: string;
98
+ maxItems?: number;
99
+ onEmpty?: "skip" | "fail";
100
+ }
101
+
102
+ export type DynamicParallelTemplate = Omit<ParallelTaskItem, "as" | "count">;
103
+
104
+ export interface DynamicCollectSpec {
105
+ as: string;
106
+ outputSchema?: JsonSchemaObject;
107
+ }
108
+
109
+ export interface DynamicParallelStep {
110
+ expand: DynamicExpandSpec;
111
+ parallel: DynamicParallelTemplate;
112
+ collect: DynamicCollectSpec;
113
+ concurrency?: number;
114
+ failFast?: boolean;
115
+ phase?: string;
116
+ label?: string;
117
+ acceptance?: AcceptanceInput;
118
+ agentContract?: AgentContract;
119
+ gateOn?: ChainGateLayer;
120
+ }
121
+
122
+ /** Approval checkpoint: pause before later chain steps until parent approval. */
123
+ export interface CheckpointStep {
124
+ checkpoint: string;
125
+ message?: string;
126
+ phase?: string;
127
+ label?: string;
128
+ agent?: string;
129
+ task?: string;
130
+ as?: string;
131
+ output?: OutputOverrideInput;
132
+ outputMode?: OutputMode;
133
+ reads?: string[] | false;
134
+ progress?: boolean;
135
+ skill?: string | string[] | false;
136
+ skills?: string[] | false;
137
+ model?: string;
138
+ }
139
+
140
+ /** Parallel step: multiple agents running concurrently */
141
+ export interface ParallelStep {
142
+ parallel: ParallelTaskItem[];
143
+ concurrency?: number;
144
+ failFast?: boolean;
145
+ worktree?: boolean;
146
+ cwd?: string;
147
+ agentContract?: AgentContract;
148
+ gateOn?: ChainGateLayer;
149
+ }
150
+
151
+ /** Union type for chain steps */
152
+ export type ChainStep = SequentialStep | ParallelStep | DynamicParallelStep | CheckpointStep;
153
+
154
+ // =============================================================================
155
+ // Type Guards
156
+ // =============================================================================
157
+
158
+ export function isCheckpointStep(step: ChainStep): step is CheckpointStep {
159
+ return "checkpoint" in step;
160
+ }
161
+
162
+ export function isParallelStep(step: ChainStep): step is ParallelStep {
163
+ return "parallel" in step && Array.isArray((step as ParallelStep).parallel);
164
+ }
165
+
166
+ export function isDynamicParallelStep(step: ChainStep): step is DynamicParallelStep {
167
+ return "expand" in step && "collect" in step && "parallel" in step && !Array.isArray((step as { parallel?: unknown }).parallel);
168
+ }
169
+
170
+ /** Get all agent names in a step (single for sequential, multiple for parallel) */
171
+ export function getStepAgents(step: ChainStep): string[] {
172
+ if (isCheckpointStep(step)) {
173
+ return [];
174
+ }
175
+ if (isParallelStep(step)) {
176
+ return step.parallel.map((t) => t.agent);
177
+ }
178
+ if (isDynamicParallelStep(step)) {
179
+ return [step.parallel.agent];
180
+ }
181
+ return [step.agent];
182
+ }
183
+
184
+ // =============================================================================
185
+ // Chain Directory Management
186
+ // =============================================================================
187
+
188
+ export function createChainDir(runId: string, baseDir?: string): string {
189
+ const chainDir = path.join(baseDir ? path.resolve(baseDir) : CHAIN_RUNS_DIR, runId);
190
+ fs.mkdirSync(chainDir, { recursive: true });
191
+ return chainDir;
192
+ }
193
+
194
+ export function removeChainDir(chainDir: string): void {
195
+ try {
196
+ fs.rmSync(chainDir, { recursive: true });
197
+ } catch {
198
+ // Chain cleanup is best-effort. Runs can already have cleaned their temp dir.
199
+ }
200
+ }
201
+
202
+ export function cleanupOldChainDirs(): void {
203
+ if (!fs.existsSync(CHAIN_RUNS_DIR)) return;
204
+ const now = Date.now();
205
+ let dirs: string[];
206
+ try {
207
+ dirs = fs.readdirSync(CHAIN_RUNS_DIR);
208
+ } catch {
209
+ // Startup cleanup is best-effort. If the scoped temp root is unreadable,
210
+ // skip cleanup instead of failing extension startup.
211
+ return;
212
+ }
213
+
214
+ for (const dir of dirs) {
215
+ try {
216
+ const dirPath = path.join(CHAIN_RUNS_DIR, dir);
217
+ const stat = fs.statSync(dirPath);
218
+ if (stat.isDirectory() && now - stat.mtimeMs > CHAIN_DIR_MAX_AGE_MS) {
219
+ fs.rmSync(dirPath, { recursive: true });
220
+ }
221
+ } catch {
222
+ // Skip directories that can't be processed; continue with others
223
+ }
224
+ }
225
+ }
226
+
227
+ // =============================================================================
228
+ // Template Resolution
229
+ // =============================================================================
230
+
231
+ /** Resolved templates for a chain - string for sequential, string[] for parallel */
232
+ export type ResolvedTemplates = (string | string[])[];
233
+
234
+ /**
235
+ * Resolve templates for a chain with parallel step support.
236
+ * Returns string for sequential steps, string[] for parallel steps.
237
+ */
238
+ export function resolveChainTemplates(
239
+ steps: ChainStep[],
240
+ ): ResolvedTemplates {
241
+ return steps.map((step, i) => {
242
+ if (isCheckpointStep(step)) return "";
243
+ if (isParallelStep(step)) {
244
+ // Parallel step: resolve each task's template
245
+ return step.parallel.map((task) => {
246
+ if (task.task) return task.task;
247
+ // Default for parallel tasks is {previous}
248
+ return "{previous}";
249
+ });
250
+ }
251
+ if (isDynamicParallelStep(step)) {
252
+ return step.parallel.task ?? "{previous}";
253
+ }
254
+ // Sequential step: existing logic
255
+ const seq = step as SequentialStep;
256
+ if (seq.task) return seq.task;
257
+ // Default: first step uses {task}, others use {previous}
258
+ return i === 0 ? "{task}" : "{previous}";
259
+ });
260
+ }
261
+
262
+ // =============================================================================
263
+ // Behavior Resolution
264
+ // =============================================================================
265
+
266
+ /**
267
+ * Resolve effective chain behavior per step.
268
+ * Priority: step override > agent frontmatter > false (disabled)
269
+ */
270
+ export function resolveStepBehavior(
271
+ agentConfig: AgentConfig,
272
+ stepOverrides: StepOverrides,
273
+ chainSkills?: string[],
274
+ ): ResolvedStepBehavior {
275
+ // Output: step override > frontmatter > false (no output)
276
+ const stepOutput = normalizeOutputOverride(stepOverrides.output);
277
+ const output =
278
+ stepOutput !== undefined
279
+ ? stepOutput
280
+ : normalizeOutputOverride(agentConfig.output) ?? false;
281
+
282
+ // Reads: step override > frontmatter defaultReads > false (no reads)
283
+ const reads =
284
+ stepOverrides.reads !== undefined
285
+ ? stepOverrides.reads
286
+ : agentConfig.defaultReads ?? false;
287
+
288
+ // Progress: step override > frontmatter defaultProgress > false
289
+ const progress =
290
+ stepOverrides.progress !== undefined
291
+ ? stepOverrides.progress
292
+ : agentConfig.defaultProgress ?? false;
293
+
294
+ let skills: string[] | false;
295
+ if (stepOverrides.skills === false) {
296
+ skills = false;
297
+ } else if (stepOverrides.skills !== undefined) {
298
+ skills = [...stepOverrides.skills];
299
+ if (chainSkills && chainSkills.length > 0) {
300
+ skills = [...new Set([...skills, ...chainSkills])];
301
+ }
302
+ } else {
303
+ skills = agentConfig.skills ? [...agentConfig.skills] : [];
304
+ if (chainSkills && chainSkills.length > 0) {
305
+ skills = [...new Set([...skills, ...chainSkills])];
306
+ }
307
+ }
308
+
309
+ const outputMode = stepOverrides.outputMode ?? "inline";
310
+ const model = stepOverrides.model ?? agentConfig.model;
311
+ return { output, outputMode, reads, progress, skills, model };
312
+ }
313
+
314
+ export function resolveTaskTextForFileUpdatePolicy(task: string | undefined, originalTask?: string): string | undefined {
315
+ if (!task) return originalTask;
316
+ return originalTask ? task.replaceAll("{task}", originalTask) : task;
317
+ }
318
+
319
+ export function taskDisallowsFileUpdates(task: string | undefined): boolean {
320
+ if (!task) return false;
321
+ return /\breview[- ]only\b/i.test(task)
322
+ || /\bread[- ]only\s+(?:review|audit|inspection|pass)\b/i.test(task)
323
+ || /\b(?:no|without)\s+(?:file\s+)?edits?\b/i.test(task)
324
+ || /\b(?:do not|don't|must not)\s+(?:edit|modify|write|touch)\b/i.test(task)
325
+ || /\bleave\s+files?\s+unchanged\b/i.test(task);
326
+ }
327
+
328
+ export function suppressProgressForReadOnlyTask(behavior: ResolvedStepBehavior, task: string | undefined, originalTask?: string): ResolvedStepBehavior {
329
+ const policyTask = resolveTaskTextForFileUpdatePolicy(task, originalTask);
330
+ return behavior.progress && taskDisallowsFileUpdates(policyTask) ? { ...behavior, progress: false } : behavior;
331
+ }
332
+
333
+ // =============================================================================
334
+ // Chain Instruction Injection
335
+ // =============================================================================
336
+
337
+ /**
338
+ * Expand a leading `~`/`~/` to the user's home directory. Other forms (relative,
339
+ * absolute, `~user/`) pass through unchanged.
340
+ */
341
+ export function expandHomePath(filePath: string): string {
342
+ if (filePath === "~") return os.homedir();
343
+ if (filePath.startsWith("~/")) return path.join(os.homedir(), filePath.slice(2));
344
+ return filePath;
345
+ }
346
+
347
+ /**
348
+ * Resolve a file path: `~`/`~/` expand to home first, then absolute paths pass
349
+ * through and relative paths get chainDir prepended.
350
+ */
351
+ export function resolveChainPath(filePath: string, chainDir: string): string {
352
+ const expanded = expandHomePath(filePath);
353
+ return path.isAbsolute(expanded) ? expanded : path.join(chainDir, expanded);
354
+ }
355
+
356
+ /**
357
+ * Build chain instructions from resolved behavior.
358
+ * These are appended to the task to tell the agent what to read/write.
359
+ */
360
+ export function writeInitialProgressFile(progressDir: string): void {
361
+ fs.mkdirSync(progressDir, { recursive: true });
362
+ fs.writeFileSync(path.join(progressDir, "progress.md"), INITIAL_PROGRESS_CONTENT);
363
+ }
364
+
365
+ export function buildChainInstructions(
366
+ behavior: ResolvedStepBehavior,
367
+ chainDir: string,
368
+ isFirstProgressAgent: boolean,
369
+ previousSummary?: string,
370
+ ): { prefix: string; suffix: string } {
371
+ const prefixParts: string[] = [];
372
+ const suffixParts: string[] = [];
373
+
374
+ // READS - prepend to override any hardcoded filenames in task text
375
+ if (behavior.reads && behavior.reads.length > 0) {
376
+ const files = behavior.reads.map((f) => resolveChainPath(f, chainDir));
377
+ prefixParts.push(`[Read from: ${files.join(", ")}]`);
378
+ }
379
+
380
+ // OUTPUT - prepend so agent knows where to write
381
+ if (behavior.output) {
382
+ const outputPath = resolveChainPath(behavior.output, chainDir);
383
+ prefixParts.push(`[Write to: ${outputPath}]`);
384
+ }
385
+
386
+ // Progress instructions in suffix (less critical)
387
+ if (behavior.progress) {
388
+ const progressPath = path.join(chainDir, "progress.md");
389
+ if (isFirstProgressAgent) {
390
+ suffixParts.push(`Create and maintain progress at: ${progressPath}`);
391
+ } else {
392
+ suffixParts.push(`Update progress at: ${progressPath}`);
393
+ }
394
+ }
395
+
396
+ // Include previous step's summary in suffix if available
397
+ if (previousSummary && previousSummary.trim()) {
398
+ suffixParts.push(`Previous step output:\n${previousSummary.trim()}`);
399
+ }
400
+
401
+ const prefix = prefixParts.length > 0
402
+ ? prefixParts.join("\n") + "\n\n"
403
+ : "";
404
+
405
+ const suffix = suffixParts.length > 0
406
+ ? "\n\n---\n" + suffixParts.join("\n")
407
+ : "";
408
+
409
+ return { prefix, suffix };
410
+ }
411
+
412
+ // =============================================================================
413
+ // Parallel Step Support
414
+ // =============================================================================
415
+
416
+ /**
417
+ * Resolve behaviors for all tasks in a parallel step.
418
+ * Creates namespaced output paths to avoid collisions.
419
+ */
420
+ export function resolveParallelBehaviors(
421
+ tasks: ParallelTaskItem[],
422
+ agentConfigs: AgentConfig[],
423
+ stepIndex: number,
424
+ chainSkills?: string[],
425
+ ): ResolvedStepBehavior[] {
426
+ return tasks.map((task, taskIndex) => {
427
+ const config = agentConfigs.find((a) => a.name === task.agent);
428
+ if (!config) {
429
+ throw new Error(`Unknown agent: ${task.agent}`);
430
+ }
431
+
432
+ // Build subdirectory path for this parallel task
433
+ const subdir = path.join(`parallel-${stepIndex}`, `${taskIndex}-${task.agent}`);
434
+
435
+ // Output: task override > agent default (namespaced) > false
436
+ // Absolute paths pass through unchanged; relative paths get namespaced under subdir
437
+ let output: string | false = false;
438
+ const taskOutput = normalizeOutputOverride(task.output);
439
+ const configOutput = normalizeOutputOverride(config.output);
440
+ if (taskOutput !== undefined) {
441
+ if (taskOutput === false) {
442
+ output = false;
443
+ } else if (path.isAbsolute(taskOutput)) {
444
+ output = taskOutput; // Absolute path: use as-is
445
+ } else {
446
+ output = path.join(subdir, taskOutput); // Relative: namespace under subdir
447
+ }
448
+ } else if (configOutput) {
449
+ // Agent defaults are always relative, so namespace them
450
+ output = path.join(subdir, configOutput);
451
+ }
452
+
453
+ // Reads: task override > agent default > false
454
+ const reads =
455
+ task.reads !== undefined ? task.reads : config.defaultReads ?? false;
456
+
457
+ // Progress: task override > agent default > false
458
+ const progress =
459
+ task.progress !== undefined
460
+ ? task.progress
461
+ : config.defaultProgress ?? false;
462
+
463
+ const taskSkillInput = normalizeSkillInput(task.skill);
464
+ let skills: string[] | false;
465
+ if (taskSkillInput === false) {
466
+ skills = false;
467
+ } else if (taskSkillInput !== undefined) {
468
+ skills = [...taskSkillInput];
469
+ if (chainSkills && chainSkills.length > 0) {
470
+ skills = [...new Set([...skills, ...chainSkills])];
471
+ }
472
+ } else {
473
+ skills = config.skills ? [...config.skills] : [];
474
+ if (chainSkills && chainSkills.length > 0) {
475
+ skills = [...new Set([...skills, ...chainSkills])];
476
+ }
477
+ }
478
+
479
+ const outputMode = task.outputMode ?? "inline";
480
+ const model = task.model ?? config.model;
481
+ return { output, outputMode, reads, progress, skills, model };
482
+ });
483
+ }
484
+
485
+ /**
486
+ * Create subdirectories for parallel step outputs
487
+ */
488
+ export function createParallelDirs(
489
+ chainDir: string,
490
+ stepIndex: number,
491
+ taskCount: number,
492
+ agentNames: string[],
493
+ ): void {
494
+ for (let i = 0; i < taskCount; i++) {
495
+ const subdir = path.join(chainDir, `parallel-${stepIndex}`, `${i}-${agentNames[i]}`);
496
+ fs.mkdirSync(subdir, { recursive: true });
497
+ }
498
+ }
499
+
500
+ export type { ParallelTaskResult } from "../runs/shared/parallel-utils.ts";
501
+ export { aggregateParallelOutputs } from "../runs/shared/parallel-utils.ts";
@@ -0,0 +1,55 @@
1
+ import type { ActivityState, AsyncJobStep } from "./types.ts";
2
+
3
+ type StepStatusLike = Pick<AsyncJobStep, "status">;
4
+
5
+ function formatActivityAge(ms: number): string {
6
+ if (ms < 1000) return "now";
7
+ if (ms < 60000) return `${Math.floor(ms / 1000)}s`;
8
+ return `${Math.floor(ms / 60000)}m`;
9
+ }
10
+
11
+ export function formatActivityLabel(lastActivityAt: number | undefined, activityState?: ActivityState, now = Date.now()): string | undefined {
12
+ if (lastActivityAt === undefined) {
13
+ if (activityState === "needs_attention") return "needs attention";
14
+ if (activityState === "active_long_running") return "active but long-running";
15
+ return undefined;
16
+ }
17
+ const age = formatActivityAge(Math.max(0, now - lastActivityAt));
18
+ if (activityState === "needs_attention") return `no activity for ${age}`;
19
+ if (activityState === "active_long_running") {
20
+ const activityAge = age === "now" ? "now" : `${age} ago`;
21
+ return `active but long-running · last activity ${activityAge}`;
22
+ }
23
+ return age === "now" ? "active now" : `active ${age} ago`;
24
+ }
25
+
26
+ function isCompletedStepStatus(status: AsyncJobStep["status"]): boolean {
27
+ return status === "complete" || status === "completed";
28
+ }
29
+
30
+ export function aggregateStepStatus(steps: StepStatusLike[]): AsyncJobStep["status"] {
31
+ if (steps.some((step) => step.status === "running")) return "running";
32
+ if (steps.some((step) => step.status === "failed")) return "failed";
33
+ if (steps.some((step) => step.status === "stopped")) return "stopped";
34
+ if (steps.some((step) => step.status === "paused")) return "paused";
35
+ if (steps.length > 0 && steps.every((step) => isCompletedStepStatus(step.status))) return "complete";
36
+ return "pending";
37
+ }
38
+
39
+ export function formatAgentRunningLabel(count: number): string {
40
+ return count === 1 ? "1 agent running" : `${count} agents running`;
41
+ }
42
+
43
+ export function formatParallelOutcome(steps: StepStatusLike[], total: number, options: { showRunning?: boolean } = {}): string {
44
+ const running = steps.filter((step) => step.status === "running").length;
45
+ const done = steps.filter((step) => isCompletedStepStatus(step.status)).length;
46
+ const failed = steps.filter((step) => step.status === "failed").length;
47
+ const stopped = steps.filter((step) => step.status === "stopped").length;
48
+ const paused = steps.filter((step) => step.status === "paused").length;
49
+ const parts = [`${done}/${total} done`];
50
+ if (options.showRunning !== false && running > 0) parts.unshift(formatAgentRunningLabel(running));
51
+ if (failed > 0) parts.push(`${failed} failed`);
52
+ if (stopped > 0) parts.push(`${stopped} stopped`);
53
+ if (paused > 0) parts.push(`${paused} paused`);
54
+ return parts.join(" · ");
55
+ }