@parcha/agentrun-serve 0.1.0-beta.44 → 0.1.0-beta.46

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 (350) hide show
  1. package/CHANGELOG.md +148 -5
  2. package/README.md +385 -305
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +62 -19
  28. package/dist/composio-preset.js +69 -7
  29. package/dist/composio-triggers.d.ts +14 -0
  30. package/dist/composio-triggers.js +79 -15
  31. package/dist/computer-attach.d.ts +40 -5
  32. package/dist/computer-attach.js +130 -15
  33. package/dist/computer-keys.d.ts +3 -0
  34. package/dist/computer-keys.js +7 -1
  35. package/dist/computer-live.js +3 -2
  36. package/dist/computers.d.ts +21 -10
  37. package/dist/computers.js +39 -28
  38. package/dist/console/assets/index-C2MYaUBa.css +1 -0
  39. package/dist/console/assets/index-CZZeCReB.js +701 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/decisions.d.ts +1 -1
  42. package/dist/dial-relay.d.ts +29 -0
  43. package/dist/dial-relay.js +94 -0
  44. package/dist/email/tools.js +10 -5
  45. package/dist/env-proxy.d.ts +2 -0
  46. package/dist/env-proxy.js +35 -0
  47. package/dist/errors.d.ts +3 -1
  48. package/dist/errors.js +7 -4
  49. package/dist/faux-computers.d.ts +8 -2
  50. package/dist/faux-computers.js +83 -6
  51. package/dist/harness-archive.d.ts +67 -0
  52. package/dist/harness-archive.js +177 -0
  53. package/dist/harness-goose.d.ts +34 -0
  54. package/dist/harness-goose.js +87 -0
  55. package/dist/harness-install.d.ts +21 -0
  56. package/dist/harness-install.js +24 -11
  57. package/dist/harness-opencode/adapter.js +1 -1
  58. package/dist/harness-table.d.ts +9 -1
  59. package/dist/harness-table.js +20 -3
  60. package/dist/harness.d.ts +1 -2
  61. package/dist/harness.js +3 -4
  62. package/dist/host.js +2 -1
  63. package/dist/import.d.ts +10 -0
  64. package/dist/import.js +28 -8
  65. package/dist/key-check.js +3 -0
  66. package/dist/learn/audit.d.ts +6 -6
  67. package/dist/learn/audit.js +3 -7
  68. package/dist/learn/check.d.ts +23 -89
  69. package/dist/learn/check.js +57 -335
  70. package/dist/learn/commit.d.ts +63 -90
  71. package/dist/learn/commit.js +124 -316
  72. package/dist/learn/compile.d.ts +53 -50
  73. package/dist/learn/compile.js +89 -104
  74. package/dist/learn/corrections.d.ts +13 -0
  75. package/dist/learn/corrections.js +23 -0
  76. package/dist/learn/delete.d.ts +5 -5
  77. package/dist/learn/delete.js +8 -10
  78. package/dist/learn/folder.d.ts +35 -47
  79. package/dist/learn/folder.js +118 -134
  80. package/dist/learn/index.d.ts +3 -5
  81. package/dist/learn/index.js +6 -9
  82. package/dist/learn/learning.sh +45 -15
  83. package/dist/learn/promote.d.ts +23 -5
  84. package/dist/learn/promote.js +40 -2
  85. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  86. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  87. package/dist/learn/workflow-nodes.js +1 -1
  88. package/dist/learned-workflow.js +2 -2
  89. package/dist/learning-cost.d.ts +38 -24
  90. package/dist/learning-cost.js +41 -24
  91. package/dist/learning-routes.d.ts +91 -170
  92. package/dist/learning-routes.js +183 -421
  93. package/dist/learning-run.d.ts +19 -40
  94. package/dist/learning-run.js +23 -93
  95. package/dist/learning-setting.d.ts +21 -10
  96. package/dist/learning-setting.js +47 -11
  97. package/dist/learning-words.d.ts +28 -74
  98. package/dist/learning-words.js +64 -162
  99. package/dist/learning.d.ts +61 -392
  100. package/dist/learning.js +101 -651
  101. package/dist/live-reach.d.ts +25 -2
  102. package/dist/live-reach.js +46 -4
  103. package/dist/llms.txt +1 -1
  104. package/dist/local-models.d.ts +3 -11
  105. package/dist/local-models.js +5 -6
  106. package/dist/mcp-servers-store.d.ts +4 -4
  107. package/dist/model-form.js +6 -5
  108. package/dist/model.d.ts +4 -0
  109. package/dist/model.js +26 -9
  110. package/dist/native/binding.js +1 -1
  111. package/dist/native/connection.js +1 -1
  112. package/dist/native/discovery.js +1 -1
  113. package/dist/native/instructions.d.ts +3 -0
  114. package/dist/native/instructions.js +5 -3
  115. package/dist/native/remote-worker-bridge.js +9 -43
  116. package/dist/native/remote.d.ts +8 -15
  117. package/dist/native/remote.js +3 -3
  118. package/dist/native/schema.js +1 -1
  119. package/dist/native/types.d.ts +2 -2
  120. package/dist/openapi.js +273 -319
  121. package/dist/paid-calls.d.ts +8 -0
  122. package/dist/paid-calls.js +20 -0
  123. package/dist/particle-provider.d.ts +11 -0
  124. package/dist/particle-provider.js +135 -0
  125. package/dist/port-models.d.ts +12 -4
  126. package/dist/port-models.js +28 -11
  127. package/dist/print.d.ts +27 -0
  128. package/dist/print.js +21 -0
  129. package/dist/provider.d.ts +7 -0
  130. package/dist/provider.js +15 -1
  131. package/dist/reflect-range.js +2 -3
  132. package/dist/run-launch.d.ts +14 -28
  133. package/dist/run-launch.js +9 -12
  134. package/dist/run-learning-served.d.ts +15 -89
  135. package/dist/run-listing.d.ts +34 -0
  136. package/dist/run-listing.js +128 -0
  137. package/dist/run-model-key.js +1 -1
  138. package/dist/run-timeline-served.js +5 -3
  139. package/dist/run-trace.d.ts +97 -0
  140. package/dist/run-trace.js +253 -0
  141. package/dist/run-view.d.ts +15 -0
  142. package/dist/run-view.js +9 -0
  143. package/dist/runnable.js +2 -1
  144. package/dist/runner/adapter-loop.d.ts +8 -6
  145. package/dist/runner/adapter-loop.js +16 -12
  146. package/dist/runner/adapter-run-spec.d.ts +16 -4
  147. package/dist/runner/adapter-run-spec.js +64 -58
  148. package/dist/runner/adapters/index.js +22 -0
  149. package/dist/runner/adapters/pi.d.ts +4 -12
  150. package/dist/runner/adapters/pi.js +2 -2
  151. package/dist/runner/audit.d.ts +1 -1
  152. package/dist/runner/audit.js +30 -13
  153. package/dist/runner/beside.d.ts +6 -2
  154. package/dist/runner/beside.js +38 -9
  155. package/dist/runner/claim-secrets.d.ts +18 -2
  156. package/dist/runner/claim-secrets.js +42 -18
  157. package/dist/runner/cli-run-spec.js +55 -51
  158. package/dist/runner/conformance/harness.d.ts +6 -0
  159. package/dist/runner/conformance/harness.js +35 -13
  160. package/dist/runner/conformance/subject.d.ts +6 -0
  161. package/dist/runner/dispatch.d.ts +2 -2
  162. package/dist/runner/end-of-run.d.ts +6 -14
  163. package/dist/runner/end-of-run.js +8 -33
  164. package/dist/runner/feedback-round.d.ts +2 -2
  165. package/dist/runner/feedback-round.js +7 -7
  166. package/dist/runner/github-app.js +3 -1
  167. package/dist/runner/harness-loops.d.ts +0 -8
  168. package/dist/runner/harness-loops.js +11 -59
  169. package/dist/runner/held.d.ts +170 -0
  170. package/dist/runner/held.js +57 -0
  171. package/dist/runner/journal-kinds.d.ts +2 -3
  172. package/dist/runner/journal-kinds.js +2 -3
  173. package/dist/runner/learned-first.d.ts +40 -0
  174. package/dist/runner/learned-first.js +32 -0
  175. package/dist/runner/learning-end.d.ts +77 -69
  176. package/dist/runner/learning-end.js +250 -303
  177. package/dist/runner/learning-seed.d.ts +15 -33
  178. package/dist/runner/learning-seed.js +24 -45
  179. package/dist/runner/loop-contract.d.ts +2 -3
  180. package/dist/runner/main.d.ts +17 -9
  181. package/dist/runner/main.js +82 -20
  182. package/dist/runner/mcp-run.d.ts +11 -0
  183. package/dist/runner/mcp-run.js +67 -0
  184. package/dist/runner/memory-claim.d.ts +10 -5
  185. package/dist/runner/memory-claim.js +12 -6
  186. package/dist/runner/model-route.d.ts +7 -4
  187. package/dist/runner/model-route.js +22 -10
  188. package/dist/runner/native-loop.d.ts +0 -7
  189. package/dist/runner/native-loop.js +9 -101
  190. package/dist/runner/promotion.d.ts +12 -8
  191. package/dist/runner/promotion.js +37 -28
  192. package/dist/runner/reflect-hook.d.ts +64 -95
  193. package/dist/runner/reflect-hook.js +112 -225
  194. package/dist/runner/run-channel.d.ts +43 -0
  195. package/dist/runner/run-channel.js +467 -0
  196. package/dist/runner/run-child-host.d.ts +169 -0
  197. package/dist/runner/run-child-host.js +1230 -0
  198. package/dist/runner/run-child.d.ts +1 -0
  199. package/dist/runner/run-child.js +254 -0
  200. package/dist/runner/run-errors.d.ts +2 -0
  201. package/dist/runner/run-errors.js +20 -0
  202. package/dist/runner/runner.js +1 -5
  203. package/dist/runner/sdk-ask.d.ts +78 -0
  204. package/dist/runner/sdk-ask.js +158 -0
  205. package/dist/runner/sdk-loop.d.ts +2 -4
  206. package/dist/runner/sdk-loop.js +29 -49
  207. package/dist/runner/store-secrets.d.ts +5 -3
  208. package/dist/runner/store-secrets.js +5 -1
  209. package/dist/runner/workflow-first.d.ts +5 -0
  210. package/dist/runner/workflow-first.js +4 -0
  211. package/dist/runner/workflow-spec.js +7 -2
  212. package/dist/runs-over-store.d.ts +16 -28
  213. package/dist/runs-over-store.js +31 -38
  214. package/dist/sdk/runs.d.ts +6 -11
  215. package/dist/sdk/runs.js +20 -41
  216. package/dist/sdk/schema.js +3 -4
  217. package/dist/seal-key.d.ts +5 -0
  218. package/dist/seal-key.js +7 -0
  219. package/dist/secrets.d.ts +3 -0
  220. package/dist/secrets.js +16 -3
  221. package/dist/server.d.ts +55 -33
  222. package/dist/server.js +689 -322
  223. package/dist/sign-ins-store.d.ts +8 -0
  224. package/dist/sign-ins-store.js +36 -1
  225. package/dist/skills.js +1 -1
  226. package/dist/store/index.d.ts +2 -2
  227. package/dist/store/index.js +1 -1
  228. package/dist/store/journal/storage.js +3 -0
  229. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  230. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  231. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  232. package/dist/store/schema.d.ts +53 -4
  233. package/dist/store/schema.js +137 -6
  234. package/dist/store/sqlite/connection.d.ts +2 -0
  235. package/dist/store/sqlite/connection.js +3 -1
  236. package/dist/store/sqlite/run-patch.d.ts +0 -17
  237. package/dist/store/sqlite/run-patch.js +4 -33
  238. package/dist/store/sqlite/store.js +246 -63
  239. package/dist/store/sqlite/worker.js +25 -0
  240. package/dist/store/store.d.ts +193 -36
  241. package/dist/store/store.js +25 -3
  242. package/dist/store-reads/learning.d.ts +102 -204
  243. package/dist/store-reads/learning.js +159 -321
  244. package/dist/store-reads/loop.d.ts +0 -1
  245. package/dist/store-reads/loop.js +1 -1
  246. package/dist/store-view.d.ts +29 -1
  247. package/dist/store-view.js +97 -31
  248. package/dist/template-eval.d.ts +3 -6
  249. package/dist/template-eval.js +22 -36
  250. package/dist/templates.d.ts +8 -4
  251. package/dist/templates.js +44 -6
  252. package/dist/timeline/index.d.ts +1 -1
  253. package/dist/timeline/index.js +1 -1
  254. package/dist/timeline/timeline.d.ts +5 -1
  255. package/dist/timeline/timeline.js +16 -0
  256. package/dist/tool-gate.d.ts +0 -7
  257. package/dist/tool-gate.js +1 -15
  258. package/dist/tool-keys-store.d.ts +1 -1
  259. package/dist/tool-keys.d.ts +6 -4
  260. package/dist/tool-keys.js +12 -6
  261. package/dist/tools.d.ts +2 -2
  262. package/dist/tools.js +11 -4
  263. package/dist/triggers.d.ts +65 -6
  264. package/dist/triggers.js +125 -19
  265. package/dist/validate.js +1 -1
  266. package/dist/webhooks.d.ts +7 -2
  267. package/dist/webhooks.js +12 -5
  268. package/dist/workspace/agent-computer.d.ts +2 -0
  269. package/dist/workspace/agent-computer.js +2 -0
  270. package/dist/workspace/archil-claim.d.ts +7 -0
  271. package/dist/workspace/archil-claim.js +29 -0
  272. package/dist/workspace/archil.d.ts +9 -1
  273. package/dist/workspace/archil.js +165 -3
  274. package/dist/workspace/attach.d.ts +3 -1
  275. package/dist/workspace/attach.js +2 -0
  276. package/dist/workspace/attached-computers.d.ts +16 -5
  277. package/dist/workspace/attached-computers.js +25 -9
  278. package/dist/workspace/computer-deps.js +1 -1
  279. package/dist/workspace/computer-for-claim.d.ts +7 -3
  280. package/dist/workspace/computer-for-claim.js +119 -22
  281. package/dist/workspace/computer-hold.js +2 -1
  282. package/dist/workspace/computer-kept.d.ts +11 -1
  283. package/dist/workspace/computer-kept.js +24 -3
  284. package/dist/workspace/resolve-computer.d.ts +33 -19
  285. package/dist/workspace/resolve-computer.js +172 -64
  286. package/dist/workspace/revision-skills.d.ts +1 -2
  287. package/dist/workspace/revision-skills.js +3 -4
  288. package/dist/workspace/run-workspace.d.ts +1 -1
  289. package/dist/workspace/run-workspace.js +5 -0
  290. package/dist/workspace/synced-folder.d.ts +85 -0
  291. package/dist/workspace/synced-folder.js +230 -0
  292. package/dist/workspace/workspace.d.ts +4 -0
  293. package/launcher/agentrun-serve +1 -1
  294. package/package.json +10 -10
  295. package/templates/README.md +8 -8
  296. package/templates/inbound-lead/agent.md +5 -4
  297. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  298. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  299. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  300. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  301. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  302. package/templates/inbound-lead/lead.schema.json +6 -5
  303. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  304. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  305. package/templates/kyb/agent.md +2 -1
  306. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  307. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  308. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  309. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  310. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  311. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  312. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  313. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  314. package/dist/console/assets/index-BUktRvS-.css +0 -1
  315. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  316. package/dist/learn/grade.d.ts +0 -138
  317. package/dist/learn/grade.js +0 -682
  318. package/dist/learn/notes.d.ts +0 -81
  319. package/dist/learn/notes.js +0 -178
  320. package/dist/learn/reflect.d.ts +0 -77
  321. package/dist/learn/reflect.js +0 -228
  322. package/dist/learn/relevance.d.ts +0 -24
  323. package/dist/learn/relevance.js +0 -91
  324. package/dist/learn/seed-check.d.ts +0 -74
  325. package/dist/learn/seed-check.js +0 -103
  326. package/dist/learning-batch.d.ts +0 -291
  327. package/dist/learning-batch.js +0 -600
  328. package/dist/learning-evals.d.ts +0 -35
  329. package/dist/learning-evals.js +0 -99
  330. package/dist/native/context.d.ts +0 -6
  331. package/dist/native/context.js +0 -22
  332. package/dist/propose.d.ts +0 -52
  333. package/dist/propose.js +0 -224
  334. package/dist/runner/learning-ask.d.ts +0 -47
  335. package/dist/runner/learning-ask.js +0 -128
  336. package/dist/runner/learning-dispatch.d.ts +0 -45
  337. package/dist/runner/learning-dispatch.js +0 -99
  338. package/dist/runner/learning-factory.d.ts +0 -16
  339. package/dist/runner/learning-factory.js +0 -50
  340. package/dist/runner/learning-loop.d.ts +0 -273
  341. package/dist/runner/learning-loop.js +0 -521
  342. package/dist/usage.d.ts +0 -11
  343. package/dist/usage.js +0 -11
  344. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  345. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  346. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  347. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  348. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  349. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  350. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -0,0 +1,1230 @@
