@humwick/runner 0.0.0-stage → 0.130.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 (293) hide show
  1. package/LICENSE +167 -0
  2. package/agent-bin/agent-relay-browser +10 -0
  3. package/agent-bin/humwick +10 -0
  4. package/hooks/fff-search-redirect/fff-search-redirect.cjs +161 -0
  5. package/hooks/fff-search-redirect/hooks.json +13 -0
  6. package/hooks/rg-r-guard/hooks.json +18 -0
  7. package/hooks/rg-r-guard/rg-r-guard.cjs +144 -0
  8. package/hooks/web-tools-redirect/hooks.json +13 -0
  9. package/hooks/web-tools-redirect/web-tools-redirect.cjs +84 -0
  10. package/node_modules/@humwick/offload/LICENSE +167 -0
  11. package/node_modules/@humwick/offload/README.md +57 -0
  12. package/node_modules/@humwick/offload/dist/async-runner.d.ts +18 -0
  13. package/node_modules/@humwick/offload/dist/async-runner.d.ts.map +1 -0
  14. package/node_modules/@humwick/offload/dist/async-runner.js +158 -0
  15. package/node_modules/@humwick/offload/dist/async-runner.js.map +1 -0
  16. package/node_modules/@humwick/offload/dist/envelope.d.ts +25 -0
  17. package/node_modules/@humwick/offload/dist/envelope.d.ts.map +1 -0
  18. package/node_modules/@humwick/offload/dist/envelope.js +80 -0
  19. package/node_modules/@humwick/offload/dist/envelope.js.map +1 -0
  20. package/node_modules/@humwick/offload/dist/fixtures/worker-task.d.ts +10 -0
  21. package/node_modules/@humwick/offload/dist/fixtures/worker-task.d.ts.map +1 -0
  22. package/node_modules/@humwick/offload/dist/fixtures/worker-task.js +59 -0
  23. package/node_modules/@humwick/offload/dist/fixtures/worker-task.js.map +1 -0
  24. package/node_modules/@humwick/offload/dist/index.d.ts +5 -0
  25. package/node_modules/@humwick/offload/dist/index.d.ts.map +1 -0
  26. package/node_modules/@humwick/offload/dist/index.js +5 -0
  27. package/node_modules/@humwick/offload/dist/index.js.map +1 -0
  28. package/node_modules/@humwick/offload/dist/subprocess-runner.d.ts +62 -0
  29. package/node_modules/@humwick/offload/dist/subprocess-runner.d.ts.map +1 -0
  30. package/node_modules/@humwick/offload/dist/subprocess-runner.js +295 -0
  31. package/node_modules/@humwick/offload/dist/subprocess-runner.js.map +1 -0
  32. package/node_modules/@humwick/offload/dist/types.d.ts +111 -0
  33. package/node_modules/@humwick/offload/dist/types.d.ts.map +1 -0
  34. package/node_modules/@humwick/offload/dist/types.js +176 -0
  35. package/node_modules/@humwick/offload/dist/types.js.map +1 -0
  36. package/node_modules/@humwick/offload/dist/worker-pool.d.ts +23 -0
  37. package/node_modules/@humwick/offload/dist/worker-pool.d.ts.map +1 -0
  38. package/node_modules/@humwick/offload/dist/worker-pool.js +435 -0
  39. package/node_modules/@humwick/offload/dist/worker-pool.js.map +1 -0
  40. package/node_modules/@humwick/offload/dist/worker-runtime.d.ts +2 -0
  41. package/node_modules/@humwick/offload/dist/worker-runtime.d.ts.map +1 -0
  42. package/node_modules/@humwick/offload/dist/worker-runtime.js +27 -0
  43. package/node_modules/@humwick/offload/dist/worker-runtime.js.map +1 -0
  44. package/node_modules/@humwick/offload/dist/worker.d.ts +5 -0
  45. package/node_modules/@humwick/offload/dist/worker.d.ts.map +1 -0
  46. package/node_modules/@humwick/offload/dist/worker.js +1 -0
  47. package/node_modules/@humwick/offload/dist/worker.js.map +1 -0
  48. package/node_modules/@humwick/offload/package.json +46 -0
  49. package/node_modules/@humwick/offload/src/async-runner.ts +170 -0
  50. package/node_modules/@humwick/offload/src/envelope.ts +92 -0
  51. package/node_modules/@humwick/offload/src/fixtures/worker-task.ts +49 -0
  52. package/node_modules/@humwick/offload/src/index.ts +4 -0
  53. package/node_modules/@humwick/offload/src/subprocess-runner.ts +334 -0
  54. package/node_modules/@humwick/offload/src/types.ts +235 -0
  55. package/node_modules/@humwick/offload/src/worker-pool.ts +463 -0
  56. package/node_modules/@humwick/offload/src/worker-runtime.ts +32 -0
  57. package/node_modules/@humwick/offload/src/worker.ts +5 -0
  58. package/package.json +47 -4
  59. package/plugins/browser/skills/playwright-cli/SKILL.md +53 -0
  60. package/plugins/claude/.claude-plugin/plugin.json +8 -0
  61. package/plugins/claude/claude-statusline-probe.cjs +144 -0
  62. package/plugins/claude/hooks/gate-run-guard.provisioned.mjs +914 -0
  63. package/plugins/claude/hooks/gate-run-guard.sh +9 -0
  64. package/plugins/claude/hooks/gate-run-guard.ts +237 -0
  65. package/plugins/claude/hooks/hooks.json +158 -0
  66. package/plugins/claude/hooks/kill-guard.provisioned.mjs +7027 -0
  67. package/plugins/claude/hooks/kill-guard.sh +341 -0
  68. package/plugins/claude/hooks/kill-guard.ts +337 -0
  69. package/plugins/claude/hooks/permission-request.sh +22 -0
  70. package/plugins/claude/hooks/post-compact.sh +10 -0
  71. package/plugins/claude/hooks/post-tool-use.sh +8 -0
  72. package/plugins/claude/hooks/pre-compact.sh +12 -0
  73. package/plugins/claude/hooks/read-only-bash-guard.sh +587 -0
  74. package/plugins/claude/hooks/relay-status.sh +373 -0
  75. package/plugins/claude/hooks/session-end.sh +26 -0
  76. package/plugins/claude/hooks/session-start.sh +31 -0
  77. package/plugins/claude/hooks/shell-trust.ts +28 -0
  78. package/plugins/claude/hooks/stop-failure.sh +47 -0
  79. package/plugins/claude/hooks/stop.sh +48 -0
  80. package/plugins/claude/hooks/subagent-guard.cjs +26 -0
  81. package/plugins/claude/hooks/subagent-skill-policy.cjs +160 -0
  82. package/plugins/claude/hooks/subagent-start.sh +13 -0
  83. package/plugins/claude/hooks/subagent-stop.sh +19 -0
  84. package/plugins/claude/hooks/user-prompt-submit.sh +18 -0
  85. package/plugins/claude/hooks/wait-loop-guard.ts +120 -0
  86. package/plugins/claude/monitors/monitors.json +7 -0
  87. package/plugins/claude/monitors/relay-monitor.provisioned.mjs +786 -0
  88. package/plugins/claude/monitors/relay-monitor.ts +58 -0
  89. package/plugins/claude/skills/disconnect/SKILL.md +16 -0
  90. package/plugins/claude/skills/label/SKILL.md +23 -0
  91. package/plugins/claude/skills/message/SKILL.md +40 -0
  92. package/plugins/claude/skills/pair/SKILL.md +30 -0
  93. package/plugins/claude/skills/react/SKILL.md +18 -0
  94. package/plugins/claude/skills/read-message/SKILL.md +24 -0
  95. package/plugins/claude/skills/reply/SKILL.md +44 -0
  96. package/plugins/claude/skills/send-claimable/SKILL.md +39 -0
  97. package/plugins/claude/skills/slice-first/SKILL.md +32 -0
  98. package/plugins/claude/skills/slice-first/references/plan-recipe.md +46 -0
  99. package/plugins/claude/skills/status/SKILL.md +16 -0
  100. package/plugins/claude/skills/tags/SKILL.md +25 -0
  101. package/plugins/claude/skills/task/SKILL.md +28 -0
  102. package/plugins/claude-output-style/.claude-plugin/plugin.json +5 -0
  103. package/plugins/claude-output-style/output-styles/agent-relay.md +5 -0
  104. package/plugins/codex/skills/disconnect/SKILL.md +15 -0
  105. package/plugins/codex/skills/guide/SKILL.md +15 -0
  106. package/plugins/codex/skills/label/SKILL.md +22 -0
  107. package/plugins/codex/skills/message/SKILL.md +40 -0
  108. package/plugins/codex/skills/pair/SKILL.md +29 -0
  109. package/plugins/codex/skills/react/SKILL.md +17 -0
  110. package/plugins/codex/skills/read-message/SKILL.md +23 -0
  111. package/plugins/codex/skills/reply/SKILL.md +44 -0
  112. package/plugins/codex/skills/send-claimable/SKILL.md +39 -0
  113. package/plugins/codex/skills/slice-first/SKILL.md +32 -0
  114. package/plugins/codex/skills/slice-first/references/plan-recipe.md +46 -0
  115. package/plugins/codex/skills/status/SKILL.md +15 -0
  116. package/plugins/codex/skills/tags/SKILL.md +24 -0
  117. package/plugins/codex/skills/task/SKILL.md +28 -0
  118. package/src/adapter.ts +1061 -0
  119. package/src/adapters/__fixtures__/codex-app-server.ts +47 -0
  120. package/src/adapters/claude-api.ts +243 -0
  121. package/src/adapters/claude-context-command.ts +16 -0
  122. package/src/adapters/claude-credentials.ts +22 -0
  123. package/src/adapters/claude-delivery-lanes.ts +28 -0
  124. package/src/adapters/claude-delivery.ts +166 -0
  125. package/src/adapters/claude-effort.ts +94 -0
  126. package/src/adapters/claude-exit.ts +290 -0
  127. package/src/adapters/claude-headless-mirror.ts +88 -0
  128. package/src/adapters/claude-headless-refusal.ts +51 -0
  129. package/src/adapters/claude-headless.ts +617 -0
  130. package/src/adapters/claude-monitor-delivery-plan.ts +317 -0
  131. package/src/adapters/claude-permission.ts +243 -0
  132. package/src/adapters/claude-prompt-gates.ts +269 -0
  133. package/src/adapters/claude-prompt-hook.ts +145 -0
  134. package/src/adapters/claude-session-capture.ts +293 -0
  135. package/src/adapters/claude-session-probe.ts +414 -0
  136. package/src/adapters/claude-shutdown.ts +190 -0
  137. package/src/adapters/claude-status-detectors.ts +426 -0
  138. package/src/adapters/claude-subagents.ts +93 -0
  139. package/src/adapters/claude-submit-confirmation.ts +287 -0
  140. package/src/adapters/claude-tmux.ts +548 -0
  141. package/src/adapters/claude-token-usage-capture.ts +253 -0
  142. package/src/adapters/claude-tool-policy.ts +165 -0
  143. package/src/adapters/claude-transcript-tail.ts +193 -0
  144. package/src/adapters/claude-transcript.ts +812 -0
  145. package/src/adapters/claude.ts +1097 -0
  146. package/src/adapters/codex-agent-message-capture.ts +189 -0
  147. package/src/adapters/codex-app-server.ts +70 -0
  148. package/src/adapters/codex-client.ts +362 -0
  149. package/src/adapters/codex-effective-config.ts +87 -0
  150. package/src/adapters/codex-launch-config.ts +153 -0
  151. package/src/adapters/codex-rollout-context.ts +272 -0
  152. package/src/adapters/codex-skill-discovery.ts +18 -0
  153. package/src/adapters/codex-token-usage-capture.ts +163 -0
  154. package/src/adapters/codex-tool-output.ts +53 -0
  155. package/src/adapters/codex-turn-outcome.ts +27 -0
  156. package/src/adapters/codex-version.ts +64 -0
  157. package/src/adapters/codex.ts +1442 -0
  158. package/src/adapters/incremental-file.ts +110 -0
  159. package/src/adapters/opencode-api.ts +71 -0
  160. package/src/adapters/opencode-context.ts +277 -0
  161. package/src/adapters/opencode-model-registry.ts +126 -0
  162. package/src/adapters/opencode-provider.ts +169 -0
  163. package/src/adapters/opencode-server-retry.ts +50 -0
  164. package/src/adapters/opencode-soft-steer.ts +302 -0
  165. package/src/adapters/opencode-spawn.ts +145 -0
  166. package/src/adapters/opencode-subscribe.ts +62 -0
  167. package/src/adapters/opencode-token-usage-capture.ts +187 -0
  168. package/src/adapters/opencode-tool-events.ts +302 -0
  169. package/src/adapters/opencode-tools-config.ts +17 -0
  170. package/src/adapters/opencode.ts +2264 -0
  171. package/src/adapters/project-shell.ts +80 -0
  172. package/src/adapters/provider-launch-config.ts +21 -0
  173. package/src/adapters/provider-quota-harvest.ts +127 -0
  174. package/src/adapters/service-access.ts +153 -0
  175. package/src/adapters/tmux-offload.ts +207 -0
  176. package/src/adapters/tool-summary.ts +214 -0
  177. package/src/agent-redact.ts +75 -0
  178. package/src/agent-runner/commands/dispatch.ts +185 -0
  179. package/src/agent-runner/commands/lifecycle.ts +84 -0
  180. package/src/agent-runner/commands/prompt.ts +284 -0
  181. package/src/agent-runner/credentials.ts +208 -0
  182. package/src/agent-runner/http-liveness.ts +85 -0
  183. package/src/agent-runner/lifecycle-milestones.ts +207 -0
  184. package/src/agent-runner/lifecycle-phase.ts +80 -0
  185. package/src/agent-runner/registration.ts +163 -0
  186. package/src/agent-runner/runner-context.ts +158 -0
  187. package/src/agent-runner/session-mirror.ts +278 -0
  188. package/src/agent-runner/task-claims.ts +116 -0
  189. package/src/agent-runner/token-usage-coverage.ts +54 -0
  190. package/src/agent-runner/turn-report.ts +269 -0
  191. package/src/api-budget-accounting.ts +91 -0
  192. package/src/area-memory.ts +255 -0
  193. package/src/artifact-path-materialize.ts +52 -0
  194. package/src/async-guard.ts +35 -0
  195. package/src/attachment-cache-sweep.ts +31 -0
  196. package/src/attachment-cache.ts +195 -0
  197. package/src/background-script-reconcile.ts +106 -0
  198. package/src/bounded-log.ts +59 -0
  199. package/src/bounded-spawn-sync.ts +18 -0
  200. package/src/busy-reconciler.ts +282 -0
  201. package/src/claim-tracker.ts +140 -0
  202. package/src/claude-settings.ts +167 -0
  203. package/src/claude-workspace-trust.ts +289 -0
  204. package/src/config.ts +547 -0
  205. package/src/context-boundary.ts +101 -0
  206. package/src/context-command.ts +151 -0
  207. package/src/context-probe-state.ts +6 -0
  208. package/src/continuation-archive.ts +179 -0
  209. package/src/control-server.ts +730 -0
  210. package/src/delivery-policy.ts +9 -0
  211. package/src/delivery-result.ts +24 -0
  212. package/src/effort-command.ts +125 -0
  213. package/src/empty-turn.ts +816 -0
  214. package/src/free-port.ts +25 -0
  215. package/src/fs-offload.ts +26 -0
  216. package/src/gate-run-config.ts +35 -0
  217. package/src/gate-run-lease-probe.ts +38 -0
  218. package/src/host-asset-plan.ts +450 -0
  219. package/src/host-claude-config-worker.ts +34 -0
  220. package/src/host-sources.ts +40 -0
  221. package/src/inbox-carrier.ts +7 -0
  222. package/src/index.ts +386 -0
  223. package/src/launch-assembly.ts +955 -0
  224. package/src/liveness.ts +105 -0
  225. package/src/logger.ts +108 -0
  226. package/src/mcp-outbox.ts +204 -0
  227. package/src/mcp-preflight.ts +86 -0
  228. package/src/mcp-source-selection.ts +54 -0
  229. package/src/mcp-tool-deferral.ts +35 -0
  230. package/src/mcp-vault-env.ts +25 -0
  231. package/src/message-body-config/config.ts +16 -0
  232. package/src/message-body-config.ts +1 -0
  233. package/src/mid-turn-delivery.ts +43 -0
  234. package/src/native-memory-lever.ts +329 -0
  235. package/src/native-self-resume.ts +244 -0
  236. package/src/outbox.ts +453 -0
  237. package/src/park-post.ts +17 -0
  238. package/src/pending-permission-store.ts +148 -0
  239. package/src/process-meta.ts +9 -0
  240. package/src/profile-home.ts +419 -0
  241. package/src/profile-projection.ts +411 -0
  242. package/src/project-hooks.ts +65 -0
  243. package/src/project-instructions.ts +119 -0
  244. package/src/provider-double.ts +59 -0
  245. package/src/provider-hold.ts +228 -0
  246. package/src/provider-home-marker.ts +3 -0
  247. package/src/provider-home-tombstone.ts +4 -0
  248. package/src/provider-input-queue.ts +134 -0
  249. package/src/provider-integration.ts +93 -0
  250. package/src/provider-processes.ts +17 -0
  251. package/src/provider-submit-failure.ts +15 -0
  252. package/src/providers.ts +35 -0
  253. package/src/provisioning.ts +703 -0
  254. package/src/question-decision.ts +18 -0
  255. package/src/quota.ts +22 -0
  256. package/src/rate-limit.ts +351 -0
  257. package/src/refused-prompt-store.ts +36 -0
  258. package/src/relay-injection-events.ts +161 -0
  259. package/src/relay-instructions.ts +107 -0
  260. package/src/relay-mcp-proxy.long-turn-e2e.ts +183 -0
  261. package/src/relay-mcp-proxy.ts +704 -0
  262. package/src/relay-mcp.ts +583 -0
  263. package/src/reply-obligation-cache.ts +211 -0
  264. package/src/response-capture-report.ts +111 -0
  265. package/src/response-routing.ts +6 -0
  266. package/src/runner-core.ts +2955 -0
  267. package/src/runner-exit.ts +12 -0
  268. package/src/runner-helpers.ts +582 -0
  269. package/src/runner-insights.ts +105 -0
  270. package/src/runner-mcp-proxy.ts +46 -0
  271. package/src/runner-spawn-config.ts +68 -0
  272. package/src/runner-stale-scratch-sweep.ts +21 -0
  273. package/src/runner.ts +9 -0
  274. package/src/runtime-token-file.ts +45 -0
  275. package/src/runtime-token-remint.ts +56 -0
  276. package/src/service-access.ts +88 -0
  277. package/src/session-destroy.ts +27 -0
  278. package/src/session-insights.ts +118 -0
  279. package/src/session-scratch.ts +296 -0
  280. package/src/spawn-input.ts +147 -0
  281. package/src/startup-config-fetch.ts +48 -0
  282. package/src/subreaper.ts +113 -0
  283. package/src/template-resolver.ts +29 -0
  284. package/src/test-run-dedup.ts +435 -0
  285. package/src/transcript-context.ts +99 -0
  286. package/src/transport-errors.ts +48 -0
  287. package/src/turn-opener.ts +55 -0
  288. package/src/turn-reconcile-event.ts +88 -0
  289. package/src/vault-proxy-hop.ts +99 -0
  290. package/src/version.ts +44 -0
  291. package/src/web-tool-call-proxy.ts +128 -0
  292. package/src/web-tools.ts +59 -0
  293. package/README.md +0 -3
@@ -0,0 +1,334 @@
1
+ import PQueue from "p-queue";
2
+ import { beginRun, finishLog, recordResult, startLog, type RunContext } from "./envelope.js";
3
+ import { OffloadError, StrikeCounter, normalizeError, validateTimeout, type OffloadDefaults, type OffloadEnvelope } from "./types.js";
4
+
5
+ export interface SubprocessSpec {
6
+ command: string[];
7
+ cwd?: string;
8
+ env?: Record<string, string | undefined>;
9
+ /**
10
+ * Exit codes that are a normal ANSWER rather than a failure. Defaults to `[0]`; pass
11
+ * `"any"` when every code is data (a land gate whose failing codes are not enumerable).
12
+ *
13
+ * Probe-shaped callers use a non-zero exit as data — `tmux has-session` exits 1 when the
14
+ * session is absent, `git rev-parse` exits 128 outside a repo, `which` exits 1. Without
15
+ * this they reject AND take an escalation strike for a healthy result, which inverts the
16
+ * signal: the sink pages on a healthy fleet, then latches (it only re-arms on a success,
17
+ * which never comes in that steady state) so the real outage is silent.
18
+ *
19
+ * `"any"` includes SIGNAL DEATHS — a child killed by SIGKILL (137) or SIGSEGV (139)
20
+ * returns as a success and RE-ARMS the strike counter. That is intended for a land gate,
21
+ * where an OOM-killed gate is simply a failed gate, but it means an infrastructure death
22
+ * reads as a healthy answer and will never escalate. Prefer an explicit code list unless
23
+ * the failing codes genuinely cannot be enumerated. Timeout and abort still throw.
24
+ */
25
+ okExitCodes?: readonly number[] | "any";
26
+ }
27
+
28
+ export interface SubprocessResult {
29
+ exitCode: number;
30
+ stdout: string;
31
+ stderr: string;
32
+ /** True when either stream hit `maxOutputBytes` and the captured text was cut short. */
33
+ truncated: boolean;
34
+ }
35
+
36
+ export interface SubprocessRunnerOptions extends OffloadDefaults {
37
+ concurrency?: number;
38
+ /**
39
+ * How long a child may keep running after SIGTERM before it is SIGKILLed. This is the
40
+ * slack on the deadline: a run cannot outlive `timeoutMs + killGraceMs` (plus a short
41
+ * reap window) even if it traps or ignores SIGTERM. Defaults to 2000ms.
42
+ */
43
+ killGraceMs?: number;
44
+ /** Captured bytes per stream before output is truncated. Defaults to 8 MiB. */
45
+ maxOutputBytes?: number;
46
+ }
47
+
48
+ export interface SubprocessRunner {
49
+ run(taskName: string, process: SubprocessSpec, env?: OffloadEnvelope): Promise<SubprocessResult>;
50
+ readonly stats: { active: number; queued: number };
51
+ /** A subprocess owns the heavy work, so maintenance callers may mark their await window off-thread. */
52
+ readonly offThread: true;
53
+ /** Resolves when everything accepted so far has finished. Does not cancel anything. */
54
+ drain(): Promise<void>;
55
+ /** SIGKILLs and awaits every live child, settles every outstanding caller, and refuses new work. */
56
+ destroy(): Promise<void>;
57
+ }
58
+
59
+ type Child = ReturnType<typeof Bun.spawn>;
60
+
61
+ const DEFAULT_KILL_GRACE_MS = 2_000;
62
+ const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
63
+ /** How long to wait for a SIGKILLed child to be reaped before giving its slot back anyway. */
64
+ const REAP_GRACE_MS = 1_000;
65
+
66
+ /**
67
+ * `detached` children are reparented rather than reaped when the host dies (#1809 P1-5), so
68
+ * every live group is killed from a single process-level exit hook. One module-scoped hook
69
+ * keeps runner instances from piling up `exit` listeners.
70
+ */
71
+ const liveChildren = new Set<Child>();
72
+ let exitHookInstalled = false;
73
+
74
+ function killGroup(child: Child, signal: NodeJS.Signals): void {
75
+ try {
76
+ if (process.platform !== "win32") process.kill(-child.pid, signal);
77
+ else child.kill();
78
+ } catch {
79
+ try { child.kill(signal); } catch { /* the child is already gone */ }
80
+ }
81
+ }
82
+
83
+ function trackChild(child: Child): void {
84
+ liveChildren.add(child);
85
+ if (exitHookInstalled) return;
86
+ exitHookInstalled = true;
87
+ process.on("exit", () => {
88
+ for (const live of liveChildren) killGroup(live, "SIGKILL");
89
+ });
90
+ }
91
+
92
+ /** Reads a stream up to `limit` bytes, then keeps draining so the child never blocks on a full pipe. */
93
+ async function readCapped(stream: ReadableStream<Uint8Array> | null, limit: number): Promise<{ text: string; truncated: boolean }> {
94
+ if (!stream) return { text: "", truncated: false };
95
+ const reader = stream.getReader();
96
+ const chunks: Uint8Array[] = [];
97
+ let size = 0;
98
+ let truncated = false;
99
+ try {
100
+ for (;;) {
101
+ const { done, value } = await reader.read();
102
+ if (done) break;
103
+ if (!value) continue;
104
+ const remaining = limit - size;
105
+ if (remaining <= 0) {
106
+ truncated = true;
107
+ continue;
108
+ }
109
+ if (value.byteLength > remaining) {
110
+ chunks.push(value.subarray(0, remaining));
111
+ size = limit;
112
+ truncated = true;
113
+ continue;
114
+ }
115
+ chunks.push(value);
116
+ size += value.byteLength;
117
+ }
118
+ } finally {
119
+ reader.releaseLock();
120
+ }
121
+ const buffer = new Uint8Array(size);
122
+ let offset = 0;
123
+ for (const chunk of chunks) {
124
+ buffer.set(chunk, offset);
125
+ offset += chunk.byteLength;
126
+ }
127
+ return { text: new TextDecoder().decode(buffer), truncated };
128
+ }
129
+
130
+ type Outcome = { ok: true; value: SubprocessResult } | { ok: false; error: OffloadError };
131
+
132
+ type LiveRun = {
133
+ taskName: string;
134
+ teardown: AbortController;
135
+ settled: Promise<void>;
136
+ /** Settles a caller whose child has not been spawned yet; a no-op once it has. */
137
+ cancelIfQueued(error: OffloadError): void;
138
+ };
139
+
140
+ /**
141
+ * Bounded wrapper around the repo's standard `Bun.spawn(... { stdout: "pipe", stderr: "pipe" })`
142
+ * pattern. On POSIX, each run gets its own process group so timeout/abort also kills
143
+ * descendants (for example shell, git, or install subprocess trees); Windows falls back
144
+ * to Bun's direct-child kill because POSIX process groups do not exist there.
145
+ */
146
+ export function createSubprocessRunner(options: SubprocessRunnerOptions = {}): SubprocessRunner {
147
+ const queue = new PQueue({ concurrency: options.concurrency ?? 1 });
148
+ const counter = new StrikeCounter(options.escalationThreshold, options.escalationWindowAttempts);
149
+ const killGraceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
150
+ const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
151
+ if (!Number.isFinite(killGraceMs) || killGraceMs < 0) throw new RangeError("killGraceMs must be a non-negative finite number");
152
+ if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1) throw new RangeError("maxOutputBytes must be a positive integer");
153
+ const live = new Set<LiveRun>();
154
+ const children = new Set<Child>();
155
+ let destroyed = false;
156
+
157
+ const abortedError = (taskName: string, cause?: unknown): OffloadError =>
158
+ new OffloadError({ kind: "aborted", taskName, message: `${taskName} was aborted`, cause });
159
+ const destroyedError = (taskName: string): OffloadError =>
160
+ new OffloadError({ kind: "aborted", taskName, message: `${taskName} was cancelled: subprocess runner destroyed` });
161
+
162
+ return {
163
+ offThread: true,
164
+ get stats() { return { active: queue.pending, queued: queue.size }; },
165
+ async run(taskName: string, spec: SubprocessSpec, env?: OffloadEnvelope): Promise<SubprocessResult> {
166
+ const labels = env?.labels ?? {};
167
+ const logger = env?.logger ?? options.logger;
168
+ const sink = env?.onEscalate ?? options.onEscalate;
169
+ const reportRejection = async (error: OffloadError): Promise<never> => {
170
+ // Rejecting before the run reaches startLog is still a terminal outcome; without this
171
+ // the structured stream shows nothing at all for it.
172
+ finishLog(logger, "subprocess", taskName, labels, performance.now(), error);
173
+ await recordResult({ counter, taskName, backend: "subprocess", labels, error, sink, logger });
174
+ throw error;
175
+ };
176
+ if (!spec.command.length) return reportRejection(new OffloadError({ kind: "rejected", taskName, message: "Subprocess command must not be empty" }));
177
+ if (destroyed) return reportRejection(destroyedError(taskName));
178
+ if (env?.signal?.aborted) return reportRejection(abortedError(taskName, env.signal.reason));
179
+ try {
180
+ validateTimeout(env?.timeoutMs ?? options.defaultTimeoutMs);
181
+ } catch (error) {
182
+ return reportRejection(normalizeError(taskName, error, "rejected"));
183
+ }
184
+
185
+ let publish!: (outcome: Outcome) => void;
186
+ let published = false;
187
+ const outcome = new Promise<Outcome>((resolve) => {
188
+ publish = (value) => { if (!published) { published = true; resolve(value); } };
189
+ });
190
+ let started = false;
191
+ let cancelled = false;
192
+ const entry: LiveRun = {
193
+ taskName,
194
+ teardown: new AbortController(),
195
+ settled: outcome.then(() => undefined),
196
+ cancelIfQueued: (error) => {
197
+ if (started || cancelled) return;
198
+ cancelled = true;
199
+ // The single funnel for both abort-while-queued and destroy()-cancels-queued, so
200
+ // the one line each terminal path owes the structured stream is emitted here. The
201
+ // callback bails on `cancelled` without logging, which keeps it to exactly one.
202
+ finishLog(logger, "subprocess", taskName, labels, performance.now(), error);
203
+ publish({ ok: false, error });
204
+ },
205
+ };
206
+ live.add(entry);
207
+
208
+ // p-queue's own `signal` option used to provide prompt abort for queued runs, but it
209
+ // also released the slot while the child kept running (#1809 P1-7).
210
+ const signal = env?.signal;
211
+ const onQueuedAbort = signal ? () => entry.cancelIfQueued(abortedError(taskName, signal.reason)) : undefined;
212
+ if (signal && onQueuedAbort) signal.addEventListener("abort", onQueuedAbort, { once: true });
213
+
214
+ const task = queue.add(async () => {
215
+ if (signal && onQueuedAbort) signal.removeEventListener("abort", onQueuedAbort);
216
+ let context: RunContext | undefined;
217
+ let child: Child | undefined;
218
+ let onAbort: (() => void) | undefined;
219
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
220
+ let abandonTimer: ReturnType<typeof setTimeout> | undefined;
221
+ let reaped = false;
222
+ let abandon!: () => void;
223
+ const abandoned = new Promise<"abandoned">((resolve) => { abandon = () => resolve("abandoned"); });
224
+ try {
225
+ if (cancelled) return;
226
+ if (destroyed || entry.teardown.signal.aborted) {
227
+ const error = destroyedError(taskName);
228
+ finishLog(logger, "subprocess", taskName, labels, performance.now(), error);
229
+ publish({ ok: false, error });
230
+ return;
231
+ }
232
+ started = true;
233
+ context = beginRun(taskName, env, options, entry.teardown.signal);
234
+ const run = context;
235
+ const startedAt = startLog(logger, "subprocess", taskName, labels);
236
+ // SIGTERM alone bounds nothing: a child that traps or ignores it runs to completion
237
+ // while holding the slot (#1809 P0-3). Escalate to a group SIGKILL, then stop
238
+ // waiting altogether so the deadline is real even for an unkillable child.
239
+ onAbort = () => {
240
+ if (!child || reaped) return;
241
+ killGroup(child, "SIGTERM");
242
+ killTimer = setTimeout(() => {
243
+ // `reaped` keeps a late timer from signalling a process group whose pid the
244
+ // kernel may already have handed to somebody else.
245
+ if (!child || reaped) return;
246
+ killGroup(child, "SIGKILL");
247
+ abandonTimer = setTimeout(abandon, REAP_GRACE_MS);
248
+ }, killGraceMs);
249
+ };
250
+ run.signal.addEventListener("abort", onAbort, { once: true });
251
+ try {
252
+ if (run.signal.aborted) throw run.abortError();
253
+ child = Bun.spawn(spec.command, {
254
+ cwd: spec.cwd,
255
+ env: spec.env ? { ...process.env, ...spec.env } : process.env,
256
+ stdin: "ignore", stdout: "pipe", stderr: "pipe",
257
+ detached: process.platform !== "win32",
258
+ });
259
+ trackChild(child);
260
+ children.add(child);
261
+ const exiting = child;
262
+ void exiting.exited.then(() => {
263
+ reaped = true;
264
+ liveChildren.delete(exiting);
265
+ children.delete(exiting);
266
+ });
267
+ const completed = Promise.all([
268
+ readCapped(child.stdout as ReadableStream<Uint8Array> | null, maxOutputBytes),
269
+ readCapped(child.stderr as ReadableStream<Uint8Array> | null, maxOutputBytes),
270
+ child.exited,
271
+ ]);
272
+ const settledRun = await Promise.race([completed, abandoned]);
273
+ if (settledRun === "abandoned") {
274
+ throw run.signal.aborted
275
+ ? run.abortError()
276
+ : new OffloadError({ kind: "timeout", taskName, message: `${taskName} did not exit after SIGKILL` });
277
+ }
278
+ const [stdout, stderr, exitCode] = settledRun;
279
+ if (run.signal.aborted) throw run.abortError();
280
+ const okExitCodes = spec.okExitCodes ?? [0];
281
+ if (okExitCodes !== "any" && !okExitCodes.includes(exitCode)) throw new OffloadError({
282
+ kind: "rejected", taskName, code: String(exitCode), message: `${taskName} exited ${exitCode}: ${stderr.text.trim() || stdout.text.trim()}`,
283
+ });
284
+ const result: SubprocessResult = { exitCode, stdout: stdout.text, stderr: stderr.text, truncated: stdout.truncated || stderr.truncated };
285
+ finishLog(logger, "subprocess", taskName, labels, startedAt);
286
+ await recordResult({ counter, taskName, backend: "subprocess", labels, sink, logger });
287
+ publish({ ok: true, value: result });
288
+ } catch (error) {
289
+ const normalized = run.signal.aborted ? run.abortError() : normalizeError(taskName, error);
290
+ finishLog(logger, "subprocess", taskName, labels, startedAt, normalized);
291
+ await recordResult({ counter, taskName, backend: "subprocess", labels, error: normalized, sink, logger });
292
+ publish({ ok: false, error: normalized });
293
+ } finally {
294
+ if (onAbort) run.signal.removeEventListener("abort", onAbort);
295
+ run.cleanup();
296
+ }
297
+ } catch (error) {
298
+ const normalized = normalizeError(taskName, error, "rejected");
299
+ finishLog(logger, "subprocess", taskName, labels, performance.now(), normalized);
300
+ await recordResult({ counter, taskName, backend: "subprocess", labels, error: normalized, sink, logger });
301
+ publish({ ok: false, error: normalized });
302
+ } finally {
303
+ context?.cleanup();
304
+ // Keep the slot until the child is actually reaped, so the concurrency cap and
305
+ // `stats` stay true while a kill is in flight (#1809 P1-7). `abandoned` bounds
306
+ // this: the SIGKILL escalation above always ends the wait.
307
+ if (child) await Promise.race([child.exited, abandoned]);
308
+ if (killTimer) clearTimeout(killTimer);
309
+ if (abandonTimer) clearTimeout(abandonTimer);
310
+ live.delete(entry);
311
+ }
312
+ });
313
+ void task.catch(() => undefined);
314
+
315
+ const result = await outcome;
316
+ if (!result.ok) throw result.error;
317
+ return result.value;
318
+ },
319
+ drain: () => queue.onIdle(),
320
+ async destroy(): Promise<void> {
321
+ destroyed = true;
322
+ const outstanding = [...live];
323
+ for (const entry of outstanding) {
324
+ entry.cancelIfQueued(destroyedError(entry.taskName));
325
+ entry.teardown.abort(new DOMException("Subprocess runner destroyed", "AbortError"));
326
+ }
327
+ for (const child of children) killGroup(child, "SIGKILL");
328
+ await Promise.all([
329
+ ...outstanding.map((entry) => entry.settled),
330
+ ...[...children].map((child) => child.exited),
331
+ ]);
332
+ },
333
+ };
334
+ }
@@ -0,0 +1,235 @@
1
+ import { errMessage } from "@humwick/sdk";
2
+
3
+ export type OffloadErrorKind = "timeout" | "aborted" | "worker-error" | "worker-exit" | "rejected";
4
+
5
+ /** A stable, backend-independent failure surface for callers and escalation sinks. */
6
+ export class OffloadError extends Error {
7
+ readonly kind: OffloadErrorKind;
8
+ readonly code?: string;
9
+ readonly taskName: string;
10
+
11
+ constructor(options: {
12
+ kind: OffloadErrorKind;
13
+ taskName: string;
14
+ code?: string;
15
+ message?: string;
16
+ cause?: unknown;
17
+ }) {
18
+ super(options.message ?? `${options.taskName} ${options.kind}`, { cause: options.cause });
19
+ this.name = "OffloadError";
20
+ this.kind = options.kind;
21
+ this.code = options.code;
22
+ this.taskName = options.taskName;
23
+ }
24
+ }
25
+
26
+ export type OffloadLogFields = Record<string, unknown>;
27
+
28
+ /** Deliberately structural: server, runner and orchestrator can pass their existing logger adapters. */
29
+ export interface OffloadLogger {
30
+ debug?(message: string, fields?: OffloadLogFields): void;
31
+ info?(message: string, fields?: OffloadLogFields): void;
32
+ warn?(message: string, fields?: OffloadLogFields): void;
33
+ error?(message: string, fields?: OffloadLogFields): void;
34
+ }
35
+
36
+ export interface EscalationEvent {
37
+ taskName: string;
38
+ backend: "worker" | "async" | "subprocess";
39
+ error: OffloadError;
40
+ strikes: number;
41
+ labels: Record<string, string>;
42
+ }
43
+
44
+ export type EscalationSink = (event: EscalationEvent) => void | Promise<void>;
45
+
46
+ /** The common per-run contract. No backend-specific options leak into this envelope. */
47
+ export interface OffloadEnvelope {
48
+ timeoutMs?: number;
49
+ signal?: AbortSignal;
50
+ logger?: OffloadLogger;
51
+ labels?: Record<string, string>;
52
+ onEscalate?: EscalationSink;
53
+ /**
54
+ * Opt in to automatic re-dispatch after an ambiguous worker death (WorkerPool only; the async
55
+ * and subprocess runners never re-run). Default is AT-MOST-ONCE: if the worker dies with this
56
+ * job in flight, the job is rejected (`worker-exit`) and never re-run — because a re-run would
57
+ * repeat any side effect the job already performed (an HTTP POST, a mutation). Set this ONLY
58
+ * when the job is idempotent/retry-safe (pure compute), in which case a worker death is
59
+ * absorbed by re-dispatching to a fresh worker up to a bounded number of times (#1822 HIGH-1).
60
+ * Command/handler offload (side-effecting) must leave this unset.
61
+ */
62
+ retrySafe?: boolean;
63
+ }
64
+
65
+ export interface OffloadDefaults {
66
+ defaultTimeoutMs?: number;
67
+ logger?: OffloadLogger;
68
+ onEscalate?: EscalationSink;
69
+ /** Consecutive failed runs for a task before its injected sink fires. Defaults to 3. */
70
+ escalationThreshold?: number;
71
+ /**
72
+ * Size, in failure-attempts, of the sliding window the strike counter escalates over: a task
73
+ * escalates when it accumulates `escalationThreshold` failures within this many consecutive
74
+ * failure-attempts (counted across ALL tasks). A task with no failure inside the window is
75
+ * forgotten, which is ALSO what bounds memory — the counter holds at most this many failure
76
+ * events, so at most this many distinct names, at once (#1822 items 1 and 4). Adoption keys
77
+ * runs by dynamic names (workspace/agent ids); the window is what keeps that from growing
78
+ * without bound. Defaults to 4096.
79
+ */
80
+ escalationWindowAttempts?: number;
81
+ }
82
+
83
+ /**
84
+ * Sliding-window failure counter driving edge-triggered escalation (#1822 F1/F4, round-3
85
+ * redesign). A task escalates when it accumulates `threshold` failures within the last
86
+ * `window` failure-attempts (counted across all tasks); a failure older than the window no
87
+ * longer counts. This is attempt-based — no wall-clock, no timers — so it is deterministic and
88
+ * needs no time injection to test.
89
+ *
90
+ * WHY windowed rather than a size-capped consecutive counter: any hard *count* cap on a
91
+ * consecutive-strike map either scans the map per failure (O(cap); an earlier attempt blocked
92
+ * the event loop ~11s at 40k / ~31s at 100k distinct failures) or silently drops a task that is
93
+ * genuinely accumulating (a missed page — strictly worse than the leak it replaced). The window
94
+ * gives all four invariants at once: no lost escalation, no page storm, amortized O(1) per
95
+ * failure, and a hard memory bound.
96
+ *
97
+ * IMPLEMENTATION — the standard sliding-window multiset over a ring of failure events:
98
+ * - `#ring[(clock-1) % window]` holds the failure event `window` attempts ago. Each new failure
99
+ * overwrites exactly that slot, and the event it evicts is exactly the one aging out — so a
100
+ * failure is pushed once and expired once: amortized O(1), never a scan.
101
+ * - `#live[name]` is the name's failure count still inside the window = its escalation score.
102
+ * - Memory is hard-bounded: the ring holds ≤ `window` events, hence ≤ `window` distinct names.
103
+ * - `succeed()` bumps a per-name `#epoch`; events carry the epoch they were recorded under, so a
104
+ * success invalidates the name's in-window failures (score resets) in O(1) without scanning
105
+ * the ring — the stale events simply don't count as they age out.
106
+ * - Latch (`trip`): a per-name flag so an escalation fires ONCE and does not re-fire while the
107
+ * task stays continuously failing; it clears when the task succeeds or every failure ages out.
108
+ *
109
+ * SEMANTIC NOTE (deliberate change from the first #1822 attempt): escalation is now "threshold
110
+ * failures WITHIN the window", not "threshold consecutive failures ever". Failures spread wider
111
+ * apart than the window decay and never trip — which is the actual flap-detection semantic.
112
+ */
113
+ export class StrikeCounter {
114
+ #ring: Array<{ name: string; epoch: number } | undefined>;
115
+ /** Failures still inside the window under the name's CURRENT epoch = its escalation score. */
116
+ #live = new Map<string, number>();
117
+ /** Total ring occurrences per name across all epochs — for O(1) cleanup and the memory bound. */
118
+ #present = new Map<string, number>();
119
+ /** Per-name epoch, bumped by succeed() so pre-success failures stop counting. */
120
+ #epoch = new Map<string, number>();
121
+ /** Names that have escalated and not yet re-armed (edge-trigger latch). */
122
+ #latched = new Set<string>();
123
+ #clock = 0;
124
+ readonly threshold: number;
125
+ readonly window: number;
126
+
127
+ constructor(threshold = 3, escalationWindowAttempts = 4096) {
128
+ if (!Number.isSafeInteger(threshold) || threshold < 1) throw new RangeError("escalationThreshold must be a positive integer");
129
+ if (!Number.isSafeInteger(escalationWindowAttempts) || escalationWindowAttempts < 1) throw new RangeError("escalationWindowAttempts must be a positive integer");
130
+ // A window smaller than the threshold can never hold `threshold` of one name's failures at
131
+ // once (the ring evicts the oldest before the count gets there), so it would score 1,2,…,
132
+ // threshold-1 forever and SILENTLY never escalate. Reject it rather than mislead (#1822 LOW-4).
133
+ if (escalationWindowAttempts < threshold) throw new RangeError("escalationWindowAttempts must be >= escalationThreshold");
134
+ this.threshold = threshold;
135
+ this.window = escalationWindowAttempts;
136
+ this.#ring = new Array(escalationWindowAttempts).fill(undefined);
137
+ }
138
+
139
+ /** Distinct task names with a failure still inside the window. Bounded by `window`. */
140
+ get size(): number {
141
+ return this.#present.size;
142
+ }
143
+
144
+ // Removes the event in `slot` (the one aging out of the window) and updates the name's counts.
145
+ #expire(slot: number): void {
146
+ const event = this.#ring[slot];
147
+ if (event === undefined) return;
148
+ this.#ring[slot] = undefined;
149
+ const { name, epoch } = event;
150
+ // Only decrement the score if the event is still under the name's live epoch; an event from
151
+ // before a succeed() carries a stale epoch and was never counted toward the current score.
152
+ if (epoch === (this.#epoch.get(name) ?? 0)) {
153
+ const live = (this.#live.get(name) ?? 0) - 1;
154
+ if (live <= 0) { this.#live.delete(name); this.#latched.delete(name); }
155
+ else this.#live.set(name, live);
156
+ }
157
+ const present = (this.#present.get(name) ?? 0) - 1;
158
+ if (present <= 0) {
159
+ // Every trace of the name has aged out of the window: forget it entirely (this is the
160
+ // natural memory bound, and it re-arms a latch that went quiet).
161
+ this.#present.delete(name);
162
+ this.#epoch.delete(name);
163
+ this.#live.delete(name);
164
+ this.#latched.delete(name);
165
+ } else {
166
+ this.#present.set(name, present);
167
+ }
168
+ }
169
+
170
+ fail(taskName: string): number {
171
+ this.#clock += 1;
172
+ const slot = (this.#clock - 1) % this.window;
173
+ // The event this slot holds is exactly `window` attempts old — evict it before reusing it.
174
+ this.#expire(slot);
175
+ const epoch = this.#epoch.get(taskName) ?? 0;
176
+ this.#ring[slot] = { name: taskName, epoch };
177
+ this.#present.set(taskName, (this.#present.get(taskName) ?? 0) + 1);
178
+ const score = (this.#live.get(taskName) ?? 0) + 1;
179
+ this.#live.set(taskName, score);
180
+ // A latched name must not re-page while it stays continuously live.
181
+ if (this.#latched.has(taskName)) return 0;
182
+ return score;
183
+ }
184
+
185
+ /** Latch an escalation so it fires once until the task re-arms (succeeds or ages out). */
186
+ trip(taskName: string): void {
187
+ // Latch ONLY a name that has a failure in the window. Otherwise a caller (or a bug) tripping
188
+ // arbitrary names would grow #latched without any ring presence to age it out — breaking the
189
+ // "memory bounded BY the window" invariant, since `size` counts only #present (#1822 MED-3).
190
+ // In practice trip() is always called right after fail() returned >= threshold, so the name
191
+ // is present; this guard just makes the bound hold unconditionally.
192
+ if (this.#present.has(taskName)) this.#latched.add(taskName);
193
+ }
194
+
195
+ succeed(taskName: string): void {
196
+ // Nothing tracked → nothing to reset (and never create an epoch entry for a name that only
197
+ // ever succeeds, which would leak one map entry per distinct successful task name).
198
+ if (!this.#present.has(taskName)) return;
199
+ // Bump the epoch: every in-window failure recorded under the old epoch stops counting, so
200
+ // the score resets to 0 in O(1). The stale ring events are reclaimed as they age out.
201
+ this.#epoch.set(taskName, (this.#epoch.get(taskName) ?? 0) + 1);
202
+ this.#live.delete(taskName);
203
+ this.#latched.delete(taskName);
204
+ }
205
+ }
206
+
207
+ export function normalizeError(taskName: string, error: unknown, fallback: OffloadErrorKind = "rejected"): OffloadError {
208
+ if (error instanceof OffloadError) return error;
209
+ const detail = error as { code?: unknown; message?: unknown } | undefined;
210
+ return new OffloadError({
211
+ kind: fallback,
212
+ taskName,
213
+ code: typeof detail?.code === "string" ? detail.code : undefined,
214
+ message: errMessage(error),
215
+ cause: error,
216
+ });
217
+ }
218
+
219
+ export function log(logger: OffloadLogger | undefined, level: keyof OffloadLogger, message: string, fields: OffloadLogFields): void {
220
+ const method = logger?.[level];
221
+ if (typeof method !== "function") return;
222
+ try {
223
+ method.call(logger, message, fields);
224
+ } catch {
225
+ // A caller-supplied transport that throws must never break the run it is describing:
226
+ // logging happens on the settle path, so an escaping throw wedges the backend (#1809 P0-1).
227
+ // There is no second transport to report this to, so it is deliberately swallowed.
228
+ }
229
+ }
230
+
231
+ export function validateTimeout(timeoutMs: number | undefined): number | undefined {
232
+ if (timeoutMs === undefined) return undefined;
233
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError("timeoutMs must be a positive finite number");
234
+ return timeoutMs;
235
+ }