@parcha/agentrun-serve 0.1.0-beta.36 → 0.1.0-beta.37

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 (325) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +158 -52
  3. package/dist/attach-conformance-cli.d.ts +1 -0
  4. package/dist/attach-conformance-cli.js +18 -0
  5. package/dist/attach-conformance.d.ts +25 -0
  6. package/dist/attach-conformance.js +343 -0
  7. package/dist/browser-cost.d.ts +1 -1
  8. package/dist/browser-live.d.ts +20 -8
  9. package/dist/browser-live.js +50 -27
  10. package/dist/cap.d.ts +0 -17
  11. package/dist/cap.js +0 -91
  12. package/dist/catalog.d.ts +1 -12
  13. package/dist/catalog.js +3 -33
  14. package/dist/cli.js +13 -4
  15. package/dist/composio-preset.d.ts +36 -0
  16. package/dist/composio-preset.js +179 -0
  17. package/dist/computer-attach.d.ts +125 -0
  18. package/dist/computer-attach.js +330 -0
  19. package/dist/computer-calls.d.ts +48 -0
  20. package/dist/computer-calls.js +126 -0
  21. package/dist/computer-channel.d.ts +57 -0
  22. package/dist/computer-channel.js +115 -0
  23. package/dist/computer-commands.d.ts +1 -1
  24. package/dist/computer-held-routes.d.ts +35 -0
  25. package/dist/computer-held-routes.js +106 -0
  26. package/dist/computer-held.d.ts +48 -0
  27. package/dist/computer-held.js +87 -0
  28. package/dist/computer-keys.d.ts +21 -1
  29. package/dist/computer-keys.js +53 -11
  30. package/dist/computer-live.d.ts +160 -0
  31. package/dist/computer-live.js +643 -0
  32. package/dist/computer-view.d.ts +13 -0
  33. package/dist/computer-view.js +50 -3
  34. package/dist/computer-viewer.d.ts +6 -0
  35. package/dist/computer-viewer.js +297 -0
  36. package/dist/computers.d.ts +33 -7
  37. package/dist/computers.js +50 -8
  38. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  39. package/dist/console/assets/index-DRN62V5v.css +1 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/faux-computers.d.ts +9 -20
  42. package/dist/faux-computers.js +53 -25
  43. package/dist/github-connection.d.ts +10 -2
  44. package/dist/github-connection.js +65 -2
  45. package/dist/github-faux.js +1 -1
  46. package/dist/graph-view.d.ts +1 -1
  47. package/dist/harness.d.ts +1 -0
  48. package/dist/harness.js +35 -1
  49. package/dist/host-tools.d.ts +1 -1
  50. package/dist/hosted-search.d.ts +5 -4
  51. package/dist/hosted-search.js +2 -7
  52. package/dist/import-sources.d.ts +10 -0
  53. package/dist/import-sources.js +44 -2
  54. package/dist/import.d.ts +3 -3
  55. package/dist/import.js +37 -6
  56. package/dist/learn/check.d.ts +4 -1
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +4 -2
  59. package/dist/learn/commit.js +5 -5
  60. package/dist/learn/folder.d.ts +6 -0
  61. package/dist/learn/folder.js +4 -1
  62. package/dist/learn/general.d.ts +66 -0
  63. package/dist/learn/general.js +73 -0
  64. package/dist/learn/grade.d.ts +4 -0
  65. package/dist/learn/grade.js +22 -1
  66. package/dist/learn/reflect.d.ts +10 -1
  67. package/dist/learn/reflect.js +14 -4
  68. package/dist/learn/skills.d.ts +33 -5
  69. package/dist/learn/skills.js +53 -7
  70. package/dist/learned-workflow.d.ts +24 -0
  71. package/dist/learned-workflow.js +66 -3
  72. package/dist/learning-batch.d.ts +283 -0
  73. package/dist/learning-batch.js +574 -0
  74. package/dist/learning-evals.d.ts +33 -0
  75. package/dist/learning-evals.js +98 -0
  76. package/dist/learning-routes.d.ts +25 -2
  77. package/dist/learning-routes.js +39 -6
  78. package/dist/learning-words.d.ts +6 -0
  79. package/dist/learning-words.js +6 -0
  80. package/dist/learning.d.ts +28 -15
  81. package/dist/learning.js +84 -44
  82. package/dist/live/stream.js +6 -3
  83. package/dist/live/translate.d.ts +4 -3
  84. package/dist/live/translate.js +8 -4
  85. package/dist/live-reach.d.ts +37 -0
  86. package/dist/live-reach.js +62 -0
  87. package/dist/mcp-gateway.d.ts +9 -0
  88. package/dist/mcp-gateway.js +60 -11
  89. package/dist/mcp-oauth.d.ts +57 -7
  90. package/dist/mcp-oauth.js +133 -18
  91. package/dist/mcp-private-hosts.d.ts +4 -4
  92. package/dist/mcp-private-hosts.js +20 -12
  93. package/dist/mcp-probe.d.ts +19 -2
  94. package/dist/mcp-probe.js +44 -9
  95. package/dist/mcp-secret-writes.js +4 -0
  96. package/dist/mcp-servers-store.d.ts +38 -15
  97. package/dist/mcp-servers-store.js +112 -20
  98. package/dist/mcp-store.d.ts +10 -4
  99. package/dist/mcp-store.js +17 -6
  100. package/dist/model-form.d.ts +26 -0
  101. package/dist/model-form.js +80 -0
  102. package/dist/model.js +23 -10
  103. package/dist/openapi.js +386 -21
  104. package/dist/page.d.ts +18 -0
  105. package/dist/page.js +48 -20
  106. package/dist/paid-calls.d.ts +1 -1
  107. package/dist/place-offers.d.ts +2 -3
  108. package/dist/place-offers.js +3 -7
  109. package/dist/place.js +1 -2
  110. package/dist/print.d.ts +15 -1
  111. package/dist/print.js +14 -3
  112. package/dist/propose.d.ts +3 -0
  113. package/dist/propose.js +13 -5
  114. package/dist/provider.js +3 -2
  115. package/dist/reflect-range.d.ts +8 -1
  116. package/dist/reflect-range.js +1 -1
  117. package/dist/run-launch.d.ts +14 -2
  118. package/dist/run-launch.js +9 -4
  119. package/dist/run-learning-served.d.ts +2 -2
  120. package/dist/run-reads-over-store.d.ts +1 -1
  121. package/dist/run-repo.d.ts +20 -0
  122. package/dist/run-repo.js +63 -0
  123. package/dist/run-timeline-served.d.ts +1 -1
  124. package/dist/run-view.d.ts +3 -3
  125. package/dist/run-view.js +14 -7
  126. package/dist/runner/adapter-loop.d.ts +23 -7
  127. package/dist/runner/adapter-loop.js +648 -62
  128. package/dist/runner/adapter-run-spec.d.ts +11 -3
  129. package/dist/runner/adapter-run-spec.js +77 -22
  130. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  131. package/dist/runner/adapters/pi-computer.js +43 -0
  132. package/dist/runner/adapters/pi.d.ts +9 -4
  133. package/dist/runner/adapters/pi.js +76 -14
  134. package/dist/runner/beside.d.ts +7 -3
  135. package/dist/runner/beside.js +21 -11
  136. package/dist/runner/claim-secrets.d.ts +4 -0
  137. package/dist/runner/claim-secrets.js +6 -1
  138. package/dist/runner/cli-run-spec.d.ts +20 -3
  139. package/dist/runner/cli-run-spec.js +113 -43
  140. package/dist/runner/commands.d.ts +3 -1
  141. package/dist/runner/commands.js +28 -3
  142. package/dist/runner/computer-channel.d.ts +34 -0
  143. package/dist/runner/computer-channel.js +61 -0
  144. package/dist/runner/conformance/harness.js +80 -14
  145. package/dist/runner/conformance/subject.d.ts +1 -1
  146. package/dist/runner/dispatch.js +3 -0
  147. package/dist/runner/end-of-run.d.ts +22 -12
  148. package/dist/runner/end-of-run.js +38 -16
  149. package/dist/runner/github-app.d.ts +2 -1
  150. package/dist/runner/github-app.js +4 -2
  151. package/dist/runner/harness-loops.js +15 -1
  152. package/dist/runner/held-run.d.ts +65 -0
  153. package/dist/runner/held-run.js +158 -0
  154. package/dist/runner/journal-kinds.d.ts +20 -1
  155. package/dist/runner/journal-kinds.js +14 -0
  156. package/dist/runner/journal-reader.d.ts +5 -4
  157. package/dist/runner/journal-reader.js +12 -10
  158. package/dist/runner/learning-ask.d.ts +7 -1
  159. package/dist/runner/learning-ask.js +21 -6
  160. package/dist/runner/learning-dispatch.d.ts +22 -0
  161. package/dist/runner/learning-dispatch.js +77 -10
  162. package/dist/runner/learning-end.d.ts +22 -1
  163. package/dist/runner/learning-end.js +92 -12
  164. package/dist/runner/learning-factory.d.ts +1 -1
  165. package/dist/runner/learning-factory.js +11 -5
  166. package/dist/runner/learning-loop.d.ts +67 -7
  167. package/dist/runner/learning-loop.js +173 -21
  168. package/dist/runner/learning-seed.d.ts +7 -0
  169. package/dist/runner/learning-seed.js +13 -0
  170. package/dist/runner/live-ticker.js +1 -0
  171. package/dist/runner/loop-contract.d.ts +8 -1
  172. package/dist/runner/loop.d.ts +5 -1
  173. package/dist/runner/loop.js +2 -1
  174. package/dist/runner/main.d.ts +13 -1
  175. package/dist/runner/main.js +27 -5
  176. package/dist/runner/mcp-claim.d.ts +10 -7
  177. package/dist/runner/mcp-claim.js +113 -24
  178. package/dist/runner/mcp-github.js +1 -1
  179. package/dist/runner/mcp-run.d.ts +5 -5
  180. package/dist/runner/mcp-run.js +15 -3
  181. package/dist/runner/metrics.d.ts +11 -2
  182. package/dist/runner/metrics.js +12 -2
  183. package/dist/runner/pr-checkout.d.ts +1 -0
  184. package/dist/runner/pr-checkout.js +1 -1
  185. package/dist/runner/reflect-hook.d.ts +18 -0
  186. package/dist/runner/reflect-hook.js +20 -8
  187. package/dist/runner/runner.d.ts +26 -0
  188. package/dist/runner/runner.js +184 -15
  189. package/dist/runner/scratch-sweep.d.ts +13 -0
  190. package/dist/runner/scratch-sweep.js +62 -0
  191. package/dist/runner/sessions.d.ts +1 -1
  192. package/dist/runner/store-port.d.ts +4 -2
  193. package/dist/runner/store-secrets.js +4 -3
  194. package/dist/runner/subagent.js +3 -1
  195. package/dist/runner/workflow-host.d.ts +6 -1
  196. package/dist/runner/workflow-host.js +1 -1
  197. package/dist/runner/workflow-loop.d.ts +1 -1
  198. package/dist/runner/workflow-spec.d.ts +14 -2
  199. package/dist/runner/workflow-spec.js +56 -20
  200. package/dist/runs-over-store.d.ts +6 -1
  201. package/dist/runs-over-store.js +38 -9
  202. package/dist/seal-key.js +3 -3
  203. package/dist/sealed-settings-store.d.ts +5 -2
  204. package/dist/sealed-settings-store.js +10 -4
  205. package/dist/secret-writes.d.ts +5 -4
  206. package/dist/secret-writes.js +5 -4
  207. package/dist/server-secrets-store.d.ts +4 -3
  208. package/dist/server-secrets-store.js +15 -9
  209. package/dist/server-secrets.js +3 -2
  210. package/dist/server.d.ts +43 -14
  211. package/dist/server.js +472 -126
  212. package/dist/settings-wake.d.ts +21 -0
  213. package/dist/settings-wake.js +59 -0
  214. package/dist/standard-webhooks.d.ts +4 -1
  215. package/dist/standard-webhooks.js +8 -4
  216. package/dist/store/command-wake.d.ts +12 -0
  217. package/dist/store/command-wake.js +37 -0
  218. package/dist/store/dialect.d.ts +6 -0
  219. package/dist/store/dialect.js +5 -0
  220. package/dist/store/index.d.ts +1 -1
  221. package/dist/store/journal/storage.d.ts +3 -2
  222. package/dist/store/journal/storage.js +13 -5
  223. package/dist/store/postgres/dialect.js +4 -0
  224. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  225. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  226. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  227. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  228. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  229. package/dist/store/schema.d.ts +1 -1
  230. package/dist/store/schema.js +77 -8
  231. package/dist/store/sqlite/run-patch.d.ts +7 -5
  232. package/dist/store/sqlite/run-patch.js +28 -13
  233. package/dist/store/sqlite/store.js +272 -54
  234. package/dist/store/store.d.ts +268 -9
  235. package/dist/store/store.js +12 -1
  236. package/dist/store-reads/cap.d.ts +1 -1
  237. package/dist/store-reads/cap.js +8 -1
  238. package/dist/store-reads/decisions.d.ts +2 -2
  239. package/dist/store-reads/decisions.js +1 -1
  240. package/dist/store-reads/import-summary.d.ts +1 -1
  241. package/dist/store-reads/journal.d.ts +5 -4
  242. package/dist/store-reads/journal.js +73 -15
  243. package/dist/store-reads/learning.d.ts +20 -4
  244. package/dist/store-reads/learning.js +74 -18
  245. package/dist/store-reads/runs.d.ts +1 -1
  246. package/dist/store-reads/workflow.d.ts +1 -1
  247. package/dist/store-view.d.ts +5 -0
  248. package/dist/store-view.js +26 -11
  249. package/dist/template-eval.js +6 -4
  250. package/dist/template-github-permissions.d.ts +22 -8
  251. package/dist/template-github-permissions.js +35 -15
  252. package/dist/timeline/timeline.d.ts +27 -0
  253. package/dist/timeline/timeline.js +10 -9
  254. package/dist/timeline/util.d.ts +4 -0
  255. package/dist/timeline/util.js +14 -0
  256. package/dist/tool-budget.d.ts +19 -7
  257. package/dist/tool-budget.js +14 -8
  258. package/dist/tool-gate.d.ts +16 -9
  259. package/dist/tool-gate.js +53 -42
  260. package/dist/tool-plane.d.ts +16 -12
  261. package/dist/tool-plane.js +9 -4
  262. package/dist/tools.d.ts +13 -4
  263. package/dist/tools.js +13 -4
  264. package/dist/trigger-adapter.d.ts +4 -0
  265. package/dist/trigger-secrets-shown.d.ts +2 -2
  266. package/dist/trigger-secrets-shown.js +1 -1
  267. package/dist/trigger-signatures.d.ts +25 -6
  268. package/dist/trigger-signatures.js +41 -7
  269. package/dist/trigger-targets.d.ts +2 -0
  270. package/dist/trigger-targets.js +1 -0
  271. package/dist/trigger-webhook.js +5 -2
  272. package/dist/triggers.d.ts +7 -3
  273. package/dist/triggers.js +35 -5
  274. package/dist/turns.js +16 -1
  275. package/dist/validate.js +11 -1
  276. package/dist/web-fetch.d.ts +1 -1
  277. package/dist/web-search.d.ts +10 -5
  278. package/dist/web-search.js +7 -6
  279. package/dist/webhooks.d.ts +145 -102
  280. package/dist/webhooks.js +559 -322
  281. package/dist/workflow/decisions.d.ts +1 -1
  282. package/dist/workflow/node-runner.d.ts +2 -1
  283. package/dist/workflow/node.d.ts +2 -1
  284. package/dist/workflow/node.js +3 -1
  285. package/dist/workflow/pi-versions.d.ts +23 -0
  286. package/dist/workflow/pi-versions.js +57 -0
  287. package/dist/workflow/record-tool.d.ts +2 -1
  288. package/dist/workflow/store.d.ts +1 -1
  289. package/dist/workflow/task.js +3 -2
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/attached-computers.d.ts +41 -0
  292. package/dist/workspace/attached-computers.js +114 -0
  293. package/dist/workspace/computer-deps.d.ts +16 -9
  294. package/dist/workspace/computer-deps.js +19 -7
  295. package/dist/workspace/computer-for-claim.d.ts +17 -8
  296. package/dist/workspace/computer-for-claim.js +62 -21
  297. package/dist/workspace/computer-hold.d.ts +11 -27
  298. package/dist/workspace/computer-hold.js +36 -56
  299. package/dist/workspace/computer-ledger.d.ts +3 -1
  300. package/dist/workspace/computer-ledger.js +4 -0
  301. package/dist/workspace/computer-mcp.d.ts +25 -0
  302. package/dist/workspace/computer-mcp.js +41 -0
  303. package/dist/workspace/computer-ports.d.ts +4 -13
  304. package/dist/workspace/computer-ports.js +4 -107
  305. package/dist/workspace/computer-script.d.ts +37 -0
  306. package/dist/workspace/computer-script.js +138 -0
  307. package/dist/workspace/executors.d.ts +1 -1
  308. package/dist/workspace/index.d.ts +4 -2
  309. package/dist/workspace/index.js +3 -1
  310. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  311. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  312. package/dist/workspace/resolve-computer.d.ts +3 -0
  313. package/dist/workspace/resolve-computer.js +8 -2
  314. package/dist/workspace/run-tools.d.ts +32 -15
  315. package/dist/workspace/run-tools.js +23 -30
  316. package/package.json +19 -16
  317. package/templates/market-monitor/agent.md +1 -1
  318. package/dist/console/assets/index-BI4Byidu.js +0 -550
  319. package/dist/console/assets/index-C19gUF2n.css +0 -1
  320. package/dist/run-db.d.ts +0 -53
  321. package/dist/run-db.js +0 -116
  322. package/dist/workflow/readers.d.ts +0 -36
  323. package/dist/workflow/readers.js +0 -145
  324. package/dist/workflow/wal.d.ts +0 -11
  325. package/dist/workflow/wal.js +0 -106
@@ -14,10 +14,20 @@ import { KINDS, withdrawnAnswers } from "./journal-kinds.js";
14
14
  import { journalEntries } from "./journal-reader.js";
15
15
  import { ClaimRefused, stopEnd } from "./loop-contract.js";
16
16
  import { isFenced } from "./store-port.js";
17
+ import { FINAL_STATES } from "../store/store.js";
18
+ import { Unanswered } from "../store/postgres/connection.js";
17
19
  import { clearWaitEnded } from "../browser-wait-ended.js";
18
20
  import { heldRedactor, processSecretRedactor } from "./redact.js";
19
21
  import { withLiveTicker } from "./live-ticker.js";
22
+ /** Tries of the re-read after a claim or release commit was answered Unanswered (the commit may have landed). */
23
+ const UNKNOWN_READS = 5;
24
+ /** Passes of the sweep after a claim answered Unanswered: the commit may still be on its way when the first read comes back
25
+ * empty, so the read is repeated, waiting twice as long each time, before the lease is left to settle it. */
26
+ const UNKNOWN_SWEEPS = 4;
20
27
  /** Most runs a runner holds at once, unless told (RunnerOptions.loops). */
28
+ /** A final run's status as its end line says it: the store holds a cancel as state 'stopped' with outcome 'cancelled', so
29
+ * the outcome tells a cancel from a person's resumable stop. */
30
+ export const endedStatus = (run) => (run.state === "stopped" && run.outcome === "cancelled" ? "cancelled" : run.state);
21
31
  export const RUNNER_LOOPS = 300;
22
32
  /** How long a claim lasts unless renewed, unless told (RunnerOptions.leaseMs). */
23
33
  export const RUNNER_LEASE_MS = 30_000;
@@ -56,7 +66,7 @@ const message = (error) => (error instanceof Error ? error.message : String(erro
56
66
  /** The run states a run patch makes final: a commit that lands one is the run's end, and its release. */
57
67
  const FINAL = new Set(["ended", "stopped", "failed"]);
58
68
  export function startRunner(options) {
59
- const { store, createLoop, name = runnerName(), loops = RUNNER_LOOPS, leaseMs = RUNNER_LEASE_MS, renewEveryMs = RUNNER_RENEW_EVERY_MS, stopMarginMs = RUNNER_STOP_MARGIN_MS, pollMs = 1_000, commandPollMs = 500, resumeTries = 3, resumeBackoffMs = 5_000, interruptBackoffMs = 1_000, endWaitMs = 5_000, drainMs = 0, memory, endRetryBackoffMs = END_RETRY_BACKOFF_MS, endRetryCapMs = END_RETRY_CAP_MS, endRetryAtCap = END_RETRY_AT_CAP, onEvent = () => { }, redact: given = processSecretRedactor(), now = Date.now, onBeat = () => { }, clock = { now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (handle) => clearTimeout(handle) }, } = options;
69
+ const { store, createLoop, name = runnerName(), loops = RUNNER_LOOPS, leaseMs = RUNNER_LEASE_MS, renewEveryMs = RUNNER_RENEW_EVERY_MS, stopMarginMs = RUNNER_STOP_MARGIN_MS, pollMs = 1_000, commandPollMs = 500, resumeTries = 3, resumeBackoffMs = 5_000, interruptBackoffMs = 1_000, unknownBackoffMs = 200, endWaitMs = 5_000, drainMs = 0, memory, endRetryBackoffMs = END_RETRY_BACKOFF_MS, endRetryCapMs = END_RETRY_CAP_MS, endRetryAtCap = END_RETRY_AT_CAP, onEvent = () => { }, redact: given = processSecretRedactor(), now = Date.now, onBeat = () => { }, clock = { now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (handle) => clearTimeout(handle) }, } = options;
60
70
  // The one instance every run's loop gets (LoopDeps.redact), able to hold what each claim opens from the store
61
71
  // (redact.ts holdClaimed): a stored key is cut wherever a key of the runner's environment is.
62
72
  const redact = heldRedactor(given);
@@ -87,6 +97,42 @@ export function startRunner(options) {
87
97
  // A listener's throw is its own.
88
98
  }
89
99
  };
100
+ /** Each run's start line in flight, so its end line (announceEnd) never comes before it. */
101
+ const startLines = new Map();
102
+ /** A run's start, said once: only its first claim (from queued) says it, so a claim taken over after a lost one, or a
103
+ * resume of a parked run, says nothing. Said with the run's agent and its revision's kind, read now. */
104
+ const announceStart = (claim) => {
105
+ if (claim.from !== "queued" || !store.runs.get || !store.agents)
106
+ return Promise.resolve();
107
+ const said = (async () => {
108
+ const run = await store.runs.get(claim.runId);
109
+ if (!run)
110
+ return;
111
+ const revision = await store.agents.revision(run.revisionId);
112
+ emit({ type: "started", runId: claim.runId, agent: run.agentId, kind: revision?.kind ?? "unknown" });
113
+ })().catch(() => undefined);
114
+ startLines.set(claim.runId, said);
115
+ // Once said the entry has done its work: a run another runner ends would otherwise leave it here for good.
116
+ void said.then(() => { if (startLines.get(claim.runId) === said)
117
+ startLines.delete(claim.runId); });
118
+ return said;
119
+ };
120
+ /** A run's end, said once its row is final: read after the run's release, so a stop that only released it (a shutdown,
121
+ * a lost claim: the run still running) says nothing. */
122
+ const announceEnd = async (claim) => {
123
+ if (!store.runs.get)
124
+ return;
125
+ try {
126
+ await startLines.get(claim.runId);
127
+ const run = await store.runs.get(claim.runId);
128
+ if (!run || !FINAL_STATES.includes(run.state))
129
+ return;
130
+ emit({ type: "ended", runId: claim.runId, agent: run.agentId, status: endedStatus(run), costUsd: run.costUsd === null || run.costUsd === undefined ? null : Number(run.costUsd.toFixed(6)) });
131
+ }
132
+ catch {
133
+ // A line that could not be read is not said; the run's end stands.
134
+ }
135
+ };
90
136
  /** Every run this runner claimed whose loop has not settled, lost ones included (they still take a loop's place). */
91
137
  const runs = new Map();
92
138
  /** A lost claim's loop that had not settled when its run was claimed again (its place in `runs` taken by the new one):
@@ -102,6 +148,8 @@ export function startRunner(options) {
102
148
  let killed = false;
103
149
  let pollTimer;
104
150
  let commandTimer;
151
+ /** Stops listening for written commands (store.watchCommands); set once the runner has started. */
152
+ let unwatchCommands;
105
153
  let polling = false;
106
154
  /** The run's journal with this runner's fence on its one write: after the claim is lost, commit throws ClaimLost. A
107
155
  * commit that lands a final run patch (the loop's own end, which is the run's release) calls `ended` at once: from
@@ -164,7 +212,10 @@ export function startRunner(options) {
164
212
  held.abort.abort(new ClaimLost(`run ${held.claim.runId}: claim lost (${why})`));
165
213
  };
166
214
  const stopLoop = (held, reason) => {
167
- held.stopping = true;
215
+ // A person's stop of a run that keeps its computer for its owner ends its agent only: its rows (the owner's calls,
216
+ // the release, a cancel) are still handed on until the computer is let go.
217
+ if (!held.loop.keepsComputer?.(reason))
218
+ held.stopping = true;
168
219
  held.loop.stop(reason).catch((error) => emit({ type: "error", runId: held.claim.runId, step: "stop", message: message(error) }));
169
220
  };
170
221
  /** Every held claim renewed in one transaction (store.renewMany), never one per run: a claim answered Fenced is lost,
@@ -232,7 +283,8 @@ export function startRunner(options) {
232
283
  if (row.kind === "stop" || row.kind === "cancel") {
233
284
  held.cursor = Math.max(held.cursor, row.id);
234
285
  stopLoop(held, { kind: "command", commandId: row.id, ...(row.kind === "cancel" ? { cancel: true } : {}) });
235
- break;
286
+ // A stop that keeps the run's computer leaves the rows after it to be handed on (the loop head ends the rest).
287
+ continue;
236
288
  }
237
289
  const outcome = COMMAND_KINDS.has(row.kind) ? await held.loop.command(row) : { refused: `no command is of kind ${JSON.stringify(row.kind)}` };
238
290
  if (held.sealed || killed)
@@ -257,6 +309,12 @@ export function startRunner(options) {
257
309
  held.delivering = false;
258
310
  if (held.inFlight === delivery)
259
311
  held.inFlight = undefined;
312
+ // A row written while this delivery ran: read again now (deliver itself checks the run still takes rows).
313
+ if (held.deliverAgain) {
314
+ held.deliverAgain = false;
315
+ if (delivering())
316
+ void deliver(held);
317
+ }
260
318
  }
261
319
  })();
262
320
  held.inFlight = delivery;
@@ -375,8 +433,9 @@ export function startRunner(options) {
375
433
  emit({ type: "refused", runId: claim.runId, commandId: row.id, reason });
376
434
  }
377
435
  await store.flush();
378
- await store.release(claim, {});
436
+ await release(claim, {});
379
437
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: "stopped" });
438
+ await announceEnd(claim);
380
439
  };
381
440
  /**
382
441
  * A stopped end that may withdraw a call, refused (EndNotWithdrawn): counted on its stop row's tries, said by the run's
@@ -401,7 +460,7 @@ export function startRunner(options) {
401
460
  const wait = Math.min(endRetryBackoffMs * 2 ** (tries - 1), endRetryCapMs);
402
461
  emit({ type: "error", runId: claim.runId, step: "end", message: `run ${claim.runId}: its end with a withdrawal was refused (try ${tries}); retrying in ${wait} ms: ${why}` });
403
462
  await store.flush();
404
- await store.release(claim, { backoffUntil: now() + wait });
463
+ await release(claim, { backoffUntil: now() + wait });
405
464
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: "interrupted" });
406
465
  };
407
466
  /** Whether the run under `claim` never started: its journal has no conversation yet, so no input of it went out. A
@@ -418,6 +477,8 @@ export function startRunner(options) {
418
477
  * so no turn, model request or tool runs on a run that is stopping. */
419
478
  const endRetried = async (claim, stop) => {
420
479
  try {
480
+ // A run stopped before any loop started still has its one start line, ahead of its end.
481
+ await announceStart(claim);
421
482
  if (await endStopped(claim, stop))
422
483
  await releaseStopped(claim, stop);
423
484
  }
@@ -491,10 +552,12 @@ export function startRunner(options) {
491
552
  interruptedInARow.set(claim.runId, inARow);
492
553
  else
493
554
  interruptedInARow.delete(claim.runId);
494
- await store.release(claim, end.state === "parked" && end.wakeAt !== undefined ? { wakeAt: end.wakeAt }
555
+ await release(claim, end.state === "parked" && end.wakeAt !== undefined ? { wakeAt: end.wakeAt }
495
556
  : inARow > 0 ? { backoffUntil: Date.now() + interruptBackoffMs * 2 ** Math.min(inARow - 1, 6) }
496
557
  : {});
497
558
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: end.state });
559
+ if (end.state === "ended" || end.state === "stopped" || end.state === "failed")
560
+ await announceEnd(claim);
498
561
  }
499
562
  catch (error) {
500
563
  emit({ type: "error", runId: claim.runId, step: isFenced(error) ? "release (fenced)" : "release", message: message(error) });
@@ -527,16 +590,16 @@ export function startRunner(options) {
527
590
  await store.take(claim, woke.id, "refused", reason);
528
591
  emit({ type: "refused", runId: claim.runId, commandId: woke.id, reason });
529
592
  await store.flush();
530
- await store.release(claim, { state: "parked" });
593
+ await release(claim, { state: "parked" });
531
594
  }
532
595
  else {
533
596
  await store.flush();
534
- await store.release(claim, { state: "parked", backoffUntil: Date.now() + resumeBackoffMs * 2 ** (tries - 1) });
597
+ await release(claim, { state: "parked", backoffUntil: Date.now() + resumeBackoffMs * 2 ** (tries - 1) });
535
598
  }
536
599
  }
537
600
  else {
538
601
  await store.flush();
539
- await store.release(claim, { state: "parked" });
602
+ await release(claim, { state: "parked" });
540
603
  }
541
604
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: "parked" });
542
605
  };
@@ -563,7 +626,7 @@ export function startRunner(options) {
563
626
  },
564
627
  redact,
565
628
  });
566
- const held = { claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false, mib };
629
+ const held = { claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false, deliverAgain: false, mib };
567
630
  heldNow = held;
568
631
  // The loop's own end landed: the run is ending from here, its teardown included (no renew, no lost claim).
569
632
  ending = () => {
@@ -573,6 +636,7 @@ export function startRunner(options) {
573
636
  runs.set(claim.runId, held);
574
637
  armDeadline(held, sentAt + leaseMs - stopMarginMs);
575
638
  emit({ type: "claimed", claim });
639
+ void announceStart(claim);
576
640
  held.done = (async () => {
577
641
  let end;
578
642
  let threw = false;
@@ -590,6 +654,76 @@ export function startRunner(options) {
590
654
  // The claim's first delivery: deps.delivered resolves once it has handed on every untaken row it read.
591
655
  void deliver(held).finally(firstDelivered);
592
656
  };
657
+ /** The claims this runner holds in the store, read back after a commit was answered Unanswered (it may have landed):
658
+ * bounded tries with a doubling wait; undefined when none answered, and the lease settles it then. */
659
+ const readClaims = async () => {
660
+ for (let attempt = 0; attempt < UNKNOWN_READS && !killed && Date.now() < recoverBy; attempt++) {
661
+ try {
662
+ return await store.runs.claimsOf(name);
663
+ }
664
+ catch (error) {
665
+ emit({ type: "error", step: "claim re-read", message: message(error) });
666
+ // Never past the close's window: a recovery cannot hold a shutdown beyond the stop grace.
667
+ await new Promise((resolve) => setTimeout(resolve, Math.min(unknownBackoffMs * 2 ** attempt, Math.max(0, recoverBy - Date.now()))));
668
+ }
669
+ }
670
+ return undefined;
671
+ };
672
+ /** Until close() sets it, no bound: the time by which every re-read after an Unanswered commit must be over, the same
673
+ * window as the close's stop (the lease less its margin), so a shutdown is never held longer than its grace allows. */
674
+ let recoverBy = Infinity;
675
+ /** The claims (`runId:epoch`) an ending with no loop is writing (endRetried): they live in `endings`, not in `runs`, so the
676
+ * sweep must not take them for claims nothing holds. */
677
+ const endingClaims = new Set();
678
+ /** store.release, but a release answered Unanswered (it may or may not have landed) is read back: a claim still held at
679
+ * its epoch is released again (fenced on that epoch, as every write is), one gone is done. */
680
+ const release = async (claim, options) => {
681
+ try {
682
+ await store.release(claim, options);
683
+ }
684
+ catch (error) {
685
+ if (!(error instanceof Unanswered))
686
+ throw error;
687
+ for (let attempt = 0; attempt < UNKNOWN_READS; attempt++) {
688
+ const mine = await readClaims();
689
+ if (!mine)
690
+ throw error;
691
+ if (!mine.some((held) => held.runId === claim.runId && held.epoch === claim.epoch))
692
+ return;
693
+ try {
694
+ await store.release(claim, options);
695
+ return;
696
+ }
697
+ catch (again) {
698
+ if (!(again instanceof Unanswered))
699
+ throw again;
700
+ }
701
+ }
702
+ throw error;
703
+ }
704
+ };
705
+ /** A claim answered Unanswered may have landed, its run held under this runner with no loop on it until the lease ran
706
+ * out: read back, and every claim of this runner's that nothing here holds (nor `known`, claims of this poll not yet
707
+ * held) is released at once, fenced on its epoch, for any runner to take. */
708
+ const giveBackUnknown = async (known) => {
709
+ // Several passes: the commit may land after a read that found nothing (it can still be pending on its old connection).
710
+ for (let pass = 0; pass < UNKNOWN_SWEEPS; pass++) {
711
+ if (pass > 0) {
712
+ if (closed || killed)
713
+ return;
714
+ await new Promise((resolve) => setTimeout(resolve, Math.min(unknownBackoffMs * 2 ** pass, Math.max(0, recoverBy - Date.now()))));
715
+ }
716
+ const mine = await readClaims();
717
+ if (!mine)
718
+ return;
719
+ for (const claim of mine) {
720
+ if (runs.get(claim.runId)?.claim.epoch === claim.epoch || endingClaims.has(`${claim.runId}:${claim.epoch}`) || known.some((k) => k.runId === claim.runId && k.epoch === claim.epoch))
721
+ continue;
722
+ emit({ type: "error", runId: claim.runId, step: "claim", message: `run ${claim.runId}: a claim answered Unanswered had landed (epoch ${claim.epoch}); given back` });
723
+ await release(claim, {}).catch((error) => emit({ type: "error", runId: claim.runId, step: "claim give-back", message: message(error) }));
724
+ }
725
+ }
726
+ };
593
727
  const claimMore = async () => {
594
728
  if (polling || closed || killed)
595
729
  return;
@@ -603,7 +737,15 @@ export function startRunner(options) {
603
737
  // on its own (claimByMemory).
604
738
  const sentAt = clock.now();
605
739
  const weights = new Map();
606
- const claims = memory ? await claimByMemory(memory, free, weights) : await store.runs.claimMany(name, free, { leaseMs });
740
+ let claims;
741
+ try {
742
+ claims = memory ? await claimByMemory(memory, free, weights) : await store.runs.claimMany(name, free, { leaseMs });
743
+ }
744
+ catch (error) {
745
+ if (error instanceof Unanswered)
746
+ await giveBackUnknown([]);
747
+ throw error;
748
+ }
607
749
  // A claim whose run must only end, with no loop (endRetried), so no turn, model request or tool runs on it:
608
750
  // - a run stopped or cancelled while it had not started: claimed from queued, or claimed from running when an earlier
609
751
  // claim was lost before the run's journal had anything (its runner gone before it wrote a word). Nothing of it
@@ -618,9 +760,14 @@ export function startRunner(options) {
618
760
  const stop = endingRow((rows.get(claim.runId) ?? []).filter((row) => row.takenAt === null));
619
761
  const endsOnly = stop !== undefined && (claim.from === "queued" || stop.tries > 0 || (claim.from === "running" && (await neverStarted(claim))));
620
762
  if (stop && endsOnly && !closed && !killed && !runs.has(claim.runId)) {
763
+ const key = `${claim.runId}:${claim.epoch}`;
764
+ endingClaims.add(key);
621
765
  const ending = endRetried(claim, stop);
622
766
  endings.add(ending);
623
- void ending.finally(() => endings.delete(ending));
767
+ void ending.finally(() => {
768
+ endings.delete(ending);
769
+ endingClaims.delete(key);
770
+ });
624
771
  continue;
625
772
  }
626
773
  const before = runs.get(claim.runId);
@@ -628,7 +775,7 @@ export function startRunner(options) {
628
775
  // Closed while the batch was claimed (or a run this runner still holds, which a claim cannot be): given back.
629
776
  if (before && !before.fence.lost)
630
777
  emit({ type: "error", runId: claim.runId, step: "claim", message: "claimed a run this runner still holds" });
631
- await store.release(claim, {}).catch(() => { });
778
+ await release(claim, {}).catch(() => { });
632
779
  continue;
633
780
  }
634
781
  try {
@@ -644,7 +791,7 @@ export function startRunner(options) {
644
791
  emit({ type: "error", runId: claim.runId, step: "create loop", message: message(error) });
645
792
  await store.runs.update(claim, { state: "failed", summary: redact(message(error)) }).catch(() => { });
646
793
  await store.flush().catch(() => { });
647
- await store.release(claim, {}).catch(() => { });
794
+ await release(claim, {}).catch(() => { });
648
795
  }
649
796
  }
650
797
  }
@@ -680,6 +827,8 @@ export function startRunner(options) {
680
827
  }
681
828
  catch (error) {
682
829
  emit({ type: "error", runId, step: "claim", message: message(error) });
830
+ if (error instanceof Unanswered)
831
+ await giveBackUnknown(claims);
683
832
  break;
684
833
  }
685
834
  if (!claim)
@@ -708,6 +857,19 @@ export function startRunner(options) {
708
857
  };
709
858
  poll();
710
859
  commandTimer = setTimeout(deliverAll, commandPollMs);
860
+ // A command written for a run this runner holds is handed on now, not at the next poll. A delivery already in flight
861
+ // marks the run, and one more delivery follows its end, so a row written mid-delivery is never left to the next poll.
862
+ unwatchCommands = store.watchCommands(({ runId, what }) => {
863
+ if (what !== "written" || !delivering())
864
+ return;
865
+ const held = runs.get(runId);
866
+ if (held === undefined)
867
+ return;
868
+ if (held.delivering)
869
+ held.deliverAgain = true;
870
+ else
871
+ void deliver(held);
872
+ });
711
873
  /** The untaken stop or cancel row each of `going` ends on (endingRow: a cancel before a stop), past its cursor, by run id:
712
874
  * the close's one read of their rows (store.commandsOf), after the deliveries in flight. The whole of it is bounded by
713
875
  * the stop margin, so a store that stalls never holds the shutdown: a read that fails or runs past it is said, and those
@@ -757,6 +919,7 @@ export function startRunner(options) {
757
919
  const stopTimers = () => {
758
920
  clearTimeout(pollTimer);
759
921
  clearTimeout(commandTimer);
922
+ unwatchCommands?.();
760
923
  clearInterval(renewTimer);
761
924
  for (const held of runs.values())
762
925
  clock.clearTimeout(held.deadline);
@@ -772,7 +935,12 @@ export function startRunner(options) {
772
935
  // A claim the poll already has in flight lands first: one it makes now is given back at once (claimMore, closed),
773
936
  // all before close resolves, so nothing is claimed by this runner after it (a raise sent then wakes no claim here).
774
937
  draining = drainMs > 0;
775
- await claiming;
938
+ // A claim recovery under way (re-reads after an Unanswered commit) is bound by the close's own window: past it the
939
+ // close goes on to stop the loops, and the lease settles what the recovery had not.
940
+ recoverBy = Date.now() + leaseMs - stopMarginMs;
941
+ let recoverTimer;
942
+ await Promise.race([claiming, new Promise((resolve) => (recoverTimer = setTimeout(resolve, Math.max(0, recoverBy - Date.now()))))]);
943
+ clearTimeout(recoverTimer);
776
944
  // The drain: each held run goes on to its own end (an answer, a park, a person's stop: their commands still reach
777
945
  // them), its claims renewed, for up to drainMs; a turn in flight then finishes, never cut and paid again on the
778
946
  // resume. Whatever is still going at the bound is stopped below, for a shutdown, where it can resume.
@@ -788,6 +956,7 @@ export function startRunner(options) {
788
956
  // One window for the stop after the drain, the one runnerCloseBoundMs counts (the lease less its margin): the read
789
957
  // below and the loops' stop share it, so the close is never longer than a deployment's stop grace allows for.
790
958
  const stopBy = Date.now() + leaseMs - stopMarginMs;
959
+ recoverBy = stopBy;
791
960
  // A stop or cancel a person sent before the close is the run's end, never a resume: one no delivery has handed on
792
961
  // yet (the command poll's tick had not come) is read here, once, for every run still going, and stops its loop as
793
962
  // its delivery would. Its end is in the store when the close is done, and the next start never resumes the turn.
@@ -0,0 +1,13 @@
1
+ import { type Store } from "../store/index.js";
2
+ /** Most run folders one start sweeps (kept folders do not count): what is left past it is swept at the next start. */
3
+ export declare const SCRATCH_SWEEP_LIMIT = 500;
4
+ export type ScratchSwept = {
5
+ readonly examined: number;
6
+ readonly swept: number;
7
+ readonly kept: number;
8
+ readonly failed: number;
9
+ };
10
+ export declare function sweepEndedScratch(store: Pick<Store, "runs">, dataDir: string, options?: {
11
+ log?: (line: string) => void;
12
+ limit?: number;
13
+ }): Promise<ScratchSwept>;
@@ -0,0 +1,62 @@
1
+ // A runner's start sweep of the scratch folders of runs that have ended (`<data>/scratch/<agent>/<run>`). A CLI run's
2
+ // files on a runner (its harness's home and session state) go at its claims' ends (cli-run-spec.ts sweepScratch), and a
3
+ // next claim sweeps what a killed claim left; a run that ends after its runner died has no next claim, so its folders stay
4
+ // until this sweep, at the next start of a runner on the data directory, takes them. It reads each run's row: a folder is
5
+ // swept only for a run the store says is final, and only the claims at or below the row's epoch (a follow-up that reopened
6
+ // the run claims above it, and its folder is never touched). A run that is not final, one the store has no row for, and a
7
+ // folder whose name is no run id stay. Bounded by `limit` run folders swept (or failed): a folder that stays costs one
8
+ // row read and never counts, so retained folders in front of an ended run cannot hide it. Logged.
9
+ import { readdir } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { FINAL_STATES } from "../store/index.js";
12
+ import { sweepScratch } from "./cli-run-spec.js";
13
+ /** Most run folders one start sweeps (kept folders do not count): what is left past it is swept at the next start. */
14
+ export const SCRATCH_SWEEP_LIMIT = 500;
15
+ const words = (error) => error?.message ?? String(error);
16
+ const names = (folder) => readdir(folder).catch((error) => {
17
+ if (error.code === "ENOENT")
18
+ return [];
19
+ throw error;
20
+ });
21
+ export async function sweepEndedScratch(store, dataDir, options = {}) {
22
+ const log = options.log ?? (() => { });
23
+ const limit = options.limit ?? SCRATCH_SWEEP_LIMIT;
24
+ const root = join(dataDir, "scratch");
25
+ let examined = 0;
26
+ let swept = 0;
27
+ let kept = 0;
28
+ let failed = 0;
29
+ try {
30
+ outer: for (const agent of await names(root)) {
31
+ const agentFolder = join(root, agent);
32
+ for (const run of await names(agentFolder)) {
33
+ if (swept + failed >= limit) {
34
+ log(`scratch sweep: stopped after ${limit} run folders swept; the rest is swept at the next start`);
35
+ break outer;
36
+ }
37
+ examined += 1;
38
+ try {
39
+ const row = await store.runs.get(run);
40
+ if (!row || !FINAL_STATES.includes(row.state)) {
41
+ kept += 1;
42
+ continue;
43
+ }
44
+ const harnesses = join(agentFolder, run, "harness");
45
+ await sweepScratch(harnesses, row.epoch, [harnesses, join(agentFolder, run), agentFolder]);
46
+ swept += 1;
47
+ }
48
+ catch (error) {
49
+ failed += 1;
50
+ log(`scratch sweep: run folder ${run} of ${agent} could not be swept: ${words(error)}`);
51
+ }
52
+ }
53
+ }
54
+ }
55
+ catch (error) {
56
+ failed += 1;
57
+ log(`scratch sweep: the scratch folder could not be read: ${words(error)}`);
58
+ }
59
+ if (swept > 0 || failed > 0)
60
+ log(`scratch sweep: ${swept} ended run${swept === 1 ? "" : "s"}' folders swept, ${kept} kept, ${failed} failed`);
61
+ return { examined, swept, kept, failed };
62
+ }
@@ -1,4 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type Harness } from "@earendil-works/pi-durable";
3
3
  import { type SessionStore } from "@parcha/agentrun-kernel";
4
4
  import { type Store } from "../store/store.js";
@@ -1,6 +1,8 @@
1
1
  import { type Store } from "../store/store.js";
2
- export type RunnerStore = Pick<Store, "claim" | "renew" | "renewMany" | "release" | "journal" | "flush" | "commands" | "commandsOf" | "take" | "retry"> & {
3
- readonly runs: Pick<Store["runs"], "claimMany" | "claimable" | "update"> & Partial<Pick<Store["runs"], "launch">>;
2
+ export type RunnerStore = Pick<Store, "claim" | "renew" | "renewMany" | "release" | "journal" | "flush" | "commands" | "commandsOf" | "take" | "retry" | "watchCommands"> & {
3
+ readonly runs: Pick<Store["runs"], "claimMany" | "claimable" | "claimsOf" | "update"> & Partial<Pick<Store["runs"], "launch" | "get">>;
4
+ /** The revision's kind, read for a run's start line (runner.ts). A store without it (a test's) says no start or end line. */
5
+ readonly agents?: Pick<Store["agents"], "revision">;
4
6
  /** The runs' live view (run_live): the runner's live ticker writes each run's held state there. A store without it (a
5
7
  * test's) has no live view. */
6
8
  readonly live?: Store["live"];
@@ -5,9 +5,10 @@
5
5
  // echoes it back. One read of the store across all its planes (store.sealedSecrets): tool, model, computer and Archil keys
6
6
  // (sealed_keys); MCP credentials, their headers' values and OAuth tokens and client secret (mcp_servers), and a sign-in in
7
7
  // flight (mcp_oauth_pending); each trigger source's settings, a webhook trigger's signing secret and the GitHub App's key
8
- // and webhook secret among them, and the outbound webhook's signing secret (trigger_settings), but a field its source marks public; browser sign-in pointers, live
9
- // and forgotten; live viewer tokens; a launch's sealed part. Beside the store, what the data directory keeps where the
10
- // runner shares it (server-secrets.ts besideTheStore: the owner's API token and the sign-in session secret). Each value in every spelling the server's list has
8
+ // and webhook secret among them, and the outbound webhook's signing secret, each it held before too (trigger_settings),
9
+ // but a field its source marks public; browser sign-in pointers, live and forgotten; live viewer tokens; a launch's sealed
10
+ // part. Beside the store, what the data directory keeps where the runner shares it (server-secrets.ts besideTheStore: the
11
+ // owner's API token and the sign-in session secret). Each value in every spelling the server's list has
11
12
  // (standard-webhooks.ts secretForms), a PEM key whole and line by line. A value that does not open under the runner's key
12
13
  // is left out: the store never holds one in the clear, and nothing of this runner can be handed it.
13
14
  import { unseal } from "../sealing.js";
@@ -1,6 +1,7 @@
1
1
  import { configure, defineTool, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
2
2
  import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
3
3
  import { ASK_TOOL } from "../tools.js";
4
+ import { durableWait } from "../workflow/pi-versions.js";
4
5
  import { HOST_TOOL_OUTPUT } from "./adapters/pi.js";
5
6
  import { cutAtLimit } from "./loop-contract.js";
6
7
  import { PI_STOP } from "./pi-stop.js";
@@ -164,7 +165,8 @@ export function subagentTool(options) {
164
165
  if (!handle)
165
166
  return { ...fail("subagent: its conversation could not be opened. Nothing ran."), details };
166
167
  const submission = await handle.submit({ type: "input", content: args.prompt, requestId: `subagent:${String(api.taskId)}` }, context);
167
- const settled = await submission.wait(context);
168
+ // Never on the call's signal (durableWait): a stop while it registers rejects this wait, never one unhandled.
169
+ const settled = await durableWait((at) => submission.wait(at), context);
168
170
  if (settled.status === "done" && settled.answer !== undefined) {
169
171
  const answer = await api.commit((tx) => tx.entry(settled.answer), context);
170
172
  const message = answer?.model?.findLast((each) => each.role === "assistant");
@@ -33,6 +33,11 @@ export interface DecisionDriver {
33
33
  /** Resolves once the driver's commits so far are durable (a request it ended, before the run parks on it). */
34
34
  flush(): Promise<void>;
35
35
  }
36
+ /** What a held call's wrapper asks of the DSL driver: its poll window moved back by the time the run was held for a raise
37
+ * of its cap (dsl recovery/driver.ts holdPoll). */
38
+ export interface PollDriver {
39
+ holdPoll?(executionPath: unknown, ms: number, hold: string): void;
40
+ }
36
41
  /** The run's spend cap over the workflow's adapters (app.ts's budget: stepped/failing/capStopped and the decision cap),
37
42
  * injected so this module holds no money of its own. Each wrapper is applied to its adapter where app.ts applied it; a run
38
43
  * with no cap (a test, or before the cap is wired) passes none and the adapters run unwrapped. `held` is a call node's
@@ -42,7 +47,7 @@ export interface WorkflowCap {
42
47
  node<F>(fn: F): F;
43
48
  /** stepped(failing(·)): a call node, before the driver admits its effect: it waits for a raise on a held effect and
44
49
  * goes again. */
45
- effect<F>(fn: F): F;
50
+ effect<F>(fn: F, driver?: PollDriver): F;
46
51
  /** A call node's effect once the driver has admitted it: held through the kernel cap, run, and settled. Absent: the
47
52
  * effect runs as given. */
48
53
  admittedEffect?<F>(fn: F): F;
@@ -74,7 +74,7 @@ export function workflowHost(deps) {
74
74
  return { deps: {
75
75
  ...recovered,
76
76
  runNode: cap.node(recovered.runNode),
77
- runEffect: cap.effect(recovered.runEffect),
77
+ runEffect: cap.effect(recovered.runEffect, driver),
78
78
  ...(recovered.runJudge ? { runJudge: cap.judge(recovered.runJudge, driver) } : {}),
79
79
  onEvent,
80
80
  ...(cap.held ? { held: (path) => cap.held(path) } : {}),
@@ -1,4 +1,4 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type Extension, Harness } from "@earendil-works/pi-durable";
3
3
  import type { Models } from "@earendil-works/pi-ai";
4
4
  import type { Workflow } from "@parcha/agentrun-dsl";
@@ -2,7 +2,7 @@ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
2
  import { type DecisionProvider, type LoadImage, type Workflow } from "@parcha/agentrun-dsl";
3
3
  import { type BeforeRequest, type Wire } from "@parcha/agentrun-kernel";
4
4
  import { type ProviderPolicy, type ProxyUsage } from "@parcha/agentrun-kernel/host";
5
- import { type CapModel } from "@parcha/agentrun-kernel/kernel/cap";
5
+ import { type CapModel, type RunDecisions } from "@parcha/agentrun-kernel/kernel/cap";
6
6
  import { type Tier } from "../model.js";
7
7
  import { deniedText } from "../refusal-words.js";
8
8
  import { type PaidBooking } from "../paid-calls.js";
@@ -85,7 +85,7 @@ export declare function workflowSpecOf(deps: WorkflowSpecDeps): (claim: {
85
85
  * parkAtCap. It still returns the refusal, so the proxy refuses the request and the node's turn ends. */
86
86
  export declare function parkOnRefusal(before: BeforeRequest, hooks: Pick<WorkflowHostHooks, "park" | "paused" | "pause">, flight?: EffectsInFlight, steps?: OpenSteps): BeforeRequest;
87
87
  /** The workflow's steps under way, by label (the workflow's node.start/node.end, through the host): `only` is the label
88
- * of the one step open, else undefined (none, or several at once). */
88
+ * of the one step open (a map's several items open at once are one label), else undefined (none, or different steps at once). */
89
89
  export interface OpenSteps {
90
90
  start(label: string): void;
91
91
  end(label: string): void;
@@ -169,6 +169,18 @@ type CallPolicy = (tool: string) => Promise<{
169
169
  * as an EffectFailure in those words, so the call node fails and the run with it in the tool's words. Applied outside
170
170
  * the cap's own effect wrapper, on the outcome it returns. */
171
171
  export declare function failingEffects(cap: WorkflowCap): WorkflowCap;
172
+ /** A decision under the run's cap with no DSL driver around it (no request committed, none asked again): both halves of
173
+ * decisionJudging in one, `before` over `admitted`. It prices the request as main does (holdOf), admits it through the
174
+ * kernel cap, asks the judge and settles the hold at what the answer charged; a refusal for room parks the run through
175
+ * the hook, one for no price fails it, and a price the catalog could not read fails the decision node unsent.
176
+ * learned-workflow.ts wraps a learned workflow's decisions in it (LS-07), over the agent run's ledger.decisions: a
177
+ * learned_workflow call is never run again. */
178
+ export declare function decisionJudge<F>(inner: F, deps: {
179
+ getCap: () => RunDecisions | undefined;
180
+ providers: DecisionProviders;
181
+ park: (refusal: CapRefusal) => void;
182
+ hooks?: Pick<WorkflowHostHooks, "paused" | "pause">;
183
+ }): F;
172
184
  /** The tools the workflow may call, for the host to register. */
173
185
  /** The tools a workflow's model node takes on the runner: main's NODE_TOOLS (tools.ts) that bind through a ToolHost alone.
174
186
  * Its file tools (read, write, edit) need the run's Workspace and its browser a computer, which the workflow loop does not