1
+ // A run is a process of its own (design: option A). The runner claims as it always did and runs no loop itself: at each
2
+ // claim it starts the run's own process (run-child.ts) and hands it, on two inherited descriptors, the run's own keys
3
+ // (fd 3: secrets.ts reads and closes it as the process loads) and a channel (fd 4: run-channel.ts). Over the channel the
4
+ // run's process asks for what it would otherwise hold: its journal, under the claim's fence (the runner's own journal
5
+ // of the claim, LoopDeps.journal); the store reads its loop makes, bound to the claim's run and agent; and what the seal key
6
+ // opens for the claim (held.ts), never the key. The runner keeps the claim, its renewals, its commands and its end.
7
+ //
8
+ // Where the image's helper can switch (agentrun-runas, root:node 0750 with file capabilities), each of the runner's claim
9
+ // slots runs as a uid of its own (1001 + slot), in folders of the slot's group (2770) the server's user reads through its
10
+ // membership of every slot group: one run can read neither another run's folder nor, being another uid, its memory. A
11
+ // slot is reaped at each run's end (every process of its uid killed, its files in /tmp removed, what it left readable to
12
+ // the server), and its folders are given back to the server's group.
13
+ import { execFile, spawn } from "node:child_process";
14
+ import { existsSync } from "node:fs";
15
+ import { chmod, chown, lchown, lstat, mkdir, readdir, rm } from "node:fs/promises";
16
+ import { dirname, join } from "node:path";
17
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
18
+ import { encode, SECRET_NAMES, SECRETS_FD_ENV, SECRETS_LEN_ENV, withoutSecrets } from "../secrets.js";
19
+ import { putLiveViewer, dropLiveViewer } from "../browser-live.js";
20
+ import { CALENDAR_EVENTS } from "../calendar/names.js";
21
+ import { openCalendar } from "../calendar/address.js";
22
+ import { openAccount } from "../email/account.js";
23
+ import { harnessOf } from "../harness-table.js";
24
+ import { installDirOf, installForClaim, shareInstall } from "../harness-install.js";
25
+ import { loadArchilSettings } from "../archil-settings.js";
26
+ import { planOf } from "../chatgpt-plan.js";
27
+ import { forgottenSignIns, handedSignInReadsBack, peekSignIn, runSignIn, signInReads, verifyRunSignIn } from "../sign-ins-store.js";
28
+ import { vendorsOver } from "../sign-ins.js";
29
+ import { decisionProvidersIn, fauxFetch } from "../decisions.js";
30
+ import { DECISION_PROVIDER_KEYS } from "../tool-plane.js";
31
+ import { learningEndOfRun } from "./learning-end.js";
32
+ import { runnerSecrets } from "./redact.js";
33
+ import { storeSecrets } from "./store-secrets.js";
34
+ import { FAUX_ENV } from "../model.js";
35
+ import { FAUX_VENDOR_API_ENV } from "../tools.js";
36
+ import { withinCarried } from "../paid-calls.js";
37
+ import { openRunMcpAuth, sealRunMcpAuth } from "../store/seal.js";
38
+ import { runZone } from "../environment.js";
39
+ import { shadowRunId } from "../learn/audit.js";
40
+ import { LEARNING_SCRIPT, learningWorkspace } from "../learn/folder.js";
41
+ import { openRunWorkspace } from "../workspace/run-workspace.js";
42
+ import { archilClaim, MOUNT_TTL_MS } from "../workspace/archil-claim.js";
43
+ import { agentDirName, recordingsFolder, runFolder, scratchFolder } from "../workspace/paths.js";
44
+ import { keptKeyOf } from "../workspace/computer-kept.js";
45
+ import { claimModelKey, claimSecrets, claimSpendOff, hostDecisionKeys, learnedDecisionKeys, openRunModelKey, savedModelKeys, serverKeyless, tierModelKeys, withoutModelKeys } from "./claim-secrets.js";
46
+ import { githubAppAccess } from "./github-app.js";
47
+ import { githubPullOf } from "../github.js";
48
+ import { isObject } from "../validate.js";
49
+ import { liveForRun, runnerLiveOf } from "../live-reach.js";
50
+ import { learningFolderOf, secretsShown } from "../learning.js";
51
+ import { learningStartOf, seedFailed } from "../run-launch.js";
52
+ import { messageText } from "../run-manifest.js";
53
+ import { placeRunInputs } from "../uploads.js";
54
+ import { withAudit } from "./audit.js";
55
+ import { learnedFirst } from "./learned-first.js";
56
+ import { workflowsAt } from "./learning-seed.js";
57
+ import { heldMcpOf, mcpForClaim } from "./mcp-run.js";
58
+ import { learnedTiers, learnsWorkflows, mcpReachOf } from "./adapter-run-spec.js";
59
+ import { createDispatchLoop } from "./dispatch.js";
60
+ import { resolveRunnerLoop } from "./harness-loops.js";
61
+ import { isWorkflowRevision } from "./workflow-loop.js";
62
+ import { loginForRun } from "../claude-login.js";
63
+ import { ClaimRefused } from "./loop-contract.js";
64
+ import { Channel, ChannelClosed } from "./run-channel.js";
65
+ import { registerRunErrors } from "./run-errors.js";
66
+ import { readLaunchBody } from "../run-launch.js";
67
+ import { SUBAGENT_TOOL } from "./subagent.js";
68
+ /** The image's helper that starts a run's process as its slot's uid (packages/serve/runas). */
69
+ export const RUNAS_HELPER = "/usr/local/bin/agentrun-runas";
70
+ /** `same`: every run runs as the runner's own user, the helper unused, said in the runner's log. */
71
+ export const RUN_USER_ENV = "AGENTRUN_RUN_USER";
72
+ /** The first of this runner's slots (0 by default): two runners on one data directory take ranges of their own. */
73
+ export const RUN_SLOT_FIRST_ENV = "AGENTRUN_RUN_SLOT_FIRST";
74
+ /** The helper's compiled range: slot s runs as uid and gid FIRST_RUN_ID + s. */
75
+ export const FIRST_RUN_ID = 1001;
76
+ export const RUN_SLOTS = 256;
77
+ /** How long a run's process has to end once its loop was told to stop, before the runner ends it. */
78
+ const STOP_GRACE_MS = 30_000;
79
+ /** How long a run's process has to exit once its loop ended. */
80
+ const EXIT_GRACE_MS = 5_000;
81
+ /** The isolation this host gives a run, as the capabilities document says it: `uid` with the helper, else `process`. */
82
+ export const runIsolationName = (isolation) => isolation.kind;
83
+ /** A runner that cannot keep its runs apart as the image promises: said in words that name the setting. */
84
+ export class RunIsolationRefused extends Error {
85
+ name = "RunIsolationRefused";
86
+ }
87
+ /** The helper run once: its exit code and output, never a rejection. A spawn error Node throws from execFile itself
88
+ * (EPERM, say, where a platform forbids the helper's file capabilities; only EACCES, EAGAIN, EMFILE, ENFILE and ENOENT
89
+ * come to the callback) is `code` -1 with the error's words as `stderr`, so every caller reads it as the failure it is. */
90
+ const execText = (file, args, timeoutMs) => new Promise((resolve) => {
91
+ try {
92
+ execFile(file, args, { timeout: timeoutMs, encoding: "utf8" }, (error, stdout, stderr) => {
93
+ const code = error ? (typeof error.code === "number" ? (error.code) : 1) : 0;
94
+ resolve({ code, stdout: String(stdout), stderr: String(stderr || (error && !stderr ? error.message : "")) });
95
+ });
96
+ }
97
+ catch (error) {
98
+ resolve({ code: -1, stdout: "", stderr: error?.message ?? String(error) });
99
+ }
100
+ });
101
+ /** This host's isolation for `loops` runs at once, by `env` and the helper: the helper's own check that it can switch
102
+ * (its effective set holds what it needs) decides `uid`; none installed (a local install), `process`; `same`, `process`
103
+ * said in the log. A helper that cannot switch is refused in words naming the setting, never a quiet fall back. `loops`
104
+ * the runner was told (--loops, AGENTRUN_MAX_RUNS) past the helper's last slot from its first is refused too; none told
105
+ * (a host's memory's count, or no bound), it holds the slots from its first. */
106
+ export async function runIsolationOf(env, loops, log, helper = RUNAS_HELPER) {
107
+ const asked = env[RUN_USER_ENV];
108
+ if (asked !== undefined && asked !== "" && asked !== "same" && asked !== "slot")
109
+ throw new RunIsolationRefused(`${RUN_USER_ENV}=${asked} is not a setting this runner knows: unset it (each run as a user of its own, where the image's helper can switch) or set it to "same" (every run as the runner's own user).`);
110
+ if (asked === "same") {
111
+ log(`${RUN_USER_ENV}=same: every run runs as this runner's own user, in a process of its own; one run's tools can read another's folder and the data directory`);
112
+ return { kind: "process", why: `${RUN_USER_ENV}=same` };
113
+ }
114
+ if (!existsSync(helper)) {
115
+ if (asked === "slot")
116
+ throw new RunIsolationRefused(`${RUN_USER_ENV}=slot asks for a user of its own for each run, and this host has no ${helper}: run the image, or unset ${RUN_USER_ENV}.`);
117
+ return { kind: "process", why: "no helper on this host" };
118
+ }
119
+ const checked = await execText(helper, ["check"], 10_000);
120
+ if (checked.code !== 0) {
121
+ throw new RunIsolationRefused(`This runner will not claim runs: it cannot start a run as a user of its own (${checked.stderr.trim() || `${helper} check exited ${checked.code}`}). ` +
122
+ `The platform strips the image's file capabilities, or starts the container with no-new-privileges (Docker's security_opt no-new-privileges:true, Kubernetes' allowPrivilegeEscalation: false). ` +
123
+ `Allow them, or set ${RUN_USER_ENV}=same to run every run as the runner's own user.`);
124
+ }
125
+ const firstText = env[RUN_SLOT_FIRST_ENV];
126
+ const first = firstText === undefined || firstText === "" ? 0 : Number(firstText);
127
+ if (!Number.isSafeInteger(first) || first < 0 || first >= RUN_SLOTS)
128
+ throw new RunIsolationRefused(`${RUN_SLOT_FIRST_ENV}=${firstText} is not a slot 0..${RUN_SLOTS - 1}.`);
129
+ const reach = RUN_SLOTS - first;
130
+ if (loops !== undefined && loops > reach) {
131
+ throw new RunIsolationRefused(`This runner will not claim runs: it holds ${loops} at once from ${RUN_SLOT_FIRST_ENV}=${first}, slots ${first}..${first + loops - 1}, and the helper's last slot is ${RUN_SLOTS - 1}. ` +
132
+ `Hold at most ${reach} (--loops, AGENTRUN_MAX_RUNS) or start from a lower ${RUN_SLOT_FIRST_ENV}; runners on one data directory each take a range of their own.`);
133
+ }
134
+ return { kind: "uid", helper, first, slots: loops ?? reach };
135
+ }
136
+ /** The runs a runner holds at once, as `uid` isolation lets it: its slots. */
137
+ export const isolationLoops = (isolation, loops) => (isolation.kind === "uid" ? Math.min(loops, isolation.slots) : loops);
138
+ /** The folder of the data directory where each slot's lock is (`<slot>.lock`, the server's user's alone). */
139
+ export const slotLocks = (data) => join(data, "run-slots");
140
+ /** Slot `slot`'s lock under `dir`, taken for as long as the process it returns lives: an exclusive flock (util-linux's
141
+ * flock) its holder keeps until its stdin closes, which the runner's end closes too, so a runner that dies holds no
142
+ * slot. Undefined when another holds it. */
143
+ async function lockSlot(dir, slot) {
144
+ await mkdir(dir, { recursive: true, mode: 0o700 });
145
+ // Its environment PATH alone: the holder lives as long as the slot is held, and needs none of the runner's.
146
+ const holder = spawn("flock", ["-n", "-E", "75", join(dir, `${slot}.lock`), "sh", "-c", "echo held; exec cat >/dev/null"], { stdio: ["pipe", "pipe", "pipe"], env: { PATH: process.env.PATH ?? "/usr/bin:/bin" } });
147
+ holder.unref();
148
+ for (const stream of [holder.stdin, holder.stdout, holder.stderr])
149
+ stream?.unref?.();
150
+ let said = "";
151
+ holder.stderr.on("data", (chunk) => void (said += chunk));
152
+ return new Promise((resolve, reject) => {
153
+ holder.stdout.once("data", () => resolve(holder));
154
+ holder.once("error", (error) => reject(new Error(`slot ${slot}'s lock could not be taken: ${error.message}`)));
155
+ holder.once("exit", (code) => (code === 75 ? resolve(undefined) : reject(new Error(`slot ${slot}'s lock could not be taken: flock exited ${code}${said ? `: ${said.trim()}` : ""}`))));
156
+ });
157
+ }
158
+ /** Ends a slot's lock: its holder's stdin closed, and its exit waited for. */
159
+ async function unlockSlot(holder) {
160
+ if (holder.exitCode !== null || holder.signalCode !== null)
161
+ return;
162
+ const gone = new Promise((resolve) => holder.once("exit", resolve));
163
+ holder.stdin?.end();
164
+ await gone;
165
+ }
166
+ /** The slots of a uid runner, each held by one run at a time. With `locks` (the data directory's slotLocks), each slot
167
+ * taken is locked there too, so runners on one data directory whose ranges overlap never run two runs on one slot: a
168
+ * slot another runner holds is skipped. */
169
+ export class Slots {
170
+ #free;
171
+ #locks;
172
+ #held = new Map();
173
+ #retired = new Set();
174
+ constructor(first, count, locks) {
175
+ this.#free = Array.from({ length: count }, (_, i) => first + count - 1 - i);
176
+ this.#locks = locks;
177
+ }
178
+ /** A free slot of this runner no other runner holds; undefined when another holds every free one, or every slot not
179
+ * held is retired. */
180
+ async take() {
181
+ if (this.#free.length === 0 && this.#retired.size > 0)
182
+ return undefined;
183
+ if (this.#free.length === 0)
184
+ throw new Error("every run slot of this runner is held: it claimed more runs than it has slots");
185
+ if (this.#locks === undefined)
186
+ return this.#free.pop();
187
+ for (const slot of [...this.#free].reverse()) {
188
+ if (!this.#free.includes(slot))
189
+ continue;
190
+ const holder = await lockSlot(this.#locks, slot);
191
+ if (!holder)
192
+ continue;
193
+ this.#free.splice(this.#free.indexOf(slot), 1);
194
+ this.#held.set(slot, holder);
195
+ return slot;
196
+ }
197
+ return undefined;
198
+ }
199
+ /** Never gives `slot` back: a slot whose reap did not hold (a process of its uid may still be alive) runs no run of
200
+ * this runner again, and its lock is kept, so no other runner on the data directory takes it either. */
201
+ retire(slot) {
202
+ this.#retired.add(slot);
203
+ }
204
+ /** The slots retired (retire). */
205
+ get retired() {
206
+ return [...this.#retired];
207
+ }
208
+ /** Gives `slot` back, its lock ended first. */
209
+ async give(slot) {
210
+ const holder = this.#held.get(slot);
211
+ this.#held.delete(slot);
212
+ if (holder)
213
+ await unlockSlot(holder);
214
+ this.#free.push(slot);
215
+ }
216
+ }
217
+ /** A slot's uid (and gid). */
218
+ export const slotId = (slot) => FIRST_RUN_ID + slot;
219
+ /** One run's hold on its slot, bound at its spawn: a kill reaps this slot alone, and only while the run holds it. Once
220
+ * settled, no kill starts, and the settle ends only when every kill already reaping has ended, so the slot goes back
221
+ * (and its next run starts) with no reap of this run still killing the slot's uid. */
222
+ export class SlotHold {
223
+ #settled = false;
224
+ #kills = new Set();
225
+ slot;
226
+ #helper;
227
+ #log;
228
+ constructor(slot, helper, log) {
229
+ this.slot = slot;
230
+ this.#helper = helper;
231
+ this.#log = log;
232
+ }
233
+ async kill() {
234
+ if (this.#settled)
235
+ return;
236
+ const reaping = execText(this.#helper, ["reap", String(this.slot)], 120_000);
237
+ this.#kills.add(reaping);
238
+ try {
239
+ const reaped = await reaping;
240
+ if (reaped.code !== 0)
241
+ this.#log(`slot ${this.slot}'s kill said: ${reaped.stderr.trim()}`);
242
+ }
243
+ finally {
244
+ this.#kills.delete(reaping);
245
+ }
246
+ }
247
+ async settle() {
248
+ this.#settled = true;
249
+ await Promise.all(this.#kills);
250
+ }
251
+ }
252
+ // ---------------------------------------------------------------------------------------------------------------------
253
+ // The folders of a run, by the slot that runs it.
254
+ /** The run's own top folders: its folder (work and recordings beneath it) and its scratch folder. */
255
+ export const runTops = (data, agentId, runId) => [dirname(runFolder(data, agentId, runId)), scratchFolder(data, agentId, runId)];
256
+ /** The parents a run's process crosses to reach its own folders, each traverse-only (0711) for it. */
257
+ const runParents = (data, agentId, runId) => {
258
+ const top = dirname(runFolder(data, agentId, runId));
259
+ const scratch = scratchFolder(data, agentId, runId);
260
+ return [data, join(data, "disk"), join(data, "disk", "agents"), join(data, "disk", "agents", agentDirName(agentId)), dirname(top), join(data, "scratch"), dirname(scratch)];
261
+ };
262
+ /** Before the run's process starts on `slot`: its parents traverse-only, its top folders the slot group's (2770), and
263
+ * what an earlier claim's slot left in them given to this slot (the helper's reown). */
264
+ async function layRunFolders(isolation, data, agentId, runId, slot) {
265
+ for (const parent of runParents(data, agentId, runId)) {
266
+ await mkdir(parent, { recursive: true });
267
+ await chmod(parent, 0o711);
268
+ }
269
+ const gid = slotId(slot);
270
+ for (const top of runTops(data, agentId, runId)) {
271
+ await mkdir(top, { recursive: true });
272
+ await chown(top, process.getuid(), gid);
273
+ await chmod(top, 0o2770);
274
+ // An earlier claim of this run on another slot left its files that slot's: given to this one, so the run reads and
275
+ // writes what it wrote before.
276
+ for (const other of await slotsUnder(top, slot)) {
277
+ const moved = await execText(isolation.helper, ["reown", String(other), String(slot), top], 120_000);
278
+ if (moved.code !== 0)
279
+ throw new Error(`the run's folder could not be given to its slot: ${moved.stderr.trim()}`);
280
+ }
281
+ // What the server's user made there (a run's inputs placed at this claim, an earlier run's folders on a volume from
282
+ // before runs had slots of their own): the slot group's, so the run writes there too.
283
+ await toSlotGroup(top, gid);
284
+ }
285
+ // The folders the run's process opens first, made here in the slot's group (setgid): its folder, its recordings and its
286
+ // temporary folder (its TMPDIR), each one the server reads through the group as the run writes it.
287
+ for (const folder of [runFolder(data, agentId, runId), recordingsFolder(data, agentId, runId), join(scratchFolder(data, agentId, runId), "tmp")]) {
288
+ await mkdir(folder, { recursive: true });
289
+ const stat = await lstat(folder);
290
+ if (stat.uid !== process.getuid())
291
+ continue;
292
+ await chown(folder, process.getuid(), gid);
293
+ await chmod(folder, 0o2770);
294
+ }
295
+ }
296
+ /** Every entry under `dir` the server's user owns, given to group `gid` as the helper's reown gives a slot's: a folder
297
+ * the group's to enter and write (2770), a file's owner bits copied to the group, none for others. The whole tree, a
298
+ * symlink never followed nor changed (an lstat's). Run while no process of the slot is alive (after its reap), so
299
+ * nothing it walks is swapped under it. */
300
+ export async function toSlotGroup(dir, gid) {
301
+ const me = process.getuid();
302
+ const walk = async (at) => {
303
+ let names;
304
+ try {
305
+ names = await readdir(at);
306
+ }
307
+ catch {
308
+ return;
309
+ }
310
+ for (const name of names) {
311
+ const path = join(at, name);
312
+ const stat = await lstat(path).catch(() => undefined);
313
+ if (!stat || stat.isSymbolicLink())
314
+ continue;
315
+ if (stat.uid === me) {
316
+ await lchown(path, me, gid);
317
+ const owner = stat.mode & 0o700;
318
+ await chmod(path, stat.isDirectory() ? 0o2770 : owner | (owner >> 3));
319
+ }
320
+ if (stat.isDirectory())
321
+ await walk(path);
322
+ }
323
+ };
324
+ await walk(dir);
325
+ }
326
+ /** The other slots that own an entry anywhere under `dir`, as the helper's reown walks it: the whole tree, a symlink
327
+ * never followed (an lstat's, never a directory). `statOf`: the stat it reads (a test's). */
328
+ export async function slotsUnder(dir, slot, statOf = lstat) {
329
+ const found = new Set();
330
+ const look = async (at) => {
331
+ let names;
332
+ try {
333
+ names = await readdir(at);
334
+ }
335
+ catch {
336
+ return;
337
+ }
338
+ for (const name of names) {
339
+ const path = join(at, name);
340
+ const stat = await statOf(path).catch(() => undefined);
341
+ if (!stat)
342
+ continue;
343
+ const other = stat.uid - FIRST_RUN_ID;
344
+ if (other >= 0 && other < RUN_SLOTS && other !== slot)
345
+ found.add(other);
346
+ if (stat.isDirectory())
347
+ await look(path);
348
+ }
349
+ };
350
+ await look(dir);
351
+ return [...found];
352
+ }
353
+ /** The host's shared folders a slot's uid can leave a file in, each swept at its reap (/var/lock is /run/lock's link on
354
+ * Debian, swept as itself where it is a folder of its own). SysV IPC is not swept. */
355
+ const SWEPT = ["/tmp", "/var/tmp", "/dev/shm", "/run/lock", "/var/lock", "/dev/mqueue"];
356
+ /** After the run's process ended: every process of the slot's uid killed, its files in the shared temporary folders
357
+ * removed, what it left in its folders readable and removable by the server's group, and its top folders the server's
358
+ * own again (0770), which the slot's next run cannot enter. Whether the reap held: the helper kills until no process of
359
+ * the uid is left, and says so; false when one still is, or the reap could not run (the slot is then never run on
360
+ * again by this runner). */
361
+ export async function reapSlot(isolation, slot, tops, log) {
362
+ const args = ["reap", String(slot), ...SWEPT.flatMap((dir) => ["--sweep", dir]), ...tops.flatMap((top) => ["--fix", top])];
363
+ const reaped = await execText(isolation.helper, args, 120_000);
364
+ if (reaped.code !== 0)
365
+ log(`slot ${slot}'s reap said: ${reaped.stderr.trim()}`);
366
+ for (const top of tops) {
367
+ try {
368
+ await chown(top, process.getuid(), process.getgid());
369
+ await chmod(top, 0o770);
370
+ }
371
+ catch (error) {
372
+ if (error.code !== "ENOENT")
373
+ log(`the run's folder ${top} was not given back to the server: ${error.message}`);
374
+ }
375
+ }
376
+ return reaped.code === 0;
377
+ }
378
+ /** After a reap that held: the run's scratch folder as a claim's end in the runner's own process leaves it (cli-run-spec.ts
379
+ * sweepScratch), with the temporary folder the runner laid for its process (its TMPDIR) gone too. The agent's folder
380
+ * above it stays: another run's start may be laying it (0711) at this moment, and the start sweep takes it once empty.
381
+ * Logged, never thrown. */
382
+ async function sweepRunScratch(data, agentId, claim, log) {
383
+ const scratch = scratchFolder(data, agentId, claim.runId);
384
+ const harnesses = join(scratch, "harness");
385
+ try {
386
+ await rm(join(scratch, "tmp"), { recursive: true, force: true });
387
+ const { sweepScratch } = await import("./cli-run-spec.js");
388
+ await sweepScratch(harnesses, claim.epoch, [harnesses, scratch]);
389
+ }
390
+ catch (error) {
391
+ log(`run ${claim.runId}: its scratch folder could not be swept: ${error?.message ?? error}`);
392
+ }
393
+ }
394
+ // ---------------------------------------------------------------------------------------------------------------------
395
+ // What crosses: data alone.
396
+ /** `value` as data: every function, symbol and class's method left out, so nothing the runner holds is handed by
397
+ * reference to the run's process unless a target hands it on purpose. */
398
+ export function dataOnly(value, seen = new Set()) {
399
+ if (value === null || typeof value !== "object")
400
+ return typeof value === "function" || typeof value === "symbol" ? undefined : value;
401
+ if (ArrayBuffer.isView(value) || value instanceof Date || value instanceof RegExp || value instanceof ArrayBuffer)
402
+ return value;
403
+ if (seen.has(value))
404
+ return undefined;
405
+ seen.add(value);
406
+ try {
407
+ if (Array.isArray(value))
408
+ return value.map((item) => dataOnly(item, seen));
409
+ if (value instanceof Map)
410
+ return new Map([...value].map(([k, v]) => [dataOnly(k, seen), dataOnly(v, seen)]));
411
+ if (value instanceof Set)
412
+ return new Set([...value].map((v) => dataOnly(v, seen)));
413
+ if (value instanceof Error)
414
+ return Object.assign(new Error(value.message), { name: value.name });
415
+ const out = {};
416
+ for (const key of Object.keys(value)) {
417
+ const member = value[key];
418
+ if (typeof member === "function" || typeof member === "symbol")
419
+ continue;
420
+ Object.defineProperty(out, key, { value: dataOnly(member, seen), enumerable: true, writable: true, configurable: true });
421
+ }
422
+ return out;
423
+ }
424
+ finally {
425
+ seen.delete(value);
426
+ }
427
+ }
428
+ /** Every string inside `value` cut by `cut`: what the run's process writes, as the runner's redactor would cut it in a
429
+ * loop of its own (rule three: no secret the runner holds is written). */
430
+ export function cutDeep(value, cut) {
431
+ if (typeof value === "string")
432
+ return cut(value);
433
+ if (value === null || typeof value !== "object")
434
+ return value;
435
+ if (ArrayBuffer.isView(value) || value instanceof Date || value instanceof RegExp || value instanceof ArrayBuffer)
436
+ return value;
437
+ if (Array.isArray(value))
438
+ return value.map((item) => cutDeep(item, cut));
439
+ if (value instanceof Map)
440
+ return new Map([...value].map(([k, v]) => [k, cutDeep(v, cut)]));
441
+ const out = {};
442
+ for (const key of Object.keys(value))
443
+ Object.defineProperty(out, key, { value: cutDeep(value[key], cut), enumerable: true, writable: true, configurable: true });
444
+ return out;
445
+ }
446
+ const ownRun = (args, bound) => args[0] === bound.claim.runId;
447
+ /** The claim's run, or its own audit's shadow run, whose spend its cap gates read beside it (learning-end.ts besideOf). */
448
+ const ownRunOrShadow = (args, bound) => args[0] === bound.claim.runId || args[0] === shadowRunId(bound.claim.runId);
449
+ const ownAgent = (args, bound) => args[0] === bound.agentId;
450
+ const ownClaim = (args, bound) => {
451
+ const claim = args[0];
452
+ return claim?.runId === bound.claim.runId && claim.epoch === bound.claim.epoch;
453
+ };
454
+ const agentQuery = (args, bound) => {
455
+ const query = args[0];
456
+ return typeof query === "object" && query !== null && query.agentId === bound.agentId;
457
+ };
458
+ const always = () => true;
459
+ /** The settings a run's process may read, the server's own configuration its loop and tools read: its tool settings,
460
+ * its Archil settings (no credential), its MCP hosts and server names, its Claude-login mode and its approvers. */
461
+ const SHARED_SETTINGS = new Set(["tool-settings", "archil", "mcp.private_oauth_hosts", "mcp.server_own", "claude_login", "approvers"]);
462
+ /** The settings of the claim's own run and agent a run's process may read: its run's Archil disk, SDK record, kept
463
+ * computer and browser wait, and its agent's Archil disk and promotions. Every other row (another run's or agent's) is
464
+ * not its to read. */
465
+ const ownSettings = (bound) => new Set([
466
+ `archil.run.${bound.claim.runId}`,
467
+ `sdk-run:${bound.claim.runId}`,
468
+ keptKeyOf(bound.claim.runId),
469
+ `browser_wait_ended:${bound.claim.runId}`,
470
+ `archil.agent.${bound.agentId}`,
471
+ `learning.promotions.${bound.agentId}`,
472
+ ]);
473
+ /** Whether a run's process may read setting `key`. */
474
+ export const settingReadable = (key, bound) => typeof key === "string" && (SHARED_SETTINGS.has(key) || ownSettings(bound).has(key));
475
+ const readableSetting = (args, bound) => settingReadable(args[0], bound);
476
+ /** The store's methods a run's loop calls, each with what binds it to the claim. A method not here is refused, and the
477
+ * refusal is said on the runner's log. Reads of the claim's run, its launch, its commands and its agent's revisions;
478
+ * of what was spent beside it (its learning grades, its own audit's shadow run's row and launch, which its cap gates
479
+ * read); of the agent's own runs (its learning reads its past runs); the server's settings its tools read and the
480
+ * claim's own rows (settingReadable). Writes only under the claim. */
481
+ const STORE_CALLS = new Map([
482
+ ["flush", always],
483
+ ["runs.get", ownRunOrShadow],
484
+ ["runs.launch", ownRunOrShadow],
485
+ ["runs.list", agentQuery],
486
+ ["runs.ofAgent", ownAgent],
487
+ ["runs.update", ownClaim],
488
+ ["runs.metrics", ownRun],
489
+ ["runs.children", ownRun],
490
+ ["commands", ownRun],
491
+ ["answerOf", ownRun],
492
+ ["take", ownClaim],
493
+ ["retry", ownClaim],
494
+ ["agents.get", ownAgent],
495
+ ["agents.revision", always],
496
+ ["agents.revisions", ownAgent],
497
+ ["settings.get", readableSetting],
498
+ // Its rows filtered to the readable ones (storeCall).
499
+ ["settings.all", always],
500
+ ["mcp.pin", ownRun],
501
+ ["readJournal", ownRun],
502
+ ["learning.proposal", ownRun],
503
+ ["learning.spentBeside", ownRun],
504
+ ["learning.proposals", ownAgent],
505
+ ["learning.list", ownAgent],
506
+ ["learning.get", always],
507
+ ["computerLedger.book", ownClaim],
508
+ ["computerLedger.list", ownRun],
509
+ ["live.put", ownClaim],
510
+ ]);
511
+ /** After a call: an answer that names another agent is refused (a revision is read by its id alone). */
512
+ const answerBound = (method, answer, bound) => {
513
+ if (method !== "agents.revision" || answer === undefined || answer === null)
514
+ return true;
515
+ return answer.agentId === bound.agentId;
516
+ };
517
+ /** The store target: a call of `method` (`a.b`) with `args`, bound to the claim. */
518
+ export async function storeCall(store, method, args, bound, log) {
519
+ const check = STORE_CALLS.get(method);
520
+ if (!check || !check(args, bound)) {
521
+ log(`run ${bound.claim.runId}: its process asked the store for ${method}, which a run's process may not`);
522
+ throw new ClaimRefused(`a run's process may not call the store's ${method}${check ? " of another run or agent" : ""}`);
523
+ }
524
+ if (method === "readJournal")
525
+ return journalRead(store, args);
526
+ const path = method.split(".");
527
+ let target = store;
528
+ for (const part of path.slice(0, -1))
529
+ target = target[part];
530
+ const fn = target?.[path.at(-1)];
531
+ if (typeof fn !== "function")
532
+ throw new ClaimRefused(`the store has no ${method}`);
533
+ const answer = await fn.apply(target, args);
534
+ if (!answerBound(method, answer, bound)) {
535
+ log(`run ${bound.claim.runId}: its process asked for another agent's revision`);
536
+ throw new ClaimRefused("a run's process may read only its own agent's revisions");
537
+ }
538
+ if (method === "settings.all")
539
+ return dataOnly(answer.filter((row) => settingReadable(row.key, bound)));
540
+ return dataOnly(answer);
541
+ }
542
+ /** One read of the run's own journal (Store.readJournal of the claim's run, checked above), as the run's process asks
543
+ * it: `[runId, read, args]`. Store.readJournal is synchronous, so the process's reader (run-child.ts readerOf) is its
544
+ * own, each read of it one call here, on a reader opened for it and closed after. */
545
+ async function journalRead(store, args) {
546
+ const [runId, read, rest] = args;
547
+ if (typeof runId !== "string" || !Array.isArray(rest))
548
+ throw new ClaimRefused("a run's process reads its journal by a run, a read and its arguments");
549
+ const reads = store.readJournal(runId);
550
+ try {
551
+ return await readOf(reads, read, rest);
552
+ }
553
+ finally {
554
+ await reads.close(BACKGROUND_CONTEXT);
555
+ }
556
+ }
557
+ // ---------------------------------------------------------------------------------------------------------------------
558
+ // The journal, as the run's process writes it: the runner's own of the claim.
559
+ /** The journal target: the claim's journal (LoopDeps.journal, behind the runner's fence). Its records are kept as the run
560
+ * wrote them, as a runner's own loop keeps them (every read that shows one cuts it as it is served, and the run's
561
+ * learning end reads them whole to refuse a secret in them); what a stage writes beside them (the run's row, its
562
+ * summary, the rows a person is shown) is cut by the runner's redactor, which holds the server's secrets the process's
563
+ * own does not. A stage whose apply throws is held and fails the next commit, as the store would have. */
564
+ function journalTarget(journal, cut) {
565
+ let staged;
566
+ return async (method, args) => {
567
+ switch (method) {
568
+ case "commit": {
569
+ if (staged !== undefined) {
570
+ const error = staged;
571
+ staged = undefined;
572
+ throw error;
573
+ }
574
+ const seqs = [];
575
+ const result = await journal.commit(args[0], (index, seq) => void seqs.push([index, seq]), BACKGROUND_CONTEXT);
576
+ return { result: dataOnly(result), seqs };
577
+ }
578
+ case "stage":
579
+ try {
580
+ journal.stage(cutDeep(args[0], cut));
581
+ }
582
+ catch (error) {
583
+ staged = error;
584
+ }
585
+ return undefined;
586
+ case "mintId":
587
+ return journal.mintId();
588
+ case "close":
589
+ return undefined;
590
+ default:
591
+ return readOf(journal, method, args);
592
+ }
593
+ };
594
+ }
595
+ /** One of a journal's reads, `method` with the arguments the run's process passed (it passes no context: the read is made
596
+ * with the runner's own), its answer data alone. Anything but a read is refused. */
597
+ async function readOf(reads, method, args) {
598
+ switch (method) {
599
+ case "conversation":
600
+ case "task":
601
+ case "submission":
602
+ return dataOnly(await reads[method](args[0], BACKGROUND_CONTEXT));
603
+ case "entry":
604
+ return dataOnly(args.length >= 2 ? await reads.entry(args[0], args[1], BACKGROUND_CONTEXT) : await reads.entry(args[0], BACKGROUND_CONTEXT));
605
+ case "findLatestHeadMarker":
606
+ return dataOnly(await reads.findLatestHeadMarker(args[0], args[1], BACKGROUND_CONTEXT));
607
+ case "scanConversations":
608
+ case "scanEntries":
609
+ case "scanTasks":
610
+ case "scanSubmissions":
611
+ case "scanDocuments":
612
+ return dataOnly(await reads[method](args[0], args[1], args[2], BACKGROUND_CONTEXT));
613
+ case "submissionByRequest":
614
+ return dataOnly(await reads.submissionByRequest(args[0], args[1], BACKGROUND_CONTEXT));
615
+ case "findDocument":
616
+ case "document":
617
+ return dataOnly(await reads[method](args[0], args[1], BACKGROUND_CONTEXT));
618
+ case "commitsAfter":
619
+ return dataOnly(await reads.commitsAfter(args[0], args[1], BACKGROUND_CONTEXT));
620
+ default:
621
+ throw new ClaimRefused(`a run's journal has no read ${String(method)}`);
622
+ }
623
+ }
624
+ /** The email tools a revision may grant. */
625
+ const grantsEmail = (granted) => granted.some((tool) => tool.startsWith("email_"));
626
+ /** Held (held.ts) for one claim, on the runner: each answer the claim's own, read with the runner's seal key from the
627
+ * runner's own reads of the claim; every argument from the run's process is checked or ignored. */
628
+ export function heldFor(deps, reads, cut, log) {
629
+ const { claim, run, launch, revision, claimed } = reads;
630
+ const sealKey = deps.sealKey;
631
+ const store = deps.store;
632
+ const granted = revision.body.tools ?? [];
633
+ const keys = { store, sealKey, env: deps.env };
634
+ const releases = [];
635
+ const fromGitHub = launch.inputOrigin?.kind === "trigger" && launch.inputOrigin.source === "github";
636
+ const github = () => githubAppAccess(store, sealKey, launch.input, { ...(deps.githubApi ? { api: deps.githubApi } : {}), fromGitHub, ...(launch.repo !== undefined ? { repo: launch.repo } : {}) });
637
+ /** Mode 2's Archil claim, made once for the claim on the runner, its folder the run's. */
638
+ let archil;
639
+ const archilOf = () => (archil ??= (async () => {
640
+ const settings = await loadArchilSettings(store, deps.env);
641
+ if (settings === undefined)
642
+ return undefined;
643
+ const made = await archilClaim({ settings, keys: store.sealedKeys, sealKey, signal: new AbortController().signal, env: deps.env, mount: { runId: claim.runId, epoch: claim.epoch, ttlMs: MOUNT_TTL_MS, ...(deps.mountControl ?? {}) }, run: { agentId: run.agentId, ...(launch.archilDisk ? { launch: launch.archilDisk } : {}), store }, ...(deps.makeArchilDisk ? { makeDisk: deps.makeArchilDisk } : {}) });
644
+ releases.push(() => made.release());
645
+ return made;
646
+ })());
647
+ /** Whether the claim's run holds a model key of its own now (its launch, as this runner opens it): its process is then
648
+ * handed none of the server's (claim-secrets.ts keyedAtClaim, held here for the runner's answers). */
649
+ const runKeyed = async () => (await openRunModelKey(keys, claim.runId)) !== undefined;
650
+ const learningFolder = async () => {
651
+ const made = await archilOf();
652
+ return made === undefined ? learningFolderOf(deps.data, run.agentId) : learningWorkspace({ mode: "archil", agentId: run.agentId, archil: made });
653
+ };
654
+ /** The learning folder's reader, made once the claim's Archil claim is known (learnedFirst's folder is synchronous). */
655
+ const folderNow = async () => {
656
+ const made = await archilOf();
657
+ return () => (made === undefined ? learningFolderOf(deps.data, run.agentId) : learningWorkspace({ mode: "archil", agentId: run.agentId, archil: made }));
658
+ };
659
+ /** What a learned workflow must never hold, as this runner sees it: every secret it holds (learning-seed.ts). */
660
+ const shown = async () => secretsShown(runnerSecrets(deps.env, await storeSecrets(store, sealKey, deps.data)), { local: true });
661
+ /** The workflows the claim's learned_workflow tool runs, as this runner chose them (held.learnedFirst): what scopes the
662
+ * tier and decision keys it hands. None until it chose. */
663
+ let learnedFlows = [];
664
+ /** The claim's one learned first choice: its promotion's writes are made once, however often the process asks. */
665
+ let chosen;
666
+ const held = {
667
+ plan: async () => {
668
+ const plan = planOf(claimed);
669
+ if (!plan)
670
+ return undefined;
671
+ return { state: plan.state, models: [...plan.models], token: () => plan.token(), refused: (sent) => plan.refused(sent), watch: (listener) => plan.watch(listener) };
672
+ },
673
+ signInReadsBack: () => handedSignInReadsBack(store, sealKey, run),
674
+ runSignIn: (resolution) => {
675
+ const vendorFetch = async () => (claimed[FAUX_ENV] ? fauxFetch(claimed, FAUX_VENDOR_API_ENV) : fetch);
676
+ return runSignIn(store, sealKey, claim, String(resolution), { vendors: vendorsOver(() => claimed, vendorFetch), log });
677
+ },
678
+ verifySignIn: (kept, at) => verifyRunSignIn(store, sealKey, claim, kept, Number(at)),
679
+ mcp: async (ask) => {
680
+ const reach = await mcpReachOf(deps);
681
+ const harness = { commit: (change) => change({ appendEntry: async (_conversation, entry) => void (await ask.appendRoot(dataOnly(entry))) }) };
682
+ const made = await mcpForClaim({ claim, store, sealKey, grants: granted, harness: harness, work: () => runFolder(deps.data, run.agentId, claim.runId), launchInput: launch.input, githubAppAccess: () => github(), ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}), ...reach });
683
+ if (!made)
684
+ return undefined;
685
+ releases.push(() => made.release());
686
+ return heldMcpOf(made, cut);
687
+ },
688
+ githubAppAccess: async () => {
689
+ // A run's process mints for one thing alone: its revision's pull-request checkout (pr-checkout.ts), of the pull
690
+ // request its launch's payload names, contents read. Its MCP mints on the runner (mcp above). So the mint handed
691
+ // here makes that token and no other, whatever repository or permissions the process names.
692
+ if (revision.body.checkout !== "pull_request")
693
+ return undefined;
694
+ const pull = githubPullOf(isObject(launch.input) ? launch.input.content : launch.input, { payload: fromGitHub });
695
+ if (!pull)
696
+ return undefined;
697
+ const access = await github();
698
+ if (!access)
699
+ return undefined;
700
+ const bound = { repo: pull.repo, ...(pull.installation !== undefined ? { installation: pull.installation } : {}) };
701
+ const mint = async (to) => {
702
+ if (to?.repo !== bound.repo || to.installation !== bound.installation) {
703
+ log(`run ${claim.runId}: its process asked for a GitHub token of another repository than its pull request's, which a run's process may not`);
704
+ throw new ClaimRefused("a run's process mints a GitHub token only for its own pull request's repository");
705
+ }
706
+ return access.mint(bound, { contents: "read" });
707
+ };
708
+ return { api: access.api, target: bound, mint, ...(access.revoke ? { revoke: access.revoke } : {}), ...(access.same ? { same: access.same } : {}) };
709
+ },
710
+ savedModelKeys: async () => {
711
+ // Only a run whose routes have no revision to scope their keys by: a subagent's tiers, a learning run's grade, an SDK
712
+ // run's grade. And never for a run that holds a key of its own (its launch's, read now): the server's keys are not
713
+ // its to spend, whatever its process asks.
714
+ const reads = granted.includes(SUBAGENT_TOOL) || launch.harness === "learning" || launch.sdk !== undefined;
715
+ const keyed = await runKeyed();
716
+ return reads ? stringsOf(keyed ? {} : await savedModelKeys(keys)) : {};
717
+ },
718
+ tierModelKeys: async (tiers) => {
719
+ // The tiers the claim's learned workflows name (learnedTiers), as this runner chose them (learnedFirst below): a
720
+ // tier the process names beyond them gets no key, and none before the choice.
721
+ const asked = new Set(tiers.filter((tier) => typeof tier === "string"));
722
+ const named = learnsWorkflows(revision.kind, learnedFlows) ? learnedTiers(learnedFlows).filter((tier) => asked.has(tier)) : [];
723
+ const keyed = await runKeyed();
724
+ const got = keyed ? {} : await tierModelKeys(keys, named);
725
+ const plan = planOf(got);
726
+ return { keys: stringsOf(got), ...(plan ? { plan: { state: plan.state, models: [...plan.models], token: () => plan.token(), refused: (sent) => plan.refused(sent), watch: (listener) => plan.watch(listener) } } : {}) };
727
+ },
728
+ // The decision providers the claim's learned workflows' questions name (learnedDecisionKeys), as this runner chose
729
+ // them: of those, the ones the process asks for (its gate's allowed). Any other provider gets no key.
730
+ decisionKeys: async (providers) => {
731
+ const asked = new Set(providers.filter((one) => typeof one === "string"));
732
+ return learnsWorkflows(revision.kind, learnedFlows) ? learnedDecisionKeys(keys, learnedFlows, (provider) => asked.has(provider)) : {};
733
+ },
734
+ // The claim's own run's key alone (its launch, as the runner reads it), whatever run the process would name.
735
+ runModelKey: () => openRunModelKey(keys, claim.runId),
736
+ serverKeyless: () => serverKeyless(keys),
737
+ // The zone alone, from the claim's own launch's trigger: the process never reads a trigger's row.
738
+ runZone: () => runZone(store, launch.inputOrigin),
739
+ liveViewerPut: (handover) => putLiveViewer(store, sealKey, claim, handover),
740
+ liveViewerDrop: (tag) => dropLiveViewer(store, claim, tag),
741
+ handOn: async (from, id) => {
742
+ if (from !== claim.runId || typeof id !== "string")
743
+ return undefined;
744
+ const sealed = await store.runs.launch(from).then((one) => one.sealed ?? null, () => null);
745
+ const handed = sealed === null ? undefined : openRunMcpAuth(sealKey, from, sealed);
746
+ return handed && Object.keys(handed).length ? sealRunMcpAuth(sealKey, id, handed) : undefined;
747
+ },
748
+ signInPeek: (resolution) => peekSignIn(store, sealKey, run.agentId, String(resolution)),
749
+ signInForgotten: (resolution) => forgottenSignIns(store, sealKey, run.agentId, String(resolution)),
750
+ emailAccount: async () => (grantsEmail(granted) ? openAccount(store, sealKey) : undefined),
751
+ calendar: async () => (granted.includes(CALENDAR_EVENTS) ? openCalendar(store, sealKey) : undefined),
752
+ learning: async (method, args) => learningCall(await learningFolder(), method, args),
753
+ install: async (name, signal) => {
754
+ const harness = launch.harness ?? revision.body.harness;
755
+ const entry = harness === undefined ? undefined : harnessOf(deps.env, harness);
756
+ if (!harness || !entry?.installs || !entry.pins || entry.installs.id !== name)
757
+ throw new ClaimRefused(`the run's harness installs no ${JSON.stringify(name)}`);
758
+ const lock = deps.harnessLocks?.[harness];
759
+ await (deps.installForClaim ?? installForClaim)(entry.installs, installDirOf(deps.data, harness), entry.pins, { ...(lock ? { lock } : {}), ...(signal ? { signal } : {}) });
760
+ // The run's process, a slot's user, loads the install itself: read and traverse for every user, never write, an
761
+ // install from before installs were shared too.
762
+ await shareInstall(installDirOf(deps.data, harness));
763
+ },
764
+ computer: async (ask) => {
765
+ const made = await archilOf();
766
+ const mode = made === undefined ? 1 : 2;
767
+ const ws = made === undefined
768
+ ? await openRunWorkspace({ mode: 1, agentId: run.agentId, runId: claim.runId, data: deps.data, log })
769
+ : await openRunWorkspace({ mode: 2, agentId: run.agentId, runId: claim.runId, archil: made, log });
770
+ const say = typeof ask.say === "function" ? ask.say : undefined;
771
+ const got = await deps.computerForClaim({ runId: claim.runId, epoch: claim.epoch, claim, agentId: run.agentId, revisionId: run.revisionId, place: launch.place }, store, {
772
+ ...deps.computerDeps, mode, workspace: ws.workspace, sealKey,
773
+ recordings: { folder: recordingsFolder(deps.data, run.agentId, claim.runId), say: (words) => say?.(cut(words)) },
774
+ hadComputer: async () => (await ask.hadComputer()) === true,
775
+ ...(ask.signal instanceof AbortSignal ? { signal: ask.signal } : {}),
776
+ ...(made ? { revokeMount: () => made.revoke(), inheritMount: () => made.inherit() } : {}),
777
+ ...(typeof ask.onImageWait === "function" ? { onImageWait: ask.onImageWait } : {}),
778
+ ...(typeof ask.onStarting === "function" ? { onStarting: ask.onStarting } : {}),
779
+ ...(typeof ask.onConnected === "function" ? { onConnected: ask.onConnected } : {}),
780
+ ...(typeof ask.onComputerNote === "function" ? { onComputerNote: ask.onComputerNote } : {}),
781
+ });
782
+ releases.push(() => ws.end());
783
+ // The computer let go by this runner at the claim's release too, before its folder: a process that crashed or broke
784
+ // its channel never calls its release. Idempotent with the process's own release and with its park (which keeps it).
785
+ const claimed = got;
786
+ if (typeof claimed?.release === "function")
787
+ releases.push(() => claimed.release("ended"));
788
+ return got;
789
+ },
790
+ archil: async () => {
791
+ const made = await archilOf();
792
+ if (made === undefined)
793
+ return undefined;
794
+ const ws = await openRunWorkspace({ mode: 2, agentId: run.agentId, runId: claim.runId, archil: made, log });
795
+ releases.push(() => ws.end());
796
+ return { workspace: ws.workspace, revoke: () => made.revoke(), inherit: async () => made.inherit(), release: async () => { } };
797
+ },
798
+ endOfRun: async (input) => {
799
+ // The step as the run's spec builds it in a runner (adapter-run-spec.ts), over the runner's reads of the claim: what
800
+ // the run must never learn is every secret this runner holds, the keys its claim handed it, every secret the server
801
+ // keeps sealed and its sign-in's pointers, none of which the run's process is given.
802
+ // A replay run or an audit's shadow run asks nothing at its end, as the run's spec says (adapter-run-spec.ts).
803
+ if (launch.replay || launch.audit)
804
+ return undefined;
805
+ const made = await archilOf();
806
+ // The audit's spend, skipped as the run's spec skips it (claim-secrets.ts claimSpendOff): over the claim's own key.
807
+ const spendOff = await claimSpendOff(keys, await claimModelKey(keys, claim.runId));
808
+ // The audit's start after the step (audit.ts withAudit) is this runner's too: it reads the run's journal and writes
809
+ // the ledger and a run.
810
+ const step = withAudit(learningEndOfRun(launch, {
811
+ store,
812
+ data: deps.data,
813
+ ...(deps.env ? { env: deps.env } : {}),
814
+ signIns: signInReads(store, sealKey),
815
+ handed: runnerSecrets(claimed),
816
+ stored: () => storeSecrets(store, sealKey, deps.data),
817
+ log,
818
+ decisionProviders: async () => decisionProvidersIn({ ...(deps.env ?? {}), ...(await hostDecisionKeys(keys, DECISION_PROVIDER_KEYS)) }),
819
+ learningFolder: made === undefined ? (agentId) => learningFolderOf(deps.data, agentId) : (agentId) => learningWorkspace({ mode: "archil", agentId, archil: made }),
820
+ }), { store, agentId: run.agentId, revisionId: run.revisionId, context: BACKGROUND_CONTEXT, folder: await folderNow(), shown, log, sealKey, spendOff, launch, redact: cut });
821
+ if (!step)
822
+ return undefined;
823
+ // keptOf is the run's process's, asked over the channel: read once, for the round learningEndOfRun reads (the
824
+ // round after the newest the run kept), before the step reads it at once.
825
+ const prior = await store.learning.proposal(claim.runId);
826
+ const round = prior ? prior.round + 1 : 1;
827
+ const kept = typeof input.keptOf === "function" ? await input.keptOf(round) : undefined;
828
+ const ask = input.ask;
829
+ const rows = await step({
830
+ runId: claim.runId,
831
+ agentId: run.agentId,
832
+ claim,
833
+ outcome: input.outcome === "failed" ? "failed" : "completed",
834
+ // A cut the runner does not know is a fault: never an end the run reached on its own, which starts an audit.
835
+ ...(input.cut === undefined ? {} : { cut: input.cut === "stopped" || input.cut === "stopped-looking" ? input.cut : "faulted" }),
836
+ ask: (prompt, opts) => ask(prompt, opts),
837
+ keptOf: (asked) => (asked === round ? kept : undefined),
838
+ signal: input.signal,
839
+ });
840
+ return rows === undefined ? undefined : { also: dataOnly(rows.also ?? []) };
841
+ },
842
+ learnedFirst: (ask) => (chosen ??= (async () => {
843
+ // The workflows the claim's seed lays, read by this runner at the launch's seed (learning-seed.ts workflowsAt), as
844
+ // the process's lay chose them: none where its lay laid none (`laid` false: a read that failed, a seed with no
845
+ // workflows).
846
+ const start = learningStartOf(launch);
847
+ const folder = await folderNow();
848
+ const laid = ask?.laid === true && start && !seedFailed(start) && !start.noWorkflows ? await workflowsAt({ folder, shown }, start.seed).catch(() => []) : [];
849
+ const spendOff = await claimSpendOff(keys, await claimModelKey(keys, claim.runId));
850
+ const outputSchema = revision.body.outputSchema;
851
+ const got = await learnedFirst({ store, sealKey, agentId: run.agentId, runId: claim.runId, revisionId: run.revisionId, kind: revision.kind, ...(outputSchema !== undefined ? { outputSchema } : {}), launch, context: BACKGROUND_CONTEXT, log, folder, shown, spendOff }, laid);
852
+ learnedFlows = got.workflows;
853
+ return cutDeep(dataOnly(got), cut);
854
+ })()),
855
+ liveAt: async () => {
856
+ const live = runnerLiveOf(deps.env ?? {}, sealKey);
857
+ if (!live)
858
+ return undefined;
859
+ const own = liveForRun(live, claim.runId);
860
+ return { host: own.host, bind: own.bind, key: new Uint8Array(own.key) };
861
+ },
862
+ };
863
+ return {
864
+ held,
865
+ inputs: async () => {
866
+ // The run's uploads and its opening message (uploads.ts placeRunInputs), placed by this runner before the run's
867
+ // process starts: their hold is the server's alone.
868
+ const made = await archilOf();
869
+ const ws = made === undefined
870
+ ? await openRunWorkspace({ mode: 1, agentId: run.agentId, runId: claim.runId, data: deps.data, log })
871
+ : await openRunWorkspace({ mode: 2, agentId: run.agentId, runId: claim.runId, archil: made, log });
872
+ try {
873
+ await placeRunInputs(deps.data, claim.runId, ws.workspace, launch.files ?? [], messageText(launch.input));
874
+ }
875
+ finally {
876
+ await ws.end();
877
+ }
878
+ },
879
+ release: async () => {
880
+ for (const release of releases.reverse())
881
+ await Promise.resolve(release()).catch((error) => log(`run ${claim.runId}: a release on its runner failed: ${error?.message ?? error}`));
882
+ },
883
+ };
884
+ }
885
+ /** `env`'s string values. */
886
+ const stringsOf = (env) => Object.fromEntries(Object.getOwnPropertyNames(env).flatMap((name) => (typeof env[name] === "string" ? [[name, env[name]]] : [])));
887
+ /** The learning-script ops a run's process may run (learn/folder.ts): its reads alone. The folder's writers (the
888
+ * end-of-run step's check, the learning run's merge, a repair) are the runner's. */
889
+ const LEARNING_OPS = new Set(["read", "show", "has", "log", "diff", "status"]);
890
+ /** A call of the learning folder a run's process asks (Held.learning), on the runner's own Workspace of the claim's
891
+ * agent's folder: reads pass, and the learning script runs its reads, with the script's own environment (the script
892
+ * laid by the runner as the folder's own); nothing the process asks writes there. */
893
+ export async function learningCall(folder, method, args) {
894
+ const ws = folder.workspace;
895
+ try {
896
+ switch (method) {
897
+ case "read":
898
+ return await ws.read(String(args[0]), args[1]);
899
+ case "stat":
900
+ return dataOnly(await ws.stat(String(args[0])));
901
+ case "list":
902
+ return dataOnly(await ws.list(String(args[0])));
903
+ case "grep":
904
+ return dataOnly(await ws.grep(String(args[0]), args[1]));
905
+ case "write":
906
+ // The learning script laid as learn/folder.ts lays it (ensureScript, before a script run): the runner's own text.
907
+ if (args[0] === LEARNING_SCRIPT.file())
908
+ return await LEARNING_SCRIPT.ensure(ws);
909
+ throw new ClaimRefused(`a run's process may not write ${JSON.stringify(args[0])} in its learning folder`);
910
+ case "append":
911
+ case "remove":
912
+ case "mkdir":
913
+ throw new ClaimRefused(`a run's process may not ${method} ${JSON.stringify(args[0])} in its learning folder`);
914
+ case "exec": {
915
+ const argv = args[0];
916
+ const options = (args[1] ?? {});
917
+ if (!Array.isArray(argv) || argv[0] !== "sh" || argv[1] !== LEARNING_SCRIPT.file() || !LEARNING_OPS.has(String(argv[2])) || !argv.every((part) => typeof part === "string"))
918
+ throw new ClaimRefused("a run's process runs no program in its learning folder but its learning script");
919
+ await LEARNING_SCRIPT.ensure(ws);
920
+ return dataOnly(await ws.exec(argv, { env: LEARNING_SCRIPT.env(), timeoutMs: LEARNING_SCRIPT.timeoutMs(), ...(options.stdin instanceof Uint8Array ? { stdin: options.stdin } : {}) }));
921
+ }
922
+ default:
923
+ throw new ClaimRefused(`a run's learning folder has no ${method} in its process`);
924
+ }
925
+ }
926
+ finally {
927
+ await folder.end().catch(() => undefined);
928
+ }
929
+ }
930
+ /** The node and module a run's process starts with. */
931
+ export const childArgv = () => [process.execPath, "--import", new URL("../secrets.js", import.meta.url).pathname, new URL("./run-child.js", import.meta.url).pathname];
932
+ /** Whether a run stays in its runner's process rather than one of its own: one that runs no agent's code or tool here.
933
+ * A built-in learning run (its launch names harness "learning"): its grade is one ask through the runner's model route,
934
+ * and its one write is the merge into the agent's learning folder, which no run's process may write. An SDK backend
935
+ * run (launch.sdk): its agent runs in the caller's application, and its loop here reads the evidence it posts and closes
936
+ * its inbox. A native run (launch.native): its agent is the source machine's own sign-in, reached through the server's
937
+ * connectors, whose rows are the server's. */
938
+ export const runsInRunner = (harness, launch) => harness === "learning" || Boolean(launch.sdk) || Boolean(launch.native);
939
+ /** The words a run on Claude Code's login on this machine is refused in where each run is a user of its own. */
940
+ export const LOGIN_NEEDS_SERVER_USER = `A run on Claude Code's login on this machine needs runs under the server's own user, and this runner runs each run as a user of its own: set ${RUN_USER_ENV}=same, or give the run a model_key.`;
941
+ /** Whether run `runId` stays in its runner's process: runsInRunner's, and a workflow run on a server with a documents
942
+ * directory (launch.documents), whose reads and writes (a pdf_pages call's pages) are rooted in a folder the server's
943
+ * user holds and no slot's user is given; its nodes run the server's own tools alone, no agent's code. A run on Claude
944
+ * Code's login on this machine (claude-login.ts loginForRun) needs the login in the server's own folder, which its CLI
945
+ * reads and refreshes: where runs are the runner's own user (`process`) it stays in the runner; where each run is a user
946
+ * of its own (`uid`) it is refused at its claim (ClaimRefused, the run failed in words naming the setting), never run as
947
+ * the server's user. A run its caller handed a model key (model_key) runs on that key and never on the login
948
+ * (cli-run-spec.ts), so it is a process of its own like any other. */
949
+ export async function staysInRunner(deps, harness, launch, runId, isolation) {
950
+ if (runsInRunner(harness, launch))
951
+ return true;
952
+ if (launch.documents !== undefined) {
953
+ const run = await deps.store.runs.get(runId);
954
+ const revision = run ? await deps.store.agents.revision(run.revisionId) : undefined;
955
+ if (revision && isWorkflowRevision(revision))
956
+ return true;
957
+ }
958
+ if ((await loginForRun(deps.store.settings, deps.data, deps.env ?? {}, harness, launch.place)) === undefined)
959
+ return false;
960
+ if ((await openRunModelKey({ store: deps.store, sealKey: deps.sealKey }, runId)) !== undefined)
961
+ return false;
962
+ if (isolation.kind === "uid")
963
+ throw new ClaimRefused(LOGIN_NEEDS_SERVER_USER);
964
+ return true;
965
+ }
966
+ /** The runner's loop factory where each run is a process of its own: a ChildLoop per claim, but for a run that stays in
967
+ * the runner (staysInRunner). */
968
+ export function childLoops(options) {
969
+ // Each slot locked on the data directory too: another runner on it whose range overlaps this one's never runs a run
970
+ // on a slot this one holds.
971
+ const slots = options.isolation.kind === "uid" ? new Slots(options.isolation.first, options.isolation.slots, slotLocks(options.deps.data)) : undefined;
972
+ const own = (loopDeps) => childLoop(options, slots, loopDeps);
973
+ const here = resolveRunnerLoop(options.deps);
974
+ return createDispatchLoop({
975
+ launchOf: (runId) => options.deps.store.runs.launch(runId),
976
+ resolve: async (harness, launch, runId) => ((await staysInRunner(options.deps, harness, launch, runId, options.isolation)) ? here(harness, launch, runId) : own),
977
+ });
978
+ }
979
+ registerRunErrors();
980
+ /** The environment a run's process starts with: the runner's run environment's plain values (runEnv: its secrets are
981
+ * not enumerable, so none is here), no key-shaped name, and where its keys come from. */
982
+ function childEnv(base, keys, extra) {
983
+ const plain = {};
984
+ for (const name of Object.keys(base))
985
+ if (typeof base[name] === "string")
986
+ plain[name] = base[name];
987
+ const env = withoutSecrets(plain);
988
+ for (const name of SECRET_NAMES)
989
+ delete env[name];
990
+ return { ...env, ...extra, [SECRETS_FD_ENV]: "3", [SECRETS_LEN_ENV]: String(keys.length) };
991
+ }
992
+ function childLoop(options, slots, loopDeps) {
993
+ const { deps, isolation } = options;
994
+ const cut = loopDeps.redact ?? ((text) => text);
995
+ const log = (line) => options.log(cut(line));
996
+ let channel;
997
+ let child;
998
+ let exited;
999
+ let stopping;
1000
+ let keeps = false;
1001
+ let latest;
1002
+ let started;
1003
+ /** Resolved once the run's process has its channel (or its start failed first): a command or a stop handed over
1004
+ * before then waits for it, as the dispatch buffers what comes before its inner loop is chosen. */
1005
+ let ready;
1006
+ const up = new Promise((resolve) => (ready = resolve));
1007
+ /** This run's hold on its slot (uid isolation), bound at its spawn and settled before the slot goes back. */
1008
+ let hold;
1009
+ /** Kills the run's process and every process it started: its group (process isolation; a program that left the group
1010
+ * with setsid escapes it, a local install's limit), or every process of its own slot's uid while it holds the slot
1011
+ * (uid isolation: never a slot it gave back, which another run may hold). */
1012
+ const kill = async () => {
1013
+ if (isolation.kind === "uid")
1014
+ return hold?.kill();
1015
+ if (child?.pid === undefined)
1016
+ return;
1017
+ try {
1018
+ process.kill(-child.pid, "SIGKILL");
1019
+ }
1020
+ catch { }
1021
+ };
1022
+ /** Ends the run's process: its channel closed (its loop ended), a grace to exit, then everything it left killed and, on
1023
+ * a slot, the slot reaped. */
1024
+ const end = async (slot, tops) => {
1025
+ let timer;
1026
+ const gone = exited ? Promise.race([exited, new Promise((resolve) => (timer = setTimeout(resolve, EXIT_GRACE_MS)))]) : Promise.resolve();
1027
+ channel?.close();
1028
+ await gone;
1029
+ clearTimeout(timer);
1030
+ let reaped = true;
1031
+ if (isolation.kind === "uid" && slot !== undefined)
1032
+ reaped = await reapSlot(isolation, slot, tops, log);
1033
+ else
1034
+ await kill();
1035
+ await exited?.catch(() => undefined);
1036
+ return reaped;
1037
+ };
1038
+ /** Gives the slot back where its reap held, else retires it (Slots.retire), said on the log. */
1039
+ const letGo = async (slot, reaped, runId) => {
1040
+ if (slot === undefined || !slots)
1041
+ return;
1042
+ if (reaped)
1043
+ return slots.give(slot);
1044
+ slots.retire(slot);
1045
+ log(`run ${runId}: slot ${slot} is retired: its reap did not end every process of its user, so no run of this runner runs on it again until the runner restarts`);
1046
+ };
1047
+ return {
1048
+ start(claim) {
1049
+ return (started ??= (async () => {
1050
+ const runRow = await deps.store.runs.get(claim.runId);
1051
+ if (!runRow)
1052
+ throw new Error(`run ${claim.runId}: its row is gone from the store`);
1053
+ const launch = readLaunchBody((await deps.store.runs.launch(claim.runId)).body);
1054
+ if (!launch)
1055
+ throw new Error(`run ${claim.runId}: its launch record could not be read as a launch`);
1056
+ const revisionRow = await deps.store.agents.revision(runRow.revisionId);
1057
+ if (!revisionRow)
1058
+ throw new Error(`run ${claim.runId}: its revision ${runRow.revisionId} is gone from the store`);
1059
+ const revision = { kind: revisionRow.kind, body: (revisionRow.body ?? {}) };
1060
+ // The run's own keys: those its claim opens (claim-secrets.ts), the one list its loop in this process read.
1061
+ const claimed = await claimSecrets({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, revisionRow, launch);
1062
+ // With them, its revision's own model's (a launch pinned at its start to another model, a --faux start's, is still
1063
+ // handed its agent's model's key, as a run's own process was handed it before: run-secrets.ts secretsFor).
1064
+ const ofRevision = await claimSecrets({ store: deps.store, sealKey: deps.sealKey, env: deps.env }, revisionRow, { ...(launch.plane ? { plane: launch.plane } : {}) });
1065
+ // A run that holds a model key of its own (model_key, its launch's) spends that key alone: its process is handed
1066
+ // none of the server's model keys, as its spec drops them from its tools' (claim-secrets.ts withoutModelKeys).
1067
+ // Copies: the runner's own reads (heldFor's `claimed`: what the run's learning must never keep) stay whole.
1068
+ const keyed = (await openRunModelKey({ store: deps.store, sealKey: deps.sealKey }, claim.runId)) !== undefined;
1069
+ const toProcess = keyed ? [withoutModelKeys({ ...claimed }), withoutModelKeys({ ...ofRevision })] : [claimed, ofRevision];
1070
+ const handed = (name) => toProcess.map((from) => from[name]).find((value) => typeof value === "string" && value !== "");
1071
+ const keys = encode(SECRET_NAMES.flatMap((name) => {
1072
+ const value = handed(name);
1073
+ return value === undefined ? [] : [[name, value]];
1074
+ }));
1075
+ const slot = await slots?.take();
1076
+ if (slots && slot === undefined) {
1077
+ // Every free slot of this runner is held by another runner on the data directory (ranges that overlap): the run
1078
+ // is handed back unstarted, for a runner with a slot to claim.
1079
+ log(`run ${claim.runId}: handed back unstarted: every free slot of this runner is held by another runner on this data directory; give each runner on one data directory a range of its own (${RUN_SLOT_FIRST_ENV}, --loops)`);
1080
+ ready();
1081
+ return { state: "interrupted" };
1082
+ }
1083
+ // A slot is reaped before its first run here too: a runner that died (its locks ended with it) may have left a
1084
+ // process of the slot's uid alive, which must never share a user with this run. A reap that does not hold
1085
+ // retires the slot, and the run is handed back unstarted.
1086
+ if (isolation.kind === "uid" && slot !== undefined && !(await reapSlot(isolation, slot, [], log))) {
1087
+ await letGo(slot, false, claim.runId);
1088
+ ready();
1089
+ return { state: "interrupted" };
1090
+ }
1091
+ if (isolation.kind === "uid" && slot !== undefined)
1092
+ hold = new SlotHold(slot, isolation.helper, log);
1093
+ const tops = runTops(deps.data, runRow.agentId, claim.runId);
1094
+ const heldSide = heldFor(deps, { claim, run: runRow, launch, revision, claimed }, cut, log);
1095
+ try {
1096
+ let extra = {};
1097
+ let argv = [...(options.argv ?? childArgv())];
1098
+ // The run's uploads and opening message, placed by the runner before its process starts (their hold is the
1099
+ // server's alone), then given to the slot with its folders.
1100
+ await heldSide.inputs();
1101
+ if (isolation.kind === "uid" && slot !== undefined) {
1102
+ await layRunFolders(isolation, deps.data, runRow.agentId, claim.runId, slot);
1103
+ const scratch = scratchFolder(deps.data, runRow.agentId, claim.runId);
1104
+ const tmp = join(scratch, "tmp");
1105
+ extra = { TMPDIR: tmp, HOME: scratch };
1106
+ argv = [isolation.helper, "run", String(slot), "--keep-fd", "3", "--keep-fd", "4", "--", ...argv];
1107
+ }
1108
+ const env = childEnv(deps.env, keys, extra);
1109
+ const [program, ...rest] = argv;
1110
+ child = spawn(program, rest, { stdio: ["ignore", "inherit", "inherit", "pipe", "pipe"], env, detached: true });
1111
+ exited = new Promise((resolve) => {
1112
+ child.once("exit", (code, signal) => resolve({ code, signal }));
1113
+ // A process that never started has no exit to wait for.
1114
+ child.once("error", (error) => {
1115
+ log(`run ${claim.runId}: its process did not start: ${error.message}`);
1116
+ resolve({ code: null, signal: null });
1117
+ });
1118
+ });
1119
+ const keyPipe = child.stdio[3];
1120
+ keyPipe.on("error", () => undefined);
1121
+ keyPipe.end(keys);
1122
+ const socket = child.stdio[4];
1123
+ let broke;
1124
+ // Each call of the run's process runs inside the ledger of the tool call it was made in (paid-calls.ts).
1125
+ channel = new Channel(socket, { onClose: (why) => void (broke ??= why), within: withinCarried });
1126
+ const bound = { claim, agentId: runRow.agentId, revisionId: runRow.revisionId };
1127
+ channel.expose("store", (method, args) => storeCall(deps.store, method, args, bound, log));
1128
+ channel.expose("journal", journalTarget(loopDeps.journal(claim), cut));
1129
+ channel.expose("held", (method, args) => {
1130
+ // Its own members alone: a name of Object's prototype (constructor, toString) is no call of Held.
1131
+ const fn = Object.hasOwn(heldSide.held, method) ? heldSide.held[method] : undefined;
1132
+ if (typeof fn !== "function")
1133
+ throw new ClaimRefused(`the runner holds no ${method} for a run`);
1134
+ return fn(...args);
1135
+ });
1136
+ channel.expose("runner", async (method, args) => {
1137
+ switch (method) {
1138
+ case "flush":
1139
+ return loopDeps.flush();
1140
+ case "delivered":
1141
+ return loopDeps.delivered;
1142
+ case "deliverNow":
1143
+ return loopDeps.deliverNow?.();
1144
+ case "live":
1145
+ latest = (args[0] ?? undefined);
1146
+ keeps = args[1] === true;
1147
+ return undefined;
1148
+ case "log":
1149
+ return void log(String(args[0]));
1150
+ default:
1151
+ throw new ClaimRefused(`the runner has no ${method} for a run`);
1152
+ }
1153
+ });
1154
+ loopDeps.live?.(() => latest);
1155
+ const reach = await mcpReachOf(deps);
1156
+ const init = {
1157
+ claim, data: deps.data, signal: loopDeps.signal, where: deps.store.where,
1158
+ ...(reach.loopback ? { mcpLoopback: true, mcpOwn: reach.own ?? [] } : {}),
1159
+ ...(deps.githubApi ? { githubApi: deps.githubApi } : {}),
1160
+ ...(deps.githubWeb ? { githubWeb: deps.githubWeb } : {}),
1161
+ ...(deps.githubMcpOrigin ? { githubMcpOrigin: deps.githubMcpOrigin } : {}),
1162
+ };
1163
+ const ended = channel.call("loop", "start", [init]);
1164
+ // From here a command or a stop goes to the run's process, after its start on the channel.
1165
+ ready();
1166
+ const died = exited.then((how) => {
1167
+ throw Object.assign(new ChannelClosed(`the run's process exited (${how.signal ?? `code ${how.code}`}) before its loop ended`), { died: true });
1168
+ });
1169
+ try {
1170
+ return (await Promise.race([ended, died]));
1171
+ }
1172
+ catch (error) {
1173
+ if (stopping?.kind === "claim-lost" || stopping?.kind === "shutdown")
1174
+ return { state: "interrupted" };
1175
+ // The run's process is gone with no end of its own written: thrown, so the runner writes the run's end, failed
1176
+ // with why (runner.ts: a loop that threw), as for a loop of its own that threw.
1177
+ if (error instanceof ChannelClosed || error.died)
1178
+ throw new Error(cut(`the run's process ended with its run: ${broke && !error.died ? `it broke its channel: ${broke.message}` : error.message}`));
1179
+ throw error;
1180
+ }
1181
+ }
1182
+ finally {
1183
+ ready();
1184
+ const reaped = await end(slot, tops).catch((error) => {
1185
+ log(`run ${claim.runId}: its process's end failed: ${error?.message ?? error}`);
1186
+ return false;
1187
+ });
1188
+ await heldSide.release();
1189
+ // The run's scratch folder, which its process may not remove (the folder above it is the server's): swept here
1190
+ // once the reap made what is in it the server's, as a run in the runner's own process sweeps it.
1191
+ if (reaped && isolation.kind === "uid" && slot !== undefined)
1192
+ await sweepRunScratch(deps.data, runRow.agentId, claim, log);
1193
+ // No kill of this run reaps the slot once it is given back: those still reaping end first.
1194
+ await hold?.settle();
1195
+ await letGo(slot, reaped, claim.runId);
1196
+ }
1197
+ })());
1198
+ },
1199
+ async command(command) {
1200
+ // A row handed over before the run's process is up waits for it (never `later`: an approve that comes as the claim
1201
+ // starts is this claim's to answer).
1202
+ if (!started)
1203
+ return { later: "the run's loop has not started" };
1204
+ await up;
1205
+ if (!channel || channel.closed)
1206
+ return { later: "the run's process is not running" };
1207
+ return (await channel.call("loop", "command", [dataOnly(command)]));
1208
+ },
1209
+ async stop(reason) {
1210
+ stopping = reason;
1211
+ if (!started)
1212
+ return;
1213
+ await up;
1214
+ if (!channel || channel.closed)
1215
+ return;
1216
+ const told = channel.call("loop", "stop", [reason]).catch(() => undefined);
1217
+ const grace = reason.kind === "command" ? STOP_GRACE_MS : STOP_GRACE_MS / 3;
1218
+ let timer;
1219
+ const late = await Promise.race([told.then(() => false), new Promise((resolve) => (timer = setTimeout(() => resolve(true), grace)))]);
1220
+ clearTimeout(timer);
1221
+ // A loop that did not stop in its grace: its process ends now (its group, or every process of its slot's uid), and
1222
+ // the run's start ends as its process's exit says.
1223
+ if (late)
1224
+ await kill();
1225
+ },
1226
+ keepsComputer(reason) {
1227
+ return reason.kind === "command" && reason.cancel !== true && keeps;
1228
+ },
1229
+ };
1230
+ }