@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,692 @@
1
+ /**
2
+ * Cross-OS control channel for async subagent runs.
3
+ *
4
+ * Background runs are detached OS processes. The original control path delivered
5
+ * an interrupt with `process.kill(pid, SIGUSR2|SIGBREAK)`, but Windows cannot
6
+ * deliver those signals cross-process via `process.kill` and throws `ENOSYS`,
7
+ * which left async runs uninterruptible (no stop, no live steer) on Windows.
8
+ *
9
+ * This module adds a portable, file-based control inbox inside the run directory.
10
+ * The parent drops an interrupt request file; the runner watches the inbox and
11
+ * routes the request into its existing graceful `interruptRunner()` (pause +
12
+ * resumable), identically on every platform. The OS signal is kept only as an
13
+ * opportunistic fast-path; its failure is non-fatal because the file inbox is
14
+ * authoritative.
15
+ */
16
+
17
+ import { randomUUID } from "node:crypto";
18
+ import * as fs from "node:fs";
19
+ import * as path from "node:path";
20
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
21
+ import { POLL_INTERVAL_MS } from "../../shared/types.ts";
22
+ import { resolveWatchPath } from "../../shared/utils.ts";
23
+
24
+ /**
25
+ * Opportunistic fast-path interrupt signal. On Unix `SIGUSR2` is trapped by the
26
+ * runner; on Windows `process.kill(pid, "SIGBREAK")` is not deliverable
27
+ * cross-process and throws `ENOSYS`, so the file inbox below is the real channel.
28
+ */
29
+ export const INTERRUPT_SIGNAL: NodeJS.Signals = process.platform === "win32" ? "SIGBREAK" : "SIGUSR2";
30
+
31
+ export type ControlChannelFs = Pick<typeof fs, "mkdirSync" | "existsSync" | "rmSync" | "watch" | "readdirSync" | "readFileSync" | "realpathSync">;
32
+ export type ControlChannelTimers = { setInterval: typeof setInterval; clearInterval: typeof clearInterval };
33
+ type KillFn = (pid: number, signal?: NodeJS.Signals | 0) => unknown;
34
+
35
+ export interface InterruptRequest {
36
+ type: "interrupt";
37
+ ts?: number;
38
+ source?: string;
39
+ reason?: string;
40
+ }
41
+
42
+ export interface TimeoutRequest {
43
+ type: "timeout";
44
+ ts?: number;
45
+ source?: string;
46
+ reason?: string;
47
+ }
48
+
49
+ export interface StopRequest {
50
+ type: "stop";
51
+ ts?: number;
52
+ source?: string;
53
+ reason?: string;
54
+ }
55
+
56
+ export interface CheckpointDecisionRequest {
57
+ type: "approve-checkpoint" | "reject-checkpoint";
58
+ ts?: number;
59
+ source?: string;
60
+ reason?: string;
61
+ }
62
+
63
+ export type SteerDeliveryMode = "steer" | "follow_up" | "auto";
64
+ export type SteerDeliveryStatus = "delivered" | "queued";
65
+
66
+ export interface SteerRequest {
67
+ type: "steer";
68
+ id: string;
69
+ ts: number;
70
+ message: string;
71
+ mode?: SteerDeliveryMode;
72
+ targetIndex?: number;
73
+ targetIndexes?: number[];
74
+ source?: string;
75
+ }
76
+
77
+ export interface SteerCapability {
78
+ type: "steer-capability";
79
+ protocolVersion: 1;
80
+ index: number;
81
+ pid: number;
82
+ readyAt: number;
83
+ supported: boolean;
84
+ }
85
+
86
+ export interface SteerAck {
87
+ type: "steer-ack";
88
+ protocolVersion: 1;
89
+ requestId: string;
90
+ index: number;
91
+ ts: number;
92
+ state: "delivered" | "queued" | "failed";
93
+ deliveryStatus?: SteerDeliveryStatus;
94
+ message: string;
95
+ }
96
+
97
+ const STEER_REQUESTS_DIR = "steer-requests";
98
+ const REVIVAL_BRIEFS_DIR = "revival-briefs";
99
+ export const MAX_STEER_QUEUE_SIZE = 20;
100
+ const STEER_TARGETS_DIR = "steer-targets";
101
+ const STEER_CAPABILITIES_DIR = "steer-capabilities";
102
+ const STEER_ACKS_DIR = "steer-acks";
103
+ const STEER_INBOX_CLOSED_FILE = "steer-inbox-closed.json";
104
+ const MAX_STEER_MESSAGE_BYTES = 128 * 1024;
105
+ const MAX_STEER_REQUEST_ID_LENGTH = 256;
106
+
107
+ /** Control inbox directory inside an async run dir. */
108
+ export function controlInboxDir(asyncDir: string): string {
109
+ return path.join(asyncDir, "control");
110
+ }
111
+
112
+ /** Path of the portable interrupt request file. */
113
+ export function interruptRequestPath(asyncDir: string): string {
114
+ return path.join(controlInboxDir(asyncDir), "interrupt.json");
115
+ }
116
+
117
+ /** Path of the portable timeout request file. */
118
+ export function timeoutRequestPath(asyncDir: string): string {
119
+ return path.join(controlInboxDir(asyncDir), "timeout.json");
120
+ }
121
+
122
+ /** Path of the portable manual stop request file. */
123
+ export function stopRequestPath(asyncDir: string): string {
124
+ return path.join(controlInboxDir(asyncDir), "stop.json");
125
+ }
126
+
127
+ export function approveCheckpointRequestPath(asyncDir: string): string {
128
+ return path.join(controlInboxDir(asyncDir), "approve-checkpoint.json");
129
+ }
130
+
131
+ export function rejectCheckpointRequestPath(asyncDir: string): string {
132
+ return path.join(controlInboxDir(asyncDir), "reject-checkpoint.json");
133
+ }
134
+
135
+ /** Directory of parent-to-runner steering requests. */
136
+ export function steerRequestsDir(asyncDir: string): string {
137
+ return path.join(controlInboxDir(asyncDir), STEER_REQUESTS_DIR);
138
+ }
139
+
140
+ export function steerInboxClosedPath(asyncDir: string): string {
141
+ return path.join(controlInboxDir(asyncDir), STEER_INBOX_CLOSED_FILE);
142
+ }
143
+
144
+ export function closeSteerInbox(asyncDir: string, state: string): void {
145
+ writeAtomicJson(steerInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now(), state });
146
+ }
147
+
148
+ /** Per-child inbox consumed by the child prompt runtime inside the Pi process. */
149
+ export function stepSteerInboxDir(asyncDir: string, index: number): string {
150
+ assertChildIndex(index);
151
+ return path.join(controlInboxDir(asyncDir), STEER_TARGETS_DIR, String(index));
152
+ }
153
+
154
+ export function steerCapabilitiesDir(asyncDir: string): string {
155
+ return path.join(controlInboxDir(asyncDir), STEER_CAPABILITIES_DIR);
156
+ }
157
+
158
+ export function steerCapabilityPath(asyncDir: string, index: number): string {
159
+ assertChildIndex(index);
160
+ return path.join(steerCapabilitiesDir(asyncDir), `${index}.json`);
161
+ }
162
+
163
+ export function steerAcksDir(asyncDir: string, index: number): string {
164
+ assertChildIndex(index);
165
+ return path.join(controlInboxDir(asyncDir), STEER_ACKS_DIR, String(index));
166
+ }
167
+
168
+ function steerAckFileName(requestId: string): string {
169
+ return `${Buffer.from(requestId).toString("base64url")}.json`;
170
+ }
171
+
172
+ export function steerAckPathFromDir(dir: string, requestId: string): string {
173
+ if (!/^[^\s]+$/.test(requestId) || requestId.length > 256) throw new Error("steer acknowledgment requestId is invalid.");
174
+ return path.join(dir, steerAckFileName(requestId));
175
+ }
176
+
177
+ function assertChildIndex(index: number): void {
178
+ if (!Number.isInteger(index) || index < 0 || index > 1_000_000) throw new Error("steer child index must be a non-negative integer.");
179
+ }
180
+
181
+ function steerRequestFileName(request: SteerRequest): string {
182
+ return `${String(request.ts).padStart(13, "0")}-${Buffer.from(request.id).toString("base64url")}.json`;
183
+ }
184
+
185
+ function validSteerRequest(request: Partial<SteerRequest>): request is SteerRequest {
186
+ return request.type === "steer"
187
+ && typeof request.id === "string"
188
+ && /^[^\s]+$/.test(request.id)
189
+ && request.id.length <= MAX_STEER_REQUEST_ID_LENGTH
190
+ && typeof request.ts === "number"
191
+ && Number.isFinite(request.ts)
192
+ && request.ts > 0
193
+ && typeof request.message === "string"
194
+ && Boolean(request.message.trim())
195
+ && Buffer.byteLength(request.message, "utf8") <= MAX_STEER_MESSAGE_BYTES
196
+ && (request.mode === undefined || request.mode === "steer" || request.mode === "follow_up" || request.mode === "auto")
197
+ && (request.targetIndex === undefined || (Number.isInteger(request.targetIndex) && request.targetIndex >= 0 && request.targetIndex <= 1_000_000))
198
+ && (request.targetIndexes === undefined || (
199
+ request.targetIndex === undefined
200
+ && Array.isArray(request.targetIndexes)
201
+ && request.targetIndexes.length > 0
202
+ && request.targetIndexes.length <= 1_000
203
+ && request.targetIndexes.every((index) => Number.isInteger(index) && index >= 0 && index <= 1_000_000)
204
+ && new Set(request.targetIndexes).size === request.targetIndexes.length
205
+ ))
206
+ && (request.source === undefined || (typeof request.source === "string" && Boolean(request.source.trim()) && request.source.length <= 256));
207
+ }
208
+
209
+ export function writeSteerRequestToDir(dir: string, request: SteerRequest): string {
210
+ if (!validSteerRequest(request)) throw new Error("steer request is malformed or exceeds transport limits.");
211
+ const requestPath = path.join(dir, steerRequestFileName(request));
212
+ writeAtomicJson(requestPath, request);
213
+ return requestPath;
214
+ }
215
+
216
+ export function writeSteerCapabilityAt(filePath: string, capability: Omit<SteerCapability, "type" | "protocolVersion">): string {
217
+ assertChildIndex(capability.index);
218
+ if (!Number.isInteger(capability.pid) || capability.pid <= 0) throw new Error("steer capability pid must be a positive integer.");
219
+ if (!Number.isFinite(capability.readyAt) || capability.readyAt <= 0) throw new Error("steer capability readyAt must be a finite timestamp.");
220
+ const record: SteerCapability = { type: "steer-capability", protocolVersion: 1, ...capability };
221
+ writeAtomicJson(filePath, record);
222
+ return filePath;
223
+ }
224
+
225
+ export function writeSteerCapability(asyncDir: string, capability: Omit<SteerCapability, "type" | "protocolVersion">): string {
226
+ return writeSteerCapabilityAt(steerCapabilityPath(asyncDir, capability.index), capability);
227
+ }
228
+
229
+ function steerAckWritePath(filePath: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
230
+ const parsed = path.parse(filePath);
231
+ const stateOrder = ack.state === "queued" ? "0" : ack.state === "delivered" ? "1" : "2";
232
+ const timestamp = String(Math.trunc(ack.ts)).padStart(13, "0");
233
+ for (let suffix = 0; suffix < 1_000; suffix += 1) {
234
+ const candidate = path.join(parsed.dir, `${parsed.name}-${timestamp}-${stateOrder}-${ack.state}${suffix === 0 ? "" : `-${suffix}`}${parsed.ext}`);
235
+ if (!fs.existsSync(candidate)) return candidate;
236
+ }
237
+ throw new Error("steer acknowledgment queue is full.");
238
+ }
239
+
240
+ export function writeSteerAckAt(filePath: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
241
+ assertChildIndex(ack.index);
242
+ if (!/^[^\s]+$/.test(ack.requestId) || ack.requestId.length > 256) throw new Error("steer acknowledgment requestId is invalid.");
243
+ if (!Number.isFinite(ack.ts) || ack.ts <= 0) throw new Error("steer acknowledgment ts must be a finite timestamp.");
244
+ if (!ack.message.trim() || ack.message.length > 1000) throw new Error("steer acknowledgment message is invalid.");
245
+ const record: SteerAck = { type: "steer-ack", protocolVersion: 1, ...ack, message: ack.message.trim() };
246
+ const ackPath = steerAckWritePath(filePath, ack);
247
+ writeAtomicJson(ackPath, record);
248
+ return ackPath;
249
+ }
250
+
251
+ export function writeSteerAck(asyncDir: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
252
+ return writeSteerAckAt(path.join(steerAcksDir(asyncDir, ack.index), steerAckFileName(ack.requestId)), ack);
253
+ }
254
+
255
+ /**
256
+ * Parent side: drop a portable interrupt request the runner's inbox watcher will
257
+ * pick up regardless of OS. Written atomically (temp + rename), dir auto-created.
258
+ */
259
+ export function requestAsyncInterrupt(
260
+ asyncDir: string,
261
+ payload: Omit<InterruptRequest, "type"> = {},
262
+ deps: { now?: () => number } = {},
263
+ ): string {
264
+ const requestPath = interruptRequestPath(asyncDir);
265
+ const request: InterruptRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type: "interrupt" };
266
+ writeAtomicJson(requestPath, request);
267
+ return requestPath;
268
+ }
269
+
270
+ export function requestAsyncTimeout(
271
+ asyncDir: string,
272
+ payload: Omit<TimeoutRequest, "type"> = {},
273
+ deps: { now?: () => number } = {},
274
+ ): string {
275
+ const requestPath = timeoutRequestPath(asyncDir);
276
+ const request: TimeoutRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type: "timeout" };
277
+ writeAtomicJson(requestPath, request);
278
+ return requestPath;
279
+ }
280
+
281
+ export function requestAsyncStop(
282
+ asyncDir: string,
283
+ payload: Omit<StopRequest, "type"> = {},
284
+ deps: { now?: () => number } = {},
285
+ ): string {
286
+ const requestPath = stopRequestPath(asyncDir);
287
+ const request: StopRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type: "stop" };
288
+ writeAtomicJson(requestPath, request);
289
+ return requestPath;
290
+ }
291
+
292
+ export function requestAsyncCheckpointDecision(
293
+ asyncDir: string,
294
+ type: CheckpointDecisionRequest["type"],
295
+ payload: Omit<CheckpointDecisionRequest, "type"> = {},
296
+ deps: { now?: () => number } = {},
297
+ ): string {
298
+ const requestPath = type === "approve-checkpoint" ? approveCheckpointRequestPath(asyncDir) : rejectCheckpointRequestPath(asyncDir);
299
+ const request: CheckpointDecisionRequest = { ...payload, ts: payload.ts ?? deps.now?.() ?? Date.now(), type };
300
+ writeAtomicJson(requestPath, request);
301
+ return requestPath;
302
+ }
303
+
304
+ export function requestAsyncSteer(
305
+ asyncDir: string,
306
+ payload: { message: string; mode?: SteerDeliveryMode; targetIndex?: number; targetIndexes?: number[]; source?: string; id?: string; ts?: number },
307
+ deps: { now?: () => number; randomId?: () => string } = {},
308
+ ): string {
309
+ const message = payload.message.trim();
310
+ if (!message) throw new Error("steer message must not be empty.");
311
+ if (Buffer.byteLength(message, "utf8") > MAX_STEER_MESSAGE_BYTES) throw new Error(`steer message exceeds ${MAX_STEER_MESSAGE_BYTES} UTF-8 bytes.`);
312
+ if (payload.targetIndex !== undefined && (!Number.isInteger(payload.targetIndex) || payload.targetIndex < 0 || payload.targetIndex > 1_000_000)) {
313
+ throw new Error("steer targetIndex must be an integer between 0 and 1000000.");
314
+ }
315
+ if (payload.targetIndexes !== undefined && (
316
+ !Array.isArray(payload.targetIndexes)
317
+ || payload.targetIndex !== undefined
318
+ || payload.targetIndexes.length === 0
319
+ || payload.targetIndexes.length > 1_000
320
+ || payload.targetIndexes.some((index) => !Number.isInteger(index) || index < 0 || index > 1_000_000)
321
+ || new Set(payload.targetIndexes).size !== payload.targetIndexes.length
322
+ )) {
323
+ throw new Error("steer targetIndexes must contain 1-1000 unique non-negative integers and cannot be combined with targetIndex.");
324
+ }
325
+ const closedPath = steerInboxClosedPath(asyncDir);
326
+ if (fs.existsSync(closedPath)) throw new Error("Async run no longer accepts steering requests.");
327
+ const request: SteerRequest = {
328
+ type: "steer",
329
+ id: payload.id ?? deps.randomId?.() ?? randomUUID(),
330
+ ts: payload.ts ?? deps.now?.() ?? Date.now(),
331
+ message,
332
+ ...(payload.mode && payload.mode !== "steer" ? { mode: payload.mode } : {}),
333
+ ...(payload.targetIndex !== undefined ? { targetIndex: payload.targetIndex } : {}),
334
+ ...(payload.targetIndexes !== undefined ? { targetIndexes: [...payload.targetIndexes] } : {}),
335
+ ...(payload.source ? { source: payload.source } : {}),
336
+ };
337
+ const requestPath = writeSteerRequestToDir(steerRequestsDir(asyncDir), request);
338
+ if (fs.existsSync(closedPath)) {
339
+ fs.rmSync(requestPath, { force: true });
340
+ throw new Error("Async run stopped accepting steering before the request was committed.");
341
+ }
342
+ return requestPath;
343
+ }
344
+
345
+ export function enqueueStepSteer(asyncDir: string, index: number, request: SteerRequest): string {
346
+ assertChildIndex(index);
347
+ const { targetIndexes: _targetIndexes, ...singleTargetRequest } = request;
348
+ return writeSteerRequestToDir(stepSteerInboxDir(asyncDir, index), { ...singleTargetRequest, targetIndex: index, type: "steer" });
349
+ }
350
+
351
+ function parseSteerCapability(raw: unknown): SteerCapability | undefined {
352
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
353
+ const input = raw as Partial<SteerCapability>;
354
+ if (input.type !== "steer-capability" || input.protocolVersion !== 1) return undefined;
355
+ const { index, pid, readyAt, supported } = input;
356
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index > 1_000_000) return undefined;
357
+ if (typeof pid !== "number" || typeof readyAt !== "number" || !Number.isInteger(pid) || pid <= 0 || !Number.isFinite(readyAt) || readyAt <= 0 || typeof supported !== "boolean") return undefined;
358
+ return { type: "steer-capability", protocolVersion: 1, index, pid, readyAt, supported };
359
+ }
360
+
361
+ function parseSteerAck(raw: unknown): SteerAck | undefined {
362
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
363
+ const input = raw as Partial<SteerAck>;
364
+ if (input.type !== "steer-ack" || input.protocolVersion !== 1 || typeof input.requestId !== "string" || !/^[^\s]+$/.test(input.requestId) || input.requestId.length > 256) return undefined;
365
+ const { index, ts, state, message } = input;
366
+ if (typeof index !== "number" || typeof ts !== "number" || !Number.isInteger(index) || index < 0 || index > 1_000_000 || !Number.isFinite(ts) || ts <= 0) return undefined;
367
+ if (state !== "delivered" && state !== "queued" && state !== "failed") return undefined;
368
+ if (input.deliveryStatus !== undefined && input.deliveryStatus !== "delivered" && input.deliveryStatus !== "queued") return undefined;
369
+ if (typeof message !== "string" || !message.trim() || message.length > 1000) return undefined;
370
+ return { type: "steer-ack", protocolVersion: 1, requestId: input.requestId, index, ts, state, ...(input.deliveryStatus ? { deliveryStatus: input.deliveryStatus } : {}), message: message.trim() };
371
+ }
372
+
373
+ export function readSteerCapability(asyncDir: string, index: number): SteerCapability | undefined {
374
+ try {
375
+ return parseSteerCapability(JSON.parse(fs.readFileSync(steerCapabilityPath(asyncDir, index), "utf-8")));
376
+ } catch {
377
+ return undefined;
378
+ }
379
+ }
380
+
381
+ export function consumeSteerCapabilities(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync"> = fs): SteerCapability[] {
382
+ const dir = steerCapabilitiesDir(asyncDir);
383
+ if (!fsImpl.existsSync(dir)) return [];
384
+ const capabilities: SteerCapability[] = [];
385
+ for (const entry of fsImpl.readdirSync(dir).filter((name) => /^\d+\.json$/.test(name)).sort()) {
386
+ try {
387
+ const capability = parseSteerCapability(JSON.parse(fsImpl.readFileSync(path.join(dir, entry), "utf-8")));
388
+ if (capability) capabilities.push(capability);
389
+ } catch {
390
+ // A partially written or malformed capability is ignored until a valid one arrives.
391
+ }
392
+ }
393
+ return capabilities;
394
+ }
395
+
396
+ export function consumeSteerAcks(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync" | "rmSync"> = fs): SteerAck[] {
397
+ const root = path.join(controlInboxDir(asyncDir), STEER_ACKS_DIR);
398
+ if (!fsImpl.existsSync(root)) return [];
399
+ const acks: SteerAck[] = [];
400
+ let indexNames: string[];
401
+ try { indexNames = fsImpl.readdirSync(root).filter((name) => /^\d+$/.test(name)); } catch { return []; }
402
+ for (const indexName of indexNames) {
403
+ const dir = path.join(root, indexName);
404
+ let entries: string[];
405
+ try { entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort(); } catch { continue; }
406
+ for (const entry of entries) {
407
+ const target = path.join(dir, entry);
408
+ let ack: SteerAck | undefined;
409
+ try { ack = parseSteerAck(JSON.parse(fsImpl.readFileSync(target, "utf-8"))); } catch { ack = undefined; }
410
+ try { fsImpl.rmSync(target, { force: true }); } catch { continue; }
411
+ if (ack) acks.push(ack);
412
+ }
413
+ }
414
+ return acks;
415
+ }
416
+
417
+ function parseSteerRequest(raw: unknown): SteerRequest | undefined {
418
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
419
+ const input = raw as Partial<SteerRequest>;
420
+ if (!validSteerRequest(input)) return undefined;
421
+ return {
422
+ type: "steer",
423
+ id: input.id.trim(),
424
+ ts: input.ts,
425
+ message: input.message.trim(),
426
+ ...(input.mode ? { mode: input.mode } : {}),
427
+ ...(input.targetIndex !== undefined ? { targetIndex: input.targetIndex } : {}),
428
+ ...(input.targetIndexes !== undefined ? { targetIndexes: [...input.targetIndexes] } : {}),
429
+ ...(typeof input.source === "string" && input.source.trim() ? { source: input.source } : {}),
430
+ };
431
+ }
432
+
433
+ export function consumeSteerRequestsFromDir(dir: string, fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs): SteerRequest[] {
434
+ if (!fsImpl.existsSync(dir)) return [];
435
+ let entries: string[];
436
+ try {
437
+ entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort();
438
+ } catch {
439
+ // Leave requests in place so the periodic poll can retry the scan.
440
+ return [];
441
+ }
442
+ const requests: SteerRequest[] = [];
443
+ for (const entry of entries) {
444
+ const requestPath = path.join(dir, entry);
445
+ let parsed: SteerRequest | undefined;
446
+ try {
447
+ parsed = parseSteerRequest(JSON.parse(fsImpl.readFileSync(requestPath, "utf-8")));
448
+ } catch {
449
+ parsed = undefined;
450
+ }
451
+ try {
452
+ fsImpl.rmSync(requestPath, { recursive: true });
453
+ } catch {
454
+ // Already removed by a concurrent check — do not execute it twice.
455
+ continue;
456
+ }
457
+ if (parsed) requests.push(parsed);
458
+ }
459
+ return requests.sort((left, right) => left.ts - right.ts || left.id.localeCompare(right.id));
460
+ }
461
+
462
+ export function consumeSteerRequests(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "rmSync" | "readdirSync" | "readFileSync"> = fs): SteerRequest[] {
463
+ return consumeSteerRequestsFromDir(steerRequestsDir(asyncDir), fsImpl);
464
+ }
465
+
466
+ export function queueRevivalBrief(asyncDir: string, request: SteerRequest): string {
467
+ const dir = path.join(controlInboxDir(asyncDir), REVIVAL_BRIEFS_DIR);
468
+ const queued = fs.existsSync(dir) ? fs.readdirSync(dir).filter((entry) => entry.endsWith(".json")).length : 0;
469
+ if (queued >= MAX_STEER_QUEUE_SIZE) throw new Error(`Follow-up queue is full (${MAX_STEER_QUEUE_SIZE} messages).`);
470
+ return writeSteerRequestToDir(dir, { ...request, mode: "follow_up" });
471
+ }
472
+
473
+ export function readRevivalBriefs(asyncDir: string): Array<{ request: SteerRequest; path: string }> {
474
+ const dir = path.join(controlInboxDir(asyncDir), REVIVAL_BRIEFS_DIR);
475
+ if (!fs.existsSync(dir)) return [];
476
+ return fs.readdirSync(dir).filter((entry) => entry.endsWith(".json")).sort().flatMap((entry) => {
477
+ const filePath = path.join(dir, entry);
478
+ try {
479
+ const request = parseSteerRequest(JSON.parse(fs.readFileSync(filePath, "utf-8")));
480
+ return request ? [{ request, path: filePath }] : [];
481
+ } catch {
482
+ return [];
483
+ }
484
+ });
485
+ }
486
+
487
+ /**
488
+ * Runner side: consume a pending interrupt request. Idempotent — removes the file
489
+ * so each distinct request fires exactly once. Returns whether one was pending.
490
+ */
491
+ export function consumeInterruptRequest(
492
+ asyncDir: string,
493
+ fsImpl: Pick<typeof fs, "existsSync" | "rmSync"> = fs,
494
+ ): boolean {
495
+ const requestPath = interruptRequestPath(asyncDir);
496
+ if (!fsImpl.existsSync(requestPath)) return false;
497
+ try {
498
+ fsImpl.rmSync(requestPath, { force: true, recursive: true });
499
+ } catch {
500
+ // Already removed by a concurrent check — still counts as consumed.
501
+ }
502
+ return true;
503
+ }
504
+
505
+ export function consumeTimeoutRequest(
506
+ asyncDir: string,
507
+ fsImpl: Pick<typeof fs, "existsSync" | "rmSync"> = fs,
508
+ ): boolean {
509
+ const requestPath = timeoutRequestPath(asyncDir);
510
+ if (!fsImpl.existsSync(requestPath)) return false;
511
+ try {
512
+ fsImpl.rmSync(requestPath, { force: true, recursive: true });
513
+ } catch {
514
+ // Already removed by a concurrent check — still counts as consumed.
515
+ }
516
+ return true;
517
+ }
518
+
519
+ export function consumeStopRequest(
520
+ asyncDir: string,
521
+ fsImpl: Pick<typeof fs, "existsSync" | "rmSync"> = fs,
522
+ ): boolean {
523
+ const requestPath = stopRequestPath(asyncDir);
524
+ if (!fsImpl.existsSync(requestPath)) return false;
525
+ try {
526
+ fsImpl.rmSync(requestPath, { force: true, recursive: true });
527
+ } catch {
528
+ // Already removed by a concurrent check — still counts as consumed.
529
+ }
530
+ return true;
531
+ }
532
+
533
+ export function consumeCheckpointDecisionRequest(
534
+ asyncDir: string,
535
+ fsImpl: Pick<typeof fs, "existsSync" | "rmSync"> = fs,
536
+ ): "approved" | "rejected" | undefined {
537
+ if (fsImpl.existsSync(rejectCheckpointRequestPath(asyncDir))) {
538
+ try { fsImpl.rmSync(rejectCheckpointRequestPath(asyncDir), { force: true, recursive: true }); } catch {}
539
+ return "rejected";
540
+ }
541
+ if (fsImpl.existsSync(approveCheckpointRequestPath(asyncDir))) {
542
+ try { fsImpl.rmSync(approveCheckpointRequestPath(asyncDir), { force: true, recursive: true }); } catch {}
543
+ return "approved";
544
+ }
545
+ return undefined;
546
+ }
547
+
548
+ /**
549
+ * Parent side: portable interrupt = authoritative file request + best-effort OS
550
+ * signal. The signal is only a latency optimization on Unix; ENOSYS on Windows
551
+ * is swallowed because the file inbox is authoritative there. Other signal
552
+ * failures are surfaced because they usually mean the runner is not alive to
553
+ * consume the request.
554
+ */
555
+ export function deliverInterruptRequest(input: {
556
+ asyncDir: string;
557
+ pid?: number;
558
+ kill?: KillFn;
559
+ signal?: NodeJS.Signals;
560
+ now?: () => number;
561
+ source?: string;
562
+ }): void {
563
+ const requestPath = requestAsyncInterrupt(input.asyncDir, input.source ? { source: input.source } : {}, { now: input.now });
564
+ if (typeof input.pid === "number" && input.pid > 0) {
565
+ try {
566
+ (input.kill ?? process.kill)(input.pid, input.signal ?? INTERRUPT_SIGNAL);
567
+ } catch (error) {
568
+ if ((error as NodeJS.ErrnoException | undefined)?.code === "ENOSYS") {
569
+ // File inbox is authoritative when custom cross-process signals are unavailable.
570
+ return;
571
+ }
572
+ try {
573
+ fs.rmSync(requestPath, { force: true });
574
+ } catch {
575
+ // Best effort cleanup; the caller still gets the signal failure.
576
+ }
577
+ throw error;
578
+ }
579
+ }
580
+ }
581
+
582
+ export function deliverTimeoutRequest(input: {
583
+ asyncDir: string;
584
+ pid?: number;
585
+ kill?: KillFn;
586
+ signal?: NodeJS.Signals;
587
+ now?: () => number;
588
+ source?: string;
589
+ }): void {
590
+ requestAsyncTimeout(input.asyncDir, input.source ? { source: input.source } : {}, { now: input.now });
591
+ }
592
+
593
+ export function deliverStopRequest(input: {
594
+ asyncDir: string;
595
+ pid?: number;
596
+ kill?: KillFn;
597
+ signal?: NodeJS.Signals;
598
+ now?: () => number;
599
+ source?: string;
600
+ }): void {
601
+ requestAsyncStop(input.asyncDir, input.source ? { source: input.source } : {}, { now: input.now });
602
+ }
603
+
604
+ export function deliverCheckpointDecisionRequest(input: {
605
+ asyncDir: string;
606
+ decision: "approved" | "rejected";
607
+ now?: () => number;
608
+ source?: string;
609
+ reason?: string;
610
+ }): void {
611
+ requestAsyncCheckpointDecision(
612
+ input.asyncDir,
613
+ input.decision === "approved" ? "approve-checkpoint" : "reject-checkpoint",
614
+ { ...(input.source ? { source: input.source } : {}), ...(input.reason ? { reason: input.reason } : {}) },
615
+ { now: input.now },
616
+ );
617
+ }
618
+
619
+ /**
620
+ * Runner side: watch the control inbox and route interrupt requests into
621
+ * `onInterrupt`. Uses `fs.watch` when available plus an interval poll as a
622
+ * portable safety net (covers filesystems/platforms where `fs.watch` is
623
+ * unreliable). Fires once per distinct request. Returns a disposer.
624
+ */
625
+ export function watchAsyncControlInbox(
626
+ asyncDir: string,
627
+ opts: {
628
+ onInterrupt: () => void;
629
+ onTimeout?: () => void;
630
+ onStop?: () => void;
631
+ onSteer?: (request: SteerRequest) => void;
632
+ onCheckpointDecision?: (decision: "approved" | "rejected") => void;
633
+ onSteerCapability?: (capability: SteerCapability) => void;
634
+ onSteerAck?: (ack: SteerAck) => void;
635
+ pollIntervalMs?: number;
636
+ fs?: ControlChannelFs;
637
+ timers?: ControlChannelTimers;
638
+ },
639
+ ): () => void {
640
+ const fsImpl = opts.fs ?? fs;
641
+ const timers = opts.timers ?? { setInterval, clearInterval };
642
+ const dir = controlInboxDir(asyncDir);
643
+ try {
644
+ fsImpl.mkdirSync(dir, { recursive: true });
645
+ } catch {
646
+ // Best effort — the poll/watch below tolerates a missing dir.
647
+ }
648
+
649
+ let disposed = false;
650
+ const check = (): void => {
651
+ if (disposed) return;
652
+ try {
653
+ if (consumeStopRequest(asyncDir, fsImpl)) opts.onStop?.();
654
+ if (consumeTimeoutRequest(asyncDir, fsImpl)) opts.onTimeout?.();
655
+ if (consumeInterruptRequest(asyncDir, fsImpl)) opts.onInterrupt();
656
+ const checkpointDecision = consumeCheckpointDecisionRequest(asyncDir, fsImpl);
657
+ if (checkpointDecision) opts.onCheckpointDecision?.(checkpointDecision);
658
+ for (const request of consumeSteerRequests(asyncDir, fsImpl)) opts.onSteer?.(request);
659
+ for (const capability of consumeSteerCapabilities(asyncDir, fsImpl)) opts.onSteerCapability?.(capability);
660
+ for (const ack of consumeSteerAcks(asyncDir, fsImpl)) opts.onSteerAck?.(ack);
661
+ } catch {
662
+ // Never let inbox errors crash the runner.
663
+ }
664
+ };
665
+
666
+ // Handle a request that may have arrived before the watcher started.
667
+ check();
668
+
669
+ let watcher: fs.FSWatcher | undefined;
670
+ try {
671
+ watcher = fsImpl.watch(resolveWatchPath(dir, fsImpl.realpathSync.native), () => check());
672
+ watcher.on?.("error", () => {
673
+ // fs.watch can emit on transient FS errors; the interval poll keeps us live.
674
+ });
675
+ } catch {
676
+ watcher = undefined;
677
+ }
678
+
679
+ const interval = timers.setInterval(check, opts.pollIntervalMs ?? POLL_INTERVAL_MS);
680
+ interval.unref?.();
681
+
682
+ return () => {
683
+ if (disposed) return;
684
+ disposed = true;
685
+ try {
686
+ watcher?.close();
687
+ } catch {
688
+ // ignore
689
+ }
690
+ timers.clearInterval(interval);
691
+ };
692
+ }