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

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 (620) hide show
  1. package/CHANGELOG.md +700 -0
  2. package/README.md +441 -177
  3. package/dist/adapters.d.ts +4 -1
  4. package/dist/adapters.js +4 -2
  5. package/dist/agent-rows.d.ts +1 -3
  6. package/dist/agents-store.d.ts +35 -3
  7. package/dist/agents-store.js +48 -23
  8. package/dist/answer-json.d.ts +34 -1
  9. package/dist/answer-json.js +91 -9
  10. package/dist/api-only.d.ts +1 -1
  11. package/dist/api-only.js +2 -2
  12. package/dist/bash-read-only.js +2 -1
  13. package/dist/browser-cost.js +52 -93
  14. package/dist/cap-short.d.ts +12 -0
  15. package/dist/cap-short.js +60 -0
  16. package/dist/cap.d.ts +3 -400
  17. package/dist/cap.js +6 -942
  18. package/dist/catalog.d.ts +0 -5
  19. package/dist/catalog.js +2 -6
  20. package/dist/chatgpt-plan.d.ts +163 -0
  21. package/dist/chatgpt-plan.js +549 -0
  22. package/dist/cli.js +26 -6
  23. package/dist/composio-preset.d.ts +25 -0
  24. package/dist/composio-preset.js +51 -8
  25. package/dist/composio-triggers.d.ts +113 -0
  26. package/dist/composio-triggers.js +411 -0
  27. package/dist/computer-calls.d.ts +36 -24
  28. package/dist/computer-calls.js +110 -27
  29. package/dist/computer-commands.d.ts +2 -0
  30. package/dist/computer-commands.js +7 -3
  31. package/dist/computer-live.d.ts +12 -2
  32. package/dist/computer-live.js +21 -5
  33. package/dist/computer-routes.d.ts +2 -2
  34. package/dist/computer-routes.js +2 -2
  35. package/dist/computer-setting.d.ts +15 -2
  36. package/dist/computer-setting.js +20 -4
  37. package/dist/computer-view.d.ts +18 -2
  38. package/dist/computer-view.js +21 -6
  39. package/dist/computer-viewer.js +40 -13
  40. package/dist/computers.d.ts +8 -2
  41. package/dist/computers.js +18 -8
  42. package/dist/console/assets/index-BNhZs-jp.css +1 -0
  43. package/dist/console/assets/index-BQv5aOGB.js +700 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/console-links.d.ts +2 -0
  46. package/dist/console-links.js +6 -3
  47. package/dist/decision-cap.d.ts +2 -5
  48. package/dist/decision-cap.js +3 -6
  49. package/dist/decision-rows.js +11 -11
  50. package/dist/decisions.js +4 -0
  51. package/dist/email/account.d.ts +84 -0
  52. package/dist/email/account.js +159 -0
  53. package/dist/email/answer.d.ts +10 -0
  54. package/dist/email/answer.js +182 -0
  55. package/dist/email/email-faux.d.ts +95 -0
  56. package/dist/email/email-faux.js +849 -0
  57. package/dist/email/labels.d.ts +1 -0
  58. package/dist/email/labels.js +84 -0
  59. package/dist/email/mail.d.ts +186 -0
  60. package/dist/email/mail.js +380 -0
  61. package/dist/email/names.d.ts +20 -0
  62. package/dist/email/names.js +40 -0
  63. package/dist/email/routes.d.ts +9 -0
  64. package/dist/email/routes.js +50 -0
  65. package/dist/email/tools.d.ts +20 -0
  66. package/dist/email/tools.js +517 -0
  67. package/dist/environment.d.ts +17 -2
  68. package/dist/environment.js +36 -8
  69. package/dist/errors.d.ts +6 -0
  70. package/dist/errors.js +12 -0
  71. package/dist/eval-mailbox.d.ts +103 -0
  72. package/dist/eval-mailbox.js +236 -0
  73. package/dist/faux-computers.js +4 -2
  74. package/dist/graph-view.d.ts +9 -2
  75. package/dist/graph-view.js +6 -2
  76. package/dist/harness-install.d.ts +28 -2
  77. package/dist/harness-install.js +147 -59
  78. package/dist/harness-opencode/adapter.js +2 -22
  79. package/dist/harness-opencode/facts.js +5 -4
  80. package/dist/harness-opencode/host/policy.d.ts +4 -5
  81. package/dist/harness-opencode/host/policy.js +14 -33
  82. package/dist/harness-opencode/index.d.ts +1 -1
  83. package/dist/harness-opencode/index.js +1 -1
  84. package/dist/harness-opencode/versions.d.ts +6 -0
  85. package/dist/harness-opencode/versions.js +6 -0
  86. package/dist/harness-table.d.ts +0 -2
  87. package/dist/harness-table.js +8 -7
  88. package/dist/harness.d.ts +12 -0
  89. package/dist/harness.js +15 -3
  90. package/dist/host-tools.d.ts +1 -5
  91. package/dist/host-tools.js +7 -10
  92. package/dist/hosted-search.d.ts +3 -3
  93. package/dist/hosted-search.js +51 -32
  94. package/dist/import-sources.d.ts +1 -1
  95. package/dist/import-sources.js +3 -3
  96. package/dist/import.d.ts +21 -0
  97. package/dist/import.js +186 -1
  98. package/dist/key-check.d.ts +0 -2
  99. package/dist/key-check.js +3 -4
  100. package/dist/key-refusal.d.ts +8 -2
  101. package/dist/key-refusal.js +16 -13
  102. package/dist/key-words.d.ts +3 -2
  103. package/dist/key-words.js +4 -2
  104. package/dist/learn/check.d.ts +24 -4
  105. package/dist/learn/check.js +340 -7
  106. package/dist/learn/commit.d.ts +10 -0
  107. package/dist/learn/commit.js +18 -4
  108. package/dist/learn/compile.d.ts +250 -0
  109. package/dist/learn/compile.js +507 -0
  110. package/dist/learn/general.d.ts +3 -0
  111. package/dist/learn/general.js +4 -2
  112. package/dist/learn/grade.d.ts +5 -1
  113. package/dist/learn/grade.js +11 -7
  114. package/dist/learn/notes.d.ts +8 -0
  115. package/dist/learn/notes.js +18 -0
  116. package/dist/learn/promote.d.ts +308 -0
  117. package/dist/learn/promote.js +321 -0
  118. package/dist/learn/refit.d.ts +48 -0
  119. package/dist/learn/refit.js +264 -0
  120. package/dist/learn/reflect.d.ts +5 -25
  121. package/dist/learn/reflect.js +14 -131
  122. package/dist/learn/replay-calls.d.ts +63 -0
  123. package/dist/learn/replay-calls.js +158 -0
  124. package/dist/learn/skills.d.ts +19 -16
  125. package/dist/learn/skills.js +157 -53
  126. package/dist/learn/workflow-nodes.d.ts +15 -0
  127. package/dist/learn/workflow-nodes.js +44 -0
  128. package/dist/learned-nodes.d.ts +58 -2
  129. package/dist/learned-nodes.js +68 -5
  130. package/dist/learned-workflow.d.ts +58 -32
  131. package/dist/learned-workflow.js +215 -77
  132. package/dist/learning-batch.d.ts +2 -2
  133. package/dist/learning-batch.js +4 -4
  134. package/dist/learning-cost.d.ts +41 -11
  135. package/dist/learning-cost.js +31 -13
  136. package/dist/learning-routes.d.ts +12 -2
  137. package/dist/learning-routes.js +34 -6
  138. package/dist/learning-words.d.ts +8 -1
  139. package/dist/learning-words.js +11 -1
  140. package/dist/learning.d.ts +26 -1
  141. package/dist/learning.js +7 -4
  142. package/dist/link-check.d.ts +27 -0
  143. package/dist/link-check.js +164 -0
  144. package/dist/llm.js +0 -3
  145. package/dist/local-models.d.ts +33 -2
  146. package/dist/local-models.js +43 -5
  147. package/dist/mcp-gateway.d.ts +12 -20
  148. package/dist/mcp-gateway.js +16 -44
  149. package/dist/mcp-oauth.d.ts +5 -0
  150. package/dist/mcp-oauth.js +1 -1
  151. package/dist/mcp-pin-first.d.ts +37 -0
  152. package/dist/mcp-pin-first.js +113 -0
  153. package/dist/mcp-probe.d.ts +8 -9
  154. package/dist/mcp-probe.js +16 -33
  155. package/dist/mcp-secret-writes.js +3 -0
  156. package/dist/mcp-servers-store.d.ts +102 -26
  157. package/dist/mcp-servers-store.js +151 -25
  158. package/dist/mcp-sources.d.ts +39 -0
  159. package/dist/mcp-sources.js +74 -0
  160. package/dist/mcp-store.d.ts +11 -0
  161. package/dist/mcp-store.js +16 -2
  162. package/dist/mcp-wire.d.ts +22 -0
  163. package/dist/mcp-wire.js +36 -0
  164. package/dist/mcp.js +3 -3
  165. package/dist/meta-tool-names.d.ts +1 -0
  166. package/dist/meta-tool-names.js +3 -0
  167. package/dist/model-form.d.ts +11 -0
  168. package/dist/model-form.js +17 -1
  169. package/dist/model.d.ts +39 -6
  170. package/dist/model.js +171 -32
  171. package/dist/monid.d.ts +50 -29
  172. package/dist/monid.js +234 -143
  173. package/dist/native/binding.d.ts +13 -0
  174. package/dist/native/binding.js +57 -0
  175. package/dist/native/cli.d.ts +2 -0
  176. package/dist/native/cli.js +48 -0
  177. package/dist/native/connection.d.ts +8 -0
  178. package/dist/native/connection.js +94 -0
  179. package/dist/native/context.d.ts +6 -0
  180. package/dist/native/context.js +22 -0
  181. package/dist/native/discovery.d.ts +27 -0
  182. package/dist/native/discovery.js +404 -0
  183. package/dist/native/environment.d.ts +4 -0
  184. package/dist/native/environment.js +18 -0
  185. package/dist/native/history.d.ts +20 -0
  186. package/dist/native/history.js +147 -0
  187. package/dist/native/instructions.d.ts +21 -0
  188. package/dist/native/instructions.js +173 -0
  189. package/dist/native/remote-worker-bridge.d.ts +3 -0
  190. package/dist/native/remote-worker-bridge.js +278 -0
  191. package/dist/native/remote.d.ts +187 -0
  192. package/dist/native/remote.js +492 -0
  193. package/dist/native/runtime.d.ts +17 -0
  194. package/dist/native/runtime.js +316 -0
  195. package/dist/native/runtimes.d.ts +66 -0
  196. package/dist/native/runtimes.js +41 -0
  197. package/dist/native/schema.d.ts +46 -0
  198. package/dist/native/schema.js +41 -0
  199. package/dist/native/types.d.ts +87 -0
  200. package/dist/native/types.js +1 -0
  201. package/dist/observation/http.d.ts +4 -0
  202. package/dist/observation/http.js +140 -0
  203. package/dist/observation/observer.d.ts +301 -0
  204. package/dist/observation/observer.js +919 -0
  205. package/dist/observation/schema.d.ts +52 -0
  206. package/dist/observation/schema.js +154 -0
  207. package/dist/openapi.d.ts +1 -0
  208. package/dist/openapi.js +705 -126
  209. package/dist/paid-calls.d.ts +34 -32
  210. package/dist/paid-calls.js +52 -104
  211. package/dist/place-offers.d.ts +4 -8
  212. package/dist/place-offers.js +4 -9
  213. package/dist/port-models.d.ts +7 -2
  214. package/dist/port-models.js +5 -2
  215. package/dist/print.d.ts +4 -2
  216. package/dist/print.js +4 -3
  217. package/dist/propose.d.ts +8 -3
  218. package/dist/propose.js +28 -7
  219. package/dist/provider.d.ts +5 -1
  220. package/dist/provider.js +17 -2
  221. package/dist/push-handler.d.ts +3 -2
  222. package/dist/push-handler.js +20 -6
  223. package/dist/reflect-range.js +2 -1
  224. package/dist/refusal-words.d.ts +11 -0
  225. package/dist/refusal-words.js +13 -2
  226. package/dist/rows.d.ts +5 -3
  227. package/dist/rows.js +15 -4
  228. package/dist/run-launch.d.ts +23 -1
  229. package/dist/run-launch.js +17 -4
  230. package/dist/run-learning-served.d.ts +84 -0
  231. package/dist/run-manifest.d.ts +8 -0
  232. package/dist/run-manifest.js +33 -1
  233. package/dist/run-reads-over-store.d.ts +3 -3
  234. package/dist/run-reads-over-store.js +13 -10
  235. package/dist/run-secrets.js +2 -3
  236. package/dist/run-timeline-served.d.ts +3 -2
  237. package/dist/run-timeline-served.js +12 -10
  238. package/dist/run-view.d.ts +59 -41
  239. package/dist/run-view.js +128 -64
  240. package/dist/runnable.d.ts +13 -8
  241. package/dist/runnable.js +77 -60
  242. package/dist/runner/adapter-loop.d.ts +60 -15
  243. package/dist/runner/adapter-loop.js +1406 -464
  244. package/dist/runner/adapter-run-spec.d.ts +45 -14
  245. package/dist/runner/adapter-run-spec.js +200 -116
  246. package/dist/runner/adapters/pi.d.ts +40 -7
  247. package/dist/runner/adapters/pi.js +149 -38
  248. package/dist/runner/beside.d.ts +3 -1
  249. package/dist/runner/beside.js +24 -8
  250. package/dist/runner/claim-secrets.d.ts +3 -1
  251. package/dist/runner/claim-secrets.js +28 -4
  252. package/dist/runner/cli-run-spec.d.ts +30 -0
  253. package/dist/runner/cli-run-spec.js +150 -66
  254. package/dist/runner/computer-channel.d.ts +5 -2
  255. package/dist/runner/computer-channel.js +5 -3
  256. package/dist/runner/computer-journal.d.ts +6 -0
  257. package/dist/runner/computer-journal.js +8 -10
  258. package/dist/runner/conformance/harness.d.ts +3 -0
  259. package/dist/runner/conformance/harness.js +149 -5
  260. package/dist/runner/conformance/subject.d.ts +11 -4
  261. package/dist/runner/end-of-run.d.ts +8 -5
  262. package/dist/runner/end-of-run.js +11 -6
  263. package/dist/runner/feedback-round.d.ts +79 -0
  264. package/dist/runner/feedback-round.js +127 -0
  265. package/dist/runner/harness-loops.js +17 -0
  266. package/dist/runner/journal-kinds.d.ts +55 -13
  267. package/dist/runner/journal-kinds.js +19 -0
  268. package/dist/runner/learning-dispatch.d.ts +3 -2
  269. package/dist/runner/learning-dispatch.js +6 -6
  270. package/dist/runner/learning-end.d.ts +58 -19
  271. package/dist/runner/learning-end.js +316 -115
  272. package/dist/runner/learning-factory.d.ts +3 -0
  273. package/dist/runner/learning-factory.js +8 -2
  274. package/dist/runner/learning-loop.d.ts +21 -1
  275. package/dist/runner/learning-loop.js +24 -6
  276. package/dist/runner/learning-seed.d.ts +4 -0
  277. package/dist/runner/learning-seed.js +14 -0
  278. package/dist/runner/loop-contract.d.ts +19 -3
  279. package/dist/runner/loop.d.ts +34 -1
  280. package/dist/runner/loop.js +55 -1
  281. package/dist/runner/main.d.ts +6 -1
  282. package/dist/runner/main.js +26 -4
  283. package/dist/runner/mcp-claim.d.ts +5 -1
  284. package/dist/runner/mcp-claim.js +66 -50
  285. package/dist/runner/mcp-run.d.ts +20 -53
  286. package/dist/runner/mcp-run.js +22 -88
  287. package/dist/runner/meta-tools.d.ts +44 -0
  288. package/dist/runner/meta-tools.js +344 -0
  289. package/dist/runner/metrics.d.ts +80 -21
  290. package/dist/runner/metrics.js +128 -42
  291. package/dist/runner/model-route.d.ts +12 -3
  292. package/dist/runner/model-route.js +149 -19
  293. package/dist/runner/monid-run.d.ts +18 -0
  294. package/dist/runner/monid-run.js +170 -0
  295. package/dist/runner/native-loop.d.ts +11 -0
  296. package/dist/runner/native-loop.js +438 -0
  297. package/dist/runner/promotion.d.ts +146 -0
  298. package/dist/runner/promotion.js +803 -0
  299. package/dist/runner/redact.js +3 -0
  300. package/dist/runner/reflect-hook.d.ts +36 -21
  301. package/dist/runner/reflect-hook.js +147 -49
  302. package/dist/runner/runner.d.ts +7 -1
  303. package/dist/runner/runner.js +34 -8
  304. package/dist/runner/sdk-loop.d.ts +7 -0
  305. package/dist/runner/sdk-loop.js +470 -0
  306. package/dist/runner/sessions.d.ts +8 -3
  307. package/dist/runner/sessions.js +5 -1
  308. package/dist/runner/spec-holds.d.ts +16 -2
  309. package/dist/runner/spec-holds.js +42 -14
  310. package/dist/runner/step-guard.d.ts +62 -0
  311. package/dist/runner/step-guard.js +93 -0
  312. package/dist/runner/store-secrets.js +17 -2
  313. package/dist/runner/subagent.d.ts +0 -3
  314. package/dist/runner/subagent.js +7 -12
  315. package/dist/runner/workflow-first.d.ts +226 -0
  316. package/dist/runner/workflow-first.js +293 -0
  317. package/dist/runner/workflow-loop.d.ts +1 -1
  318. package/dist/runner/workflow-loop.js +32 -19
  319. package/dist/runner/workflow-spec.d.ts +5 -1
  320. package/dist/runner/workflow-spec.js +63 -48
  321. package/dist/runs-over-store.d.ts +41 -4
  322. package/dist/runs-over-store.js +64 -22
  323. package/dist/sdk/runs.d.ts +115 -0
  324. package/dist/sdk/runs.js +422 -0
  325. package/dist/sdk/schema.d.ts +175 -0
  326. package/dist/sdk/schema.js +138 -0
  327. package/dist/sdk/workflows.d.ts +22 -0
  328. package/dist/sdk/workflows.js +39 -0
  329. package/dist/secrets.d.ts +2 -0
  330. package/dist/secrets.js +19 -1
  331. package/dist/server.d.ts +108 -20
  332. package/dist/server.js +874 -157
  333. package/dist/settings-wake.d.ts +8 -6
  334. package/dist/settings-wake.js +13 -7
  335. package/dist/skill-route.d.ts +3 -0
  336. package/dist/skill-route.js +16 -0
  337. package/dist/skills/agentrun-serve/SKILL.md +368 -0
  338. package/dist/stats.d.ts +10 -10
  339. package/dist/store/agent-body.d.ts +22 -7
  340. package/dist/store/agent-body.js +23 -14
  341. package/dist/store/command-wake.d.ts +3 -2
  342. package/dist/store/command-wake.js +4 -4
  343. package/dist/store/index.d.ts +1 -1
  344. package/dist/store/native-command-owner.d.ts +10 -0
  345. package/dist/store/native-command-owner.js +47 -0
  346. package/dist/store/postgres/connection.js +3 -1
  347. package/dist/store/postgres/migrations/0010_imported_templates.sql +18 -0
  348. package/dist/store/postgres/migrations/0011_revision_mcp_pin.sql +13 -0
  349. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  350. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  351. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  352. package/dist/store/postgres/store.js +3 -0
  353. package/dist/store/schema.d.ts +16 -0
  354. package/dist/store/schema.js +47 -8
  355. package/dist/store/sqlite/connection.d.ts +2 -2
  356. package/dist/store/sqlite/connection.js +2 -2
  357. package/dist/store/sqlite/run-patch.d.ts +8 -1
  358. package/dist/store/sqlite/run-patch.js +33 -10
  359. package/dist/store/sqlite/store.js +184 -28
  360. package/dist/store/store.d.ts +98 -21
  361. package/dist/store-reads/analytics.d.ts +7 -7
  362. package/dist/store-reads/analytics.js +23 -5
  363. package/dist/store-reads/cap.js +8 -6
  364. package/dist/store-reads/journal.d.ts +30 -1
  365. package/dist/store-reads/journal.js +141 -83
  366. package/dist/store-reads/learning.d.ts +179 -13
  367. package/dist/store-reads/learning.js +230 -68
  368. package/dist/store-reads/loop.d.ts +61 -0
  369. package/dist/store-reads/loop.js +111 -0
  370. package/dist/store-reads/runs.d.ts +5 -0
  371. package/dist/store-reads/runs.js +3 -2
  372. package/dist/store-view.d.ts +3 -2
  373. package/dist/store-view.js +109 -37
  374. package/dist/template-eval.d.ts +87 -16
  375. package/dist/template-eval.js +605 -120
  376. package/dist/template-github-permissions.d.ts +2 -2
  377. package/dist/template-github-permissions.js +2 -1
  378. package/dist/template-import.d.ts +31 -0
  379. package/dist/template-import.js +121 -0
  380. package/dist/template-source.d.ts +51 -0
  381. package/dist/template-source.js +371 -0
  382. package/dist/templates.d.ts +274 -52
  383. package/dist/templates.js +670 -201
  384. package/dist/text-urls.d.ts +38 -0
  385. package/dist/text-urls.js +170 -0
  386. package/dist/timeline/computer.d.ts +48 -0
  387. package/dist/timeline/computer.js +169 -0
  388. package/dist/timeline/index.d.ts +7 -5
  389. package/dist/timeline/index.js +7 -5
  390. package/dist/timeline/labels.d.ts +11 -4
  391. package/dist/timeline/labels.js +122 -8
  392. package/dist/timeline/origin.d.ts +20 -6
  393. package/dist/timeline/origin.js +13 -6
  394. package/dist/timeline/render-text.js +1 -1
  395. package/dist/timeline/timeline.d.ts +76 -20
  396. package/dist/timeline/timeline.js +184 -39
  397. package/dist/timeline/util.d.ts +5 -0
  398. package/dist/timeline/util.js +44 -8
  399. package/dist/timeline/web-calls.d.ts +17 -0
  400. package/dist/timeline/web-calls.js +106 -0
  401. package/dist/tool-gate.d.ts +103 -76
  402. package/dist/tool-gate.js +200 -127
  403. package/dist/tool-keys.d.ts +4 -1
  404. package/dist/tool-keys.js +8 -3
  405. package/dist/tool-list.d.ts +29 -0
  406. package/dist/tool-list.js +50 -0
  407. package/dist/tool-names.d.ts +76 -0
  408. package/dist/tool-names.js +101 -0
  409. package/dist/tool-plane.d.ts +34 -28
  410. package/dist/tool-plane.js +72 -37
  411. package/dist/tools.d.ts +59 -15
  412. package/dist/tools.js +46 -42
  413. package/dist/trigger-adapter.d.ts +85 -5
  414. package/dist/trigger-adapter.js +6 -0
  415. package/dist/trigger-adapters.js +3 -1
  416. package/dist/trigger-composio.d.ts +10 -0
  417. package/dist/trigger-composio.js +122 -0
  418. package/dist/trigger-email.d.ts +4 -0
  419. package/dist/trigger-email.js +228 -0
  420. package/dist/trigger-signatures.d.ts +6 -10
  421. package/dist/trigger-signatures.js +16 -16
  422. package/dist/trigger-targets.d.ts +1 -1
  423. package/dist/trigger-targets.js +4 -3
  424. package/dist/trigger-webhook.js +6 -4
  425. package/dist/triggers.d.ts +94 -9
  426. package/dist/triggers.js +263 -62
  427. package/dist/uploads.d.ts +9 -0
  428. package/dist/uploads.js +27 -0
  429. package/dist/validate.d.ts +15 -7
  430. package/dist/validate.js +91 -50
  431. package/dist/web-fake.d.ts +56 -0
  432. package/dist/web-fake.js +102 -0
  433. package/dist/web-fetch-direct.d.ts +3 -0
  434. package/dist/web-fetch-direct.js +4 -1
  435. package/dist/web-fetch.d.ts +6 -8
  436. package/dist/web-fetch.js +10 -53
  437. package/dist/web-search.d.ts +51 -2
  438. package/dist/web-search.js +116 -18
  439. package/dist/webhooks.d.ts +2 -1
  440. package/dist/webhooks.js +5 -1
  441. package/dist/workflow/node-runner.js +10 -2
  442. package/dist/workspace/archil-claim.d.ts +3 -0
  443. package/dist/workspace/archil-claim.js +9 -2
  444. package/dist/workspace/computer-deps.d.ts +25 -9
  445. package/dist/workspace/computer-deps.js +82 -38
  446. package/dist/workspace/computer-for-claim.d.ts +60 -4
  447. package/dist/workspace/computer-for-claim.js +203 -45
  448. package/dist/workspace/computer-hold.js +7 -1
  449. package/dist/workspace/computer-janitor.d.ts +10 -3
  450. package/dist/workspace/computer-janitor.js +96 -29
  451. package/dist/workspace/computer-kept.d.ts +82 -0
  452. package/dist/workspace/computer-kept.js +147 -0
  453. package/dist/workspace/computer-mcp.js +4 -3
  454. package/dist/workspace/computer-ports.d.ts +23 -3
  455. package/dist/workspace/computer-ports.js +115 -5
  456. package/dist/workspace/index.d.ts +2 -3
  457. package/dist/workspace/index.js +1 -2
  458. package/dist/workspace/kind-skills/desktop/SKILL.md +31 -11
  459. package/dist/workspace/kind-skills/phone/SKILL.md +29 -14
  460. package/dist/workspace/local.js +2 -2
  461. package/dist/workspace/resolve-computer.d.ts +33 -1
  462. package/dist/workspace/resolve-computer.js +37 -16
  463. package/dist/workspace/revision-skills.d.ts +6 -2
  464. package/dist/workspace/revision-skills.js +12 -5
  465. package/dist/workspace/run-end-computers.d.ts +30 -0
  466. package/dist/workspace/run-end-computers.js +137 -0
  467. package/dist/workspace/run-tools.d.ts +40 -23
  468. package/dist/workspace/run-tools.js +46 -19
  469. package/dist/wrap-up.d.ts +35 -0
  470. package/dist/wrap-up.js +48 -0
  471. package/launcher/agentrun-serve +4 -2
  472. package/package.json +13 -9
  473. package/skills/agentrun-serve/SKILL.md +248 -10
  474. package/templates/README.md +220 -60
  475. package/templates/TOOLS.md +168 -0
  476. package/templates/code-review/agent.md +46 -16
  477. package/templates/code-review/evals/clean-refactor/case.yaml +2 -1
  478. package/templates/code-review/evals/clean-refactor/graders/head-sha.md +6 -0
  479. package/templates/code-review/evals/injection/case.yaml +2 -1
  480. package/templates/code-review/evals/injection/graders/head-sha.md +6 -0
  481. package/templates/code-review/evals/mentions-defused/case.yaml +3 -3
  482. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -23
  483. package/templates/code-review/evals/mentions-defused/graders/head-sha.md +6 -0
  484. package/templates/code-review/evals/never-flag/case.yaml +2 -1
  485. package/templates/code-review/evals/never-flag/graders/head-sha.md +6 -0
  486. package/templates/code-review/evals/null-name/case.yaml +2 -1
  487. package/templates/code-review/evals/null-name/graders/head-sha.md +6 -0
  488. package/templates/code-review/evals/off-by-one/case.yaml +2 -1
  489. package/templates/code-review/evals/off-by-one/graders/head-sha.md +6 -0
  490. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  491. package/templates/code-review/evals/other-repo/case.yaml +16 -0
  492. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +130 -0
  493. package/templates/code-review/evals/other-repo/graders/head-sha.md +6 -0
  494. package/templates/code-review/evals/other-repo/graders/no-canary.md +6 -0
  495. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +8 -0
  496. package/templates/code-review/evals/other-repo/graders/refused-not-quoted.md +18 -0
  497. package/templates/code-review/evals/other-repo/prompt.md +10 -0
  498. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  499. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  500. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  501. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  502. package/templates/code-review/evals/re-review/case.yaml +2 -1
  503. package/templates/code-review/evals/re-review/graders/head-sha.md +6 -0
  504. package/templates/code-review/evals/re-review-open/case.yaml +2 -1
  505. package/templates/code-review/evals/re-review-open/graders/head-sha.md +6 -0
  506. package/templates/code-review/evals/repo-rule/case.yaml +2 -1
  507. package/templates/code-review/evals/repo-rule/graders/head-sha.md +6 -0
  508. package/templates/code-review/evals/two-defects/case.yaml +2 -1
  509. package/templates/code-review/evals/two-defects/graders/head-sha.md +6 -0
  510. package/templates/code-review/rules/CODEREVIEW.md +1 -1
  511. package/templates/code-review/skills/review/DEEP.md +5 -4
  512. package/templates/code-review/skills/review/REVIEWER.md +5 -4
  513. package/templates/code-review/skills/review/SKILL.md +11 -6
  514. package/templates/code-review/{findings.schema.json → skills/review/findings.schema.json} +1 -0
  515. package/templates/inbound-lead/agent.md +26 -16
  516. package/templates/inbound-lead/evals/injection-in-form/graders/no-exfil.md +16 -0
  517. package/templates/inbound-lead/evals/injection-in-form/prompt.md +2 -2
  518. package/templates/inbound-lead/evals/write-back/case.yaml +2 -6
  519. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +34 -225
  520. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +10 -14
  521. package/templates/inbound-lead/evals/write-back/graders/writes-once.md +7 -0
  522. package/templates/inbound-lead/evals/write-back/prompt.md +1 -1
  523. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +3 -7
  524. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +34 -225
  525. package/templates/inbound-lead/evals/write-back-wrong-record/graders/form-id.md +17 -0
  526. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +3 -3
  527. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +2 -2
  528. package/templates/inbound-lead/skills/lead/SKILL.md +23 -27
  529. package/templates/kyb/agent.md +15 -5
  530. package/templates/kyb/evals/adverse-media/prompt.md +2 -7
  531. package/templates/kyb/evals/canada-active-filed/prompt.md +2 -6
  532. package/templates/kyb/evals/clean-public-company/prompt.md +2 -6
  533. package/templates/kyb/evals/injection-in-page/prompt.md +3 -7
  534. package/templates/kyb/evals/name-collision/prompt.md +2 -6
  535. package/templates/kyb/evals/no-invention/prompt.md +2 -6
  536. package/templates/kyb/evals/opensanctions-on/prompt.md +2 -6
  537. package/templates/kyb/evals/sanctioned-entity/prompt.md +2 -6
  538. package/templates/kyb/kyb.schema.json +8 -7
  539. package/templates/kyb/skills/kyb/SKILL.md +9 -6
  540. package/templates/market-monitor/agent.md +19 -12
  541. package/templates/market-monitor/evals/post-happens/case.yaml +4 -4
  542. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +13 -9
  543. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +1 -1
  544. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +3 -3
  545. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  546. package/templates/release-notes/agent.md +32 -10
  547. package/templates/release-notes/evals/draft-not-publish/case.yaml +5 -4
  548. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +29 -51
  549. package/templates/release-notes/evals/every-pr-accounted/case.yaml +2 -1
  550. package/templates/release-notes/evals/issue-write-refused/case.yaml +5 -4
  551. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +29 -51
  552. package/templates/release-notes/evals/late-arrival/case.yaml +6 -5
  553. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +29 -51
  554. package/templates/release-notes/evals/learned-style/case.yaml +2 -1
  555. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +2 -1
  556. package/templates/release-notes/evals/other-repo/case.yaml +24 -0
  557. package/templates/release-notes/evals/other-repo/fixtures/github-mcp.json +907 -0
  558. package/templates/release-notes/evals/other-repo/graders/no-canary.md +7 -0
  559. package/templates/release-notes/evals/other-repo/graders/no-other-repo.md +8 -0
  560. package/templates/release-notes/evals/other-repo/graders/refused-not-quoted.md +18 -0
  561. package/templates/release-notes/evals/other-repo/prompt.md +32 -0
  562. package/templates/release-notes/evals/upgrade-line/case.yaml +2 -1
  563. package/templates/release-notes/evals/user-facing-only/case.yaml +2 -1
  564. package/templates/release-notes/notes.schema.json +1 -1
  565. package/templates/release-notes/skills/release-notes/SKILL.md +26 -17
  566. package/dist/console/assets/index-Cn6JX1uH.js +0 -563
  567. package/dist/console/assets/index-DRN62V5v.css +0 -1
  568. package/dist/host-calls.d.ts +0 -20
  569. package/dist/host-calls.js +0 -12
  570. package/dist/runner/adapters/pi-computer.d.ts +0 -7
  571. package/dist/runner/adapters/pi-computer.js +0 -43
  572. package/dist/tool-blurbs.d.ts +0 -4
  573. package/dist/tool-blurbs.js +0 -28
  574. package/dist/tool-budget.d.ts +0 -38
  575. package/dist/tool-budget.js +0 -62
  576. package/dist/workspace/computer-script.d.ts +0 -37
  577. package/dist/workspace/computer-script.js +0 -138
  578. package/templates/code-review/evals/clean-refactor/graders/schema.md +0 -5
  579. package/templates/code-review/evals/injection/graders/schema.md +0 -5
  580. package/templates/code-review/evals/mentions-defused/graders/schema.md +0 -5
  581. package/templates/code-review/evals/never-flag/graders/schema.md +0 -5
  582. package/templates/code-review/evals/null-name/graders/schema.md +0 -5
  583. package/templates/code-review/evals/off-by-one/graders/schema.md +0 -5
  584. package/templates/code-review/evals/re-review/graders/schema.md +0 -5
  585. package/templates/code-review/evals/re-review-open/graders/schema.md +0 -5
  586. package/templates/code-review/evals/repo-rule/graders/schema.md +0 -5
  587. package/templates/code-review/evals/two-defects/graders/schema.md +0 -5
  588. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +0 -5
  589. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +0 -5
  590. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +0 -5
  591. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +0 -5
  592. package/templates/inbound-lead/evals/thin-data/graders/schema.md +0 -5
  593. package/templates/inbound-lead/evals/write-back/graders/schema.md +0 -5
  594. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +0 -7
  595. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +0 -18
  596. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +0 -5
  597. package/templates/kyb/evals/adverse-media/graders/schema.md +0 -5
  598. package/templates/kyb/evals/canada-active-filed/graders/schema.md +0 -5
  599. package/templates/kyb/evals/clean-public-company/graders/schema.md +0 -5
  600. package/templates/kyb/evals/injection-in-page/graders/schema.md +0 -5
  601. package/templates/kyb/evals/name-collision/graders/schema.md +0 -5
  602. package/templates/kyb/evals/no-invention/graders/schema.md +0 -5
  603. package/templates/kyb/evals/opensanctions-on/graders/schema.md +0 -5
  604. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +0 -5
  605. package/templates/market-monitor/evals/blocked-source/graders/schema.md +0 -5
  606. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +0 -5
  607. package/templates/market-monitor/evals/learned-preference/graders/schema.md +0 -5
  608. package/templates/market-monitor/evals/no-repeats/graders/schema.md +0 -5
  609. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +0 -5
  610. package/templates/market-monitor/evals/post-happens/graders/schema.md +0 -5
  611. package/templates/market-monitor/evals/pricing-change/graders/schema.md +0 -5
  612. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +0 -5
  613. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +0 -5
  614. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +0 -5
  615. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +0 -5
  616. package/templates/release-notes/evals/late-arrival/graders/schema.md +0 -5
  617. package/templates/release-notes/evals/learned-style/graders/schema.md +0 -5
  618. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +0 -5
  619. package/templates/release-notes/evals/upgrade-line/graders/schema.md +0 -5
  620. package/templates/release-notes/evals/user-facing-only/graders/schema.md +0 -5
package/dist/server.js CHANGED
@@ -1,3 +1,15 @@
1
+ import { maintainObservations, Observations } from './observation/observer.js';
2
+ import { isObservationRoute, observationHttp } from './observation/http.js';
3
+ import { SdkRuns, sdkOf } from "./sdk/runs.js";
4
+ import { gradeRouteFor } from "./runner/harness-loops.js";
5
+ import { routeOf as sdkModelRoute } from "./runner/model-route.js";
6
+ import { answerSkill } from './skill-route.js';
7
+ import { RemoteConnectors, verifyRemote, REMOTE_COMPLETION_BODY_BYTES } from './native/remote.js';
8
+ import { REMOTE_HISTORY_BODY_BYTES } from './native/history.js';
9
+ import { nativeOf, nativeModelOverrides, nativeExecutionOverrides, NATIVE_MODEL_SETTINGS_UNSUPPORTED, NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, NATIVE_TOOL_BUDGET_UNSUPPORTED } from "./native/binding.js";
10
+ import { discoverNative } from "./native/discovery.js";
11
+ import { isNativeRuntime } from "./native/runtimes.js";
12
+ import { connectNative, launchNative, updateNative, verifyConnection } from "./native/connection.js";
1
13
  // The /v2 API over the agent store in a data directory: the contract agentrun.v2/0, served on loopback with a bearer
2
14
  // token.
3
15
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
@@ -12,14 +24,15 @@ import { once } from "node:events";
12
24
  import { existsSync } from "node:fs";
13
25
  import { rm } from "node:fs/promises";
14
26
  import { homedir } from "node:os";
15
- import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
27
+ import { pinFirst as pinFirstOf } from "./mcp-pin-first.js";
28
+ import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, etagOf, externalKey, getAgent, listAgents, makeRevision, refuseExternal, revisionView, setAgentArchived, setCurrentRevision } from "./agents-store.js";
16
29
  import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
17
30
  import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
18
31
  import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
19
- import { FAUX_MONID_ENV } from "./monid.js";
32
+ import { FAUX_MONID_ENV, MONID_KEY_ENV, pinMonid, PRICED_BY_USAGE } from "./monid.js";
20
33
  import { FAUX_EXA_ENV } from "./exa-keyless.js";
21
34
  import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView } from "./tools.js";
22
- import { ApiError, invalid, unsupported } from "./errors.js";
35
+ import { ApiError, invalid, sentence, unsupported } from "./errors.js";
23
36
  import { deref, explain } from "./explain.js";
24
37
  import { HOME_HOST_OWNED } from "./files.js";
25
38
  import { DATA_ENV, readJson, syncDir, TOKEN_FILE, writeDurable } from "./server-fs.js";
@@ -31,7 +44,8 @@ import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./h
31
44
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
32
45
  import { IMPORT_ASKED } from "./import.js";
33
46
  import { answerStoreCall } from "./import-proxy.js";
34
- import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
47
+ import { gradeModelOf, LEARNING_LABEL, learningBudgetOf, learningFolderOf, learningOf, learnsOf, RUN_LEARNING_USE, seedOf } from "./learning.js";
48
+ import { askReplay, ReplayRefused, replayView } from "./runner/promotion.js";
35
49
  import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowRevisions, writeNote } from "./learning-routes.js";
36
50
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
37
51
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
@@ -43,11 +57,12 @@ import { answerPage, byOwnerSession, ConsoleSessions, heldSessions, isJson, over
43
57
  import { hostFix, hostName, loopbackNames } from "./host-check.js";
44
58
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
45
59
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
46
- import { computerView, sessionIn } from "./computer-view.js";
60
+ import { computerView, lapsedOf, sessionIn } from "./computer-view.js";
61
+ import { readKept } from "./workspace/computer-kept.js";
47
62
  import { liveReachOf } from "./live-reach.js";
48
63
  import { screenWaitEnded } from "./browser-wait-ended.js";
49
64
  import { durationMs, logLine } from "./print.js";
50
- import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
65
+ import { approve, archiveRun, cancel, message, pause as pauseRunOverStore, prepareLaunch, raiseCap, resume as resumeRunOverStore, startInline, startRun, stop as stopRunOverStore } from "./runs-over-store.js";
51
66
  import { factsOverStore, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
52
67
  import { HELD_WAITS } from "./runner/journal-kinds.js";
53
68
  import { servedTimelineRows } from "./run-timeline-served.js";
@@ -66,8 +81,11 @@ import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
66
81
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
67
82
  import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
68
83
  import { answerOf, logged } from "./agents.js";
84
+ import { keepGrade } from "./runner/feedback-round.js";
69
85
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
86
+ import { GRADE_SOURCES, GRADES_KEPT, gradeView, LABEL_MAX, promotionsOf, promotionsShown } from "./learn/promote.js";
70
87
  import { runModelRef } from "./model.js";
88
+ import { REDACTED } from "./secret-cut.js";
71
89
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
72
90
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
73
91
  import { runLines } from "./usage-lines.js";
@@ -76,27 +94,32 @@ import { dockerComputerRefusal, dockerPathsOf, FAUX_MOUNTINFO_ENV, remoteDockerO
76
94
  import { dockerDaemonCheck } from "./docker-daemon.js";
77
95
  import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
78
96
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
79
- import { CAP_MODES } from "./cap.js";
80
- import { blockersOf, CODE_NODES_ENV, issueOf, MCP_HARNESSES, NOT_SET_UP } from "./runnable.js";
97
+ import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
81
98
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
82
99
  import { isSecretWriteOperation, SECRET_WRITE_REFUSAL, secretsWritableFields, secretWriterFacts, writesSecretFor, writesSecretsAllowed } from "./secret-writes.js";
100
+ import { ChatGPTPlan, planOf, PlanSignInRefused, SIGN_OUT_UNCONFIRMED, withPlan } from "./chatgpt-plan.js";
83
101
  import { bootSealKey, withSealKey } from "./seal-key.js";
84
102
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
85
103
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
86
104
  import { analyticsFilter, analyticsView, statsView } from "./stats.js";
87
- import { agentCostOverStore, agentLearningOverStore, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd } from "./store-reads/learning.js";
105
+ import { agentLoopOverStore } from "./store-reads/loop.js";
106
+ import { printable } from "./learn/index.js";
107
+ import { agentCostOverStore, agentLearningOverStore, allInOf, costRunOf, learningCountsOverStore, learningSpendOverStore, runLearningEnd } from "./store-reads/learning.js";
88
108
  import { figuresOf, LearningBatches } from "./learning-batch.js";
89
- import { costCsv, learningCostQuery } from "./learning-cost.js";
109
+ import { costCsv, learningCostQuery, RUN_PATHS } from "./learning-cost.js";
90
110
  import { evalOf, evalsOf, recordEval } from "./learning-evals.js";
91
111
  import { keyOf, SEAL_KEY_ENV, TOOL_FIELDS } from "./tool-keys.js";
92
112
  import { toolKeysOverStore } from "./tool-keys-store.js";
93
113
  import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
94
114
  import { signInsOverStore } from "./sign-ins-store.js";
95
- import { MCP_AUTH_TYPES, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
96
- import { composioSave, composioTools } from "./composio-preset.js";
115
+ import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
116
+ import { composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
117
+ import { ComposioTriggers } from "./composio-triggers.js";
97
118
  import { mcpServersOverStore } from "./mcp-servers-store.js";
119
+ import { getMcpServer, listMcpServers } from "./mcp-store.js";
98
120
  import { privateHostsRoute } from "./mcp-private-hosts.js";
99
121
  import { metaToolOf } from "./mcp-meta.js";
122
+ import { mcpPinOf } from "./mcp-gateway.js";
100
123
  import { MCP_SETTINGS_PAGE, signInCookie, startedHere } from "./mcp-oauth.js";
101
124
  import { WEBHOOK_EVENTS, WEBHOOK_FILE, waitMarkerOf, Webhooks } from "./webhooks.js";
102
125
  import { appPermissionWarnings } from "./template-github-permissions.js";
@@ -111,10 +134,14 @@ import { HookCut, receivePush } from "./push-handler.js";
111
134
  import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
112
135
  import { webhook } from "./trigger-webhook.js";
113
136
  import { SCHEME_NAMES } from "./trigger-signatures.js";
114
- import { permissionFrom } from "./tool-gate.js";
137
+ import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
138
+ import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
115
139
  import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
116
- import { applyBodyOf, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, packageModel, packageTiers, packageView, pickComputer, readPackages } from "./templates.js";
117
- import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, isObject, stable, unknownFields } from "./validate.js";
140
+ import { applyBodyOf, choiceUnrunnable, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, serversFor, TemplateRegistry } from "./templates.js";
141
+ import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
142
+ import { templateInstallLink, templateLink } from "./console-links.js";
143
+ import { GITHUB_HOSTS } from "./template-source.js";
144
+ import { checkDefinitionBody, DEFAULT_INPUT_SCHEMA, definitionBodyIssues, EXTERNAL_NAME, ID, IDEMPOTENCY_TTL_S, inputIssues, inputSchemaOf, isObject, stable, unknownFields } from "./validate.js";
118
145
  import { agentTools, BROWSER_VENDOR_IDS, browserKeyRow, isUnavailable, keptVendor, loadToolSettings, recheckPlane, settingsIssues, whyUnavailable, withDefaults } from "./tool-plane.js";
119
146
  import { wakeAnsweredBySetting } from "./settings-wake.js";
120
147
  import { toolSettingsOverStore } from "./tool-settings-store.js";
@@ -122,12 +149,15 @@ import { readApprovers, writeApprovers } from "./server-approvers.js";
122
149
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
123
150
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
124
151
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
125
- import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runViewedKind } from "./computer-routes.js";
152
+ import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
126
153
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
127
154
  import { createAttachRoutes, pairedView } from "./computer-attach.js";
128
155
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
129
156
  import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
157
+ import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
130
158
  import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
159
+ import { noAccount, openAccount } from "./email/account.js";
160
+ import { emailRoute } from "./email/routes.js";
131
161
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
132
162
  import { computerOfPlace } from "./computer-setting.js";
133
163
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
@@ -194,6 +224,25 @@ const digest = (text) => createHash("sha256").update(text).digest();
194
224
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
195
225
  const SESSION_S = SESSION_MS / 1000;
196
226
  export const ROUTES = [
227
+ { method: "GET", pattern: /^\/observations$/, name: "getObservations" },
228
+ { method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
229
+ { method: "POST", pattern: /^\/connectors\/enrollment$/, name: "enrollRemoteConnector" },
230
+ { method: "POST", pattern: /^\/connectors$/, name: "registerRemoteConnector" },
231
+ { method: "DELETE", pattern: /^\/connectors\/([^/]+)$/, name: "revokeRemoteConnector" },
232
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/import$/, name: "importRemoteTarget" },
233
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/history$/, name: "importRemoteHistory" },
234
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/poll$/, name: "pollRemoteConnector" },
235
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/events$/, name: "remoteCommandEvents" },
236
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/complete$/, name: "completeRemoteCommand" },
237
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/sdk-runs$/, name: "startSdkRun" },
238
+ { method: "GET", pattern: /^\/sdk-runs\/([^/]+)$/, name: "getSdkRun" },
239
+ { method: "POST", pattern: /^\/sdk-runs\/([^/]+)\/events$/, name: "sdkRunEvents" },
240
+ { method: "POST", pattern: /^\/sdk-runs\/([^/]+)\/complete$/, name: "completeSdkRun" },
241
+ { method: "POST", pattern: /^\/native\/discover$/, name: "discoverNative" },
242
+ { method: "POST", pattern: /^\/native\/connect$/, name: "connectNative" },
243
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/native$/, name: "getNative" },
244
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/native\/verify$/, name: "verifyNative" },
245
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/native\/disconnect$/, name: "disconnectNative" },
197
246
  { method: "GET", pattern: /^\/capabilities$/, name: "getCapabilities" },
198
247
  { method: "GET", pattern: /^\/openapi\.json$/, name: "getOpenapi" },
199
248
  // Answered here only with accounts off: with accounts on, the owner's routes answer it before any route (ownerRoute).
@@ -227,6 +276,8 @@ export const ROUTES = [
227
276
  { method: "POST", pattern: /^\/runs\/([^/]+)\/cancel$/, name: "cancelRun" },
228
277
  { method: "POST", pattern: /^\/runs\/([^/]+)\/approvals\/([^/]+)$/, name: "answerApproval" },
229
278
  { method: "POST", pattern: /^\/runs\/([^/]+)\/archive$/, name: "archiveRun" },
279
+ // A person's or an eval's grade of an ended run (learn/promote.ts): what promotion by replay reads.
280
+ { method: "PUT", pattern: /^\/runs\/([^/]+)\/grade$/, name: "gradeRun" },
230
281
  { method: "POST", pattern: /^\/runs\/([^/]+)\/unarchive$/, name: "unarchiveRun" },
231
282
  { method: "GET", pattern: /^\/runs\/([^/]+)\/graph$/, name: "getRunGraph" },
232
283
  { method: "POST", pattern: /^\/workflows\/validate$/, name: "validateWorkflow" },
@@ -274,12 +325,27 @@ export const ROUTES = [
274
325
  { method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
275
326
  { method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
276
327
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
328
+ // The server's email account (email/routes.ts): the owner's session's alone, its password in no answer.
329
+ { method: "GET", pattern: /^\/settings\/email$/, name: "getEmailAccount" },
330
+ { method: "PUT", pattern: /^\/settings\/email$/, name: "saveEmailAccount" },
331
+ { method: "DELETE", pattern: /^\/settings\/email$/, name: "deleteEmailAccount" },
332
+ { method: "POST", pattern: /^\/settings\/email\/test$/, name: "testEmailAccount" },
333
+ { method: "GET", pattern: /^\/settings\/chatgpt$/, name: "getChatGPTSignIn" },
334
+ { method: "DELETE", pattern: /^\/settings\/chatgpt$/, name: "signOutChatGPT" },
335
+ { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in$/, name: "startChatGPTSignIn" },
336
+ { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in\/finish$/, name: "finishChatGPTSignIn" },
277
337
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
278
338
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
279
339
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
280
340
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
281
341
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
282
342
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio$/, name: "saveComposioServer" },
343
+ // A saved Composio server's triggers (composio-triggers.ts): its toolkit's events, its triggers and their state on
344
+ // Composio, and the project's webhook subscription (its secret rotated, or the subscription deleted: secret writes).
345
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/events$/, name: "listComposioEvents" },
346
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/triggers$/, name: "listComposioTriggers" },
347
+ { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/rotate-secret$/, name: "rotateComposioSecret" },
348
+ { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/subscription$/, name: "deleteComposioSubscription" },
283
349
  { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
284
350
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
285
351
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/oauth\/start$/, name: "startMcpOAuth" },
@@ -306,9 +372,12 @@ export const ROUTES = [
306
372
  { method: "GET", pattern: /^\/triggers\/([^/]+)\/firings$/, name: "listTriggerFirings" },
307
373
  { method: "POST", pattern: /^\/triggers\/([^/]+)\/secret$/, name: "rotateTriggerSecret" },
308
374
  { method: "GET", pattern: /^\/templates$/, name: "listTemplates" },
375
+ { method: "POST", pattern: /^\/templates\/import$/, name: "importTemplate" },
376
+ { method: "DELETE", pattern: /^\/templates\/([^/]+)$/, name: "deleteTemplate" },
309
377
  { method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
310
378
  // Answered before the bearer check: the request's signature is its credential.
311
- { method: "POST", pattern: /^\/hooks\/([^/]+)$/, name: "receiveHook" },
379
+ // A source that keeps its key per scope (Composio's projects) is served at /hooks/{source}/{scope}.
380
+ { method: "POST", pattern: /^\/hooks\/([^/]+)(?:\/([^/]+))?$/, name: "receiveHook" },
312
381
  { method: "GET", pattern: /^\/integrations\/github$/, name: "getGitHubConnection" },
313
382
  { method: "DELETE", pattern: /^\/integrations\/github$/, name: "disconnectGitHub" },
314
383
  { method: "POST", pattern: /^\/integrations\/github\/connect$/, name: "connectGitHub" },
@@ -318,12 +387,14 @@ export const ROUTES = [
318
387
  { method: "POST", pattern: /^\/mcp$/, name: "callMcp" },
319
388
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning$/, name: "getAgentLearning" },
320
389
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/cost$/, name: "getLearningCost" },
390
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/promotions$/, name: "listLearningPromotions" },
321
391
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "createLearningBatch" },
322
392
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches$/, name: "listLearningBatches" },
323
393
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)$/, name: "getLearningBatch" },
324
394
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/batches\/([^/]+)\/cancel$/, name: "cancelLearningBatch" },
325
395
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "listLearningEvals" },
326
396
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/evals$/, name: "recordLearningEval" },
397
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/loop$/, name: "getLearningLoop" },
327
398
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/notes$/, name: "listLearningNotes" },
328
399
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/log$/, name: "listLearningLog" },
329
400
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)$/, name: "readLearningFile" },
@@ -333,6 +404,8 @@ export const ROUTES = [
333
404
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
334
405
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions$/, name: "listLearnedWorkflowRevisions" },
335
406
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
407
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays$/, name: "startLearnedWorkflowReplay" },
408
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays\/([^/]+)$/, name: "getLearnedWorkflowReplay" },
336
409
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
337
410
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
338
411
  ];
@@ -342,15 +415,19 @@ export const ROUTES = [
342
415
  * kept plane's (a run from before the plane names none, and is Browserbase's where it grants the tool) checked again as a
343
416
  * launch would be; off, saying why, where it has none or its browser resolves unavailable here. Where the agent's
344
417
  * computer is a browser, that browser, whose keys are the computer's (checked at the run's start), never the plane's.
418
+ * A run whose agent's computer is a sandbox (`own`, its revision's kind) and has no browser has a computer with no
419
+ * screen: off says so, never that its agent has none; its browser, where it has the tool, is its view, and why that
420
+ * browser is unavailable is said as for any run.
345
421
  * TODO: the agent's own `computer: {kind, provider?}` setting once definitions carry it (desktop, phone). */
346
- function computerOf(kept, env, family = "computer") {
422
+ function computerOf(kept, env, family = "computer", own) {
347
423
  if (kept === ON_COMPUTER)
348
424
  return { kind: "browser" };
349
425
  const browser = kept === undefined ? undefined : recheckPlane({ browser: kept }, env).browser;
350
426
  if (browser === undefined)
351
- return { off: family === "browser" ? "this run's agent has no browser tool" : "this run's agent has no computer" };
427
+ return { off: family === "browser" ? "this run's agent has no browser tool" : own === "sandbox" ? SANDBOX_NO_SCREEN : "this run's agent has no computer" };
352
428
  return isUnavailable(browser) ? { off: whyUnavailable(browser) } : { kind: "browser" };
353
429
  }
430
+ const SANDBOX_NO_SCREEN = "A sandbox has no screen: what the agent runs in it is on the timeline.";
354
431
  /** The run's kept browser vendor, over the store, as computerOf reads it: the vendor its launch plane resolved at start
355
432
  * (the same source the runner's claim reads), normalized to the vendor name (keptVendor) so recheckPlane re-resolves it as
356
433
  * a vendor, not a stored no-key sentinel; with no browser in the plane, the default vendor when the run's revision grants
@@ -402,7 +479,18 @@ export function offersEnvOf(env) {
402
479
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
403
480
  * saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
404
481
  * the offers probed again, never shown. */
405
- const offersInputs = (env) => SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]);
482
+ const offersInputs = (env) => [...SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]), planOf(env)?.state, planOf(env)?.models.join(" ")];
483
+ /** A sign-in step's answer; its refusal (a stale or bad pasted address, no sign-in waiting, OpenAI's no) a 400 in words. */
484
+ async function planStep(step) {
485
+ try {
486
+ return await step();
487
+ }
488
+ catch (error) {
489
+ if (error instanceof PlanSignInRefused)
490
+ throw new ApiError("bad_request", error.message);
491
+ throw error;
492
+ }
493
+ }
406
494
  async function needsOf(env) {
407
495
  const chosen = await chooseModel(env, undefined);
408
496
  if ("why" in chosen)
@@ -516,7 +604,7 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
516
604
  tool_keys: { routes: true, at_rest: "sealed" },
517
605
  /** /settings/mcp-servers: remote MCP servers previewed and saved, each credential sealed under the server's seal key,
518
606
  * which always exists (seal-key.ts), so MCP credentials are always kept sealed. */
519
- mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...MCP_HARNESSES] },
607
+ mcp_client: { transports: ["streamable-http"], auth: [...MCP_AUTH_TYPES], at_rest: "sealed", harnesses: [...HARNESSES] },
520
608
  /** This server's learning switch (`--learning`): on, a run learns when its agent says `learning: true`; off, none does. */
521
609
  learning,
522
610
  /** /settings/webhook: one URL POSTed, signed by the Standard Webhooks spec, when a run needs its person and when it
@@ -541,6 +629,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
541
629
  idempotency_ttl_s: IDEMPOTENCY_TTL_S,
542
630
  input_wait_s: null,
543
631
  max_cost_usd: null,
632
+ // The most requests on free models a run makes (AGENTRUN_FREE_MODEL_REQUESTS, else 60): each costs $0, so the
633
+ // dollar cap cannot stop them, and this does (the kernel cap's free.ts). ChatGPT-plan requests don't count.
634
+ free_model_requests: freeModelRequestsOf(env),
544
635
  },
545
636
  };
546
637
  }
@@ -597,6 +688,8 @@ export async function startServe(options) {
597
688
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
598
689
  const learning = learningOf(process.env, options.learning);
599
690
  const learningBudget = learningBudgetOf(process.env, options.learningBudget);
691
+ // A limit on a run's requests on free models that is no whole number above 0 stops the start, naming its variable.
692
+ freeModelRequestsOf(process.env);
600
693
  const minFreeMib = process.env.AGENTRUN_MIN_FREE_MB ? Number(process.env.AGENTRUN_MIN_FREE_MB) : MIN_FREE_MIB;
601
694
  if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
602
695
  throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
@@ -689,7 +782,15 @@ async function startHolding(options, data, checked, stops) {
689
782
  warn: (message) => void process.stderr.write(`agentrun-serve: ${message}\n`),
690
783
  ...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
691
784
  }), (error) => onSqlite && error instanceof StoreOwned, replacedUntil, waitingForReplaced);
692
- stops.push(() => store.close());
785
+ let stopObservationRetention = async () => undefined;
786
+ stops.push(async () => { await stopObservationRetention(); await store.close(); });
787
+ // The packages served: the bundled ones, read and checked before the start, and those imported here, which the store
788
+ // keeps and are checked again as they load (template-import.ts). One that no longer checks is left out, said in the log.
789
+ const registry = new TemplateRegistry(templates);
790
+ await loadImported({ registry, store }, (id, why) => log?.(logLine("template_import_skipped", { template: id, why })));
791
+ stopObservationRetention = await maintainObservations(new Observations(store), {
792
+ onError: () => { process.stderr.write("agentrun-serve: observation retention failed; retrying on the next sweep\n"); },
793
+ });
693
794
  // The person's own computers paired with this server (computer-attach.ts): their live sockets are this process's hub,
694
795
  // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
695
796
  // store is refused above (its owner lock).
@@ -743,24 +844,23 @@ async function startHolding(options, data, checked, stops) {
743
844
  const mcpServers = mcpServersOverStore(store, own(withSecrets(base, "own")), VERSION);
744
845
  if (options.githubMcpOrigin)
745
846
  mcpServers.appOrigin = options.githubMcpOrigin;
746
- // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the run-grant checks read in
747
- // step (blockersOf's `mcp`, and the template apply): the server is the one writer of these rows (a save, refresh, sign-in
748
- // or delete), so the snapshot is refreshed after each of those and reads what is saved now. The runner reads the registry,
749
- // pins and credentials from the store at a run's claim (runner/mcp-claim.ts); this server hands a run no MCP source.
847
+ mcpServers.standIns = options.mcpStandIns === true;
848
+ // The saved MCP servers' metadata (their addresses and the tools they list), a snapshot the checks read in step (which
849
+ // servers are saved, a workflow's grants, the template apply): the server is the one writer of these rows (a save,
850
+ // refresh, sign-in or delete), so the snapshot is refreshed after each of those and reads what is saved now. An agent's
851
+ // save lists its granted servers live and pins their tools on its revision (saveable, mcpListingOf); the runner reads
852
+ // that pin and the credentials from the store at a run's claim (runner/mcp-claim.ts); this server hands a run no MCP
853
+ // source. Each with what it is (its source and toolkit, mcp-sources.ts), which a template's apply maps its MCP needs on.
750
854
  let mcpMeta = new Map();
751
855
  const refreshMcpMeta = async () => {
752
- mcpMeta = new Map((await store.mcp.servers()).map((row) => [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [] }]));
856
+ mcpMeta = new Map(await Promise.all((await listMcpServers(store)).map(async (row) => [row.name, { url: row.url, auth: row.auth, tools: row.tools ?? [], source: await mcpServers.sourceOf(row) }])));
753
857
  };
754
858
  await refreshMcpMeta();
755
859
  // Each saved server's tools in the harnesses' shape (the registry keeps input_schema; a bound tool takes inputSchema),
756
860
  // with whether each can be granted: a known meta tool can't (mcp-meta.ts).
757
861
  const mcpTools = (server) => {
758
862
  const saved = mcpMeta.get(server);
759
- return saved?.tools.map((tool) => {
760
- const meta = metaToolOf(saved.url, tool.name);
761
- const bound = { name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), inputSchema: (tool.input_schema ?? {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) };
762
- return meta ? { ...bound, grantable: false, reason: meta.reason } : bound;
763
- });
863
+ return saved && marked(saved.url, { tools: saved.tools.map((tool) => ({ name: tool.name, ...(tool.title ? { title: tool.title } : {}), ...(tool.description ? { description: tool.description } : {}), inputSchema: (tool.input_schema ?? {}), ...(tool.annotations ? { annotations: tool.annotations } : {}) })) }).tools;
764
864
  };
765
865
  // The server's tool settings, in the store: capabilities say what they resolve to, again after a PUT. load() reads them
766
866
  // once here.
@@ -777,7 +877,12 @@ async function startHolding(options, data, checked, stops) {
777
877
  // settings, caps; a save or delete of a key, env and caps, and the offers only when what they are made from changed,
778
878
  // which no tool key is. So a write answers at once, and capabilities, save checks and run checks after it see it, with
779
879
  // no restart and no request opening the file. The offers are probed once saved keys are read (below), at the start.
780
- let env = own(withSecrets(base, "all", storedKeys));
880
+ // The ChatGPT sign-in, sealed in the store: on every reading of env (chatgpt-plan.ts withPlan), so a plan model runs
881
+ // where it is signed in. A sign-in, a sign-out or an expiry it sees makes the reading again, as a key's save does.
882
+ const plan = new ChatGPTPlan({ store, sealKey: seal.key, log: (fields) => (log ? log(logLine("chatgpt", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("chatgpt", fields)}\n`)), changed: () => keysChanged() });
883
+ await plan.load();
884
+ stops.push(async () => plan.close());
885
+ let env = withPlan(own(withSecrets(base, "all", storedKeys)), plan);
781
886
  let offers;
782
887
  let caps;
783
888
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -809,7 +914,7 @@ async function startHolding(options, data, checked, stops) {
809
914
  const keysChanged = async () => {
810
915
  // A run's learning, view, list and timeline row are cut of the keys saved now by the run view at read time (it reads
811
916
  // serverSecrets live, store-view), so a key change needs no cache invalidation here.
812
- env = own(withSecrets(base, "all", storedKeys));
917
+ env = withPlan(own(withSecrets(base, "all", storedKeys)), plan);
813
918
  const mine = ++needsAsked;
814
919
  const next = await needsOf(env);
815
920
  if (mine === needsAsked)
@@ -820,6 +925,12 @@ async function startHolding(options, data, checked, stops) {
820
925
  else
821
926
  await probe("key");
822
927
  };
928
+ /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again. */
929
+ const planNow = async () => {
930
+ const was = plan.state;
931
+ if ((await plan.load()).state !== was)
932
+ await keysChanged();
933
+ };
823
934
  // The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
824
935
  // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
825
936
  // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
@@ -954,6 +1065,19 @@ async function startHolding(options, data, checked, stops) {
954
1065
  }
955
1066
  return { none: `this server has no shell to give an agent now: Archil is off (Settings → Workspace), and the docker box is unavailable here (${why})` };
956
1067
  };
1068
+ /** Each package's computer list read against this server now, as a listing shows it (`computer_here`): what an apply
1069
+ * here would pick (pickComputer), the shell asked for once for them all. */
1070
+ const computerHere = async (packages) => {
1071
+ const here = packages.some((one) => one.computer) ? await shellHere() : undefined;
1072
+ return (pkg) => {
1073
+ const pick = here && pickComputer(pkg, here);
1074
+ if (!pick)
1075
+ return null;
1076
+ if ("refused" in pick)
1077
+ return { entry: null, computer: null, shell: null, dropped: [], note: pick.refused };
1078
+ return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
1079
+ };
1080
+ };
957
1081
  const archil = createArchilRoutes({ store, sealKey, env: process.env, ...(options.archilControl ? { control: options.archilControl } : {}) });
958
1082
  /** Where a run of `revision` has its shell (shellOf): its computer setting as the claim reads it (computer-for-claim.ts
959
1083
  * settingOf), else its place's computer, else the place its run would resolve to (fallbackPlace). The agent's tool
@@ -971,7 +1095,7 @@ async function startHolding(options, data, checked, stops) {
971
1095
  const agents = {
972
1096
  get: (id) => getAgent(store, id),
973
1097
  list: (options = {}) => listAgents(store, options),
974
- create: (body, check, fresh) => createAgent(store, body, { ...(check ? { check } : {}), ...(fresh ? { fresh } : {}) }),
1098
+ create: (body, check, fresh, template) => createAgent(store, body, { ...(check ? { check } : {}), ...(fresh ? { fresh } : {}), ...(template ? { template } : {}) }),
975
1099
  commit: (entry, body, options = {}) => commitAgent(store, entry, body, options),
976
1100
  revisions: (id) => agentRevisions(store, id),
977
1101
  revision: (agentId, revisionId) => agentRevision(store, agentId, revisionId),
@@ -989,6 +1113,16 @@ async function startHolding(options, data, checked, stops) {
989
1113
  };
990
1114
  ({ secrets: secretStores, settings: triggerSettings } = await openServerSecretsOverStore(store, data, env, adapters, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`))));
991
1115
  secretStores.add("server", () => [token]);
1116
+ // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1117
+ // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1118
+ const emailPasswords = new Set();
1119
+ const heldEmailPassword = async () => {
1120
+ const password = (await openAccount(store, sealKey).catch(() => undefined))?.password;
1121
+ if (password)
1122
+ emailPasswords.add(password);
1123
+ };
1124
+ await heldEmailPassword();
1125
+ secretStores.add("email", () => [...emailPasswords]);
992
1126
  // Each agent's saved sign-ins, over the one store (module A, sign-ins-store): the vendor's calls on the server's keys
993
1127
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
994
1128
  // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
@@ -1032,11 +1166,16 @@ async function startHolding(options, data, checked, stops) {
1032
1166
  const lock = options.harnessLocks?.[entry.id];
1033
1167
  // npm past its SIGTERM's grace (it waits on a tarball once it writes): killed, and the line says so.
1034
1168
  const onKilled = () => log?.(logLine("harness_install_killed", { harness: entry.id, said: `npm did not stop within ${NPM_STOP_GRACE_MS / 1000} s of SIGTERM; killed` }));
1035
- return [entry.id, new HarnessInstall(entry, installDirOf(data, entry.id), pins, (entry, dir, pins, signal) => npmInstall(entry, dir, pins, { signal, onKilled, ...(lock ? { lock } : {}) }), (ms) => {
1169
+ return [entry.id, new HarnessInstall(entry, installDirOf(data, entry.id), pins, options.harnessInstall ?? ((entry, dir, pins, signal) => npmInstall(entry, dir, pins, { signal, onKilled, ...(lock ? { lock } : {}) })), (ms) => {
1036
1170
  log?.(logLine("harness_installed", { harness: entry.id, ms, dir: installDirOf(data, entry.id) }));
1037
1171
  void probe(`${entry.id}_installed`).catch(() => undefined);
1038
1172
  })];
1039
1173
  }));
1174
+ // Each harness found installed as this server starts has what earlier installs left beside it swept (HarnessInstall
1175
+ // needed): the point sure to come after an install that could not remove one (a crashed server's npm still writing in
1176
+ // it), since no install runs again until the pin changes. Not waited for; the close waits for it (install.stop).
1177
+ for (const install of Object.values(installs))
1178
+ void install.needed().catch(() => undefined);
1040
1179
  // A capped start prices each OpenRouter Decisions model a workflow pins (runnable.ts) from OpenRouter's public catalog,
1041
1180
  // read once for this server (and again after a read that failed), through the faux one under --faux.
1042
1181
  let pricing;
@@ -1055,7 +1194,7 @@ async function startHolding(options, data, checked, stops) {
1055
1194
  // no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
1056
1195
  // needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
1057
1196
  // reads launch.model alone).
1058
- const modelOf = (_entry, revision) => runModelRef(env, revision);
1197
+ const modelOf = (_entry, revision) => nativeOf(revision.body) ? Promise.resolve(undefined) : runModelRef(env, revision);
1059
1198
  const startDeps = {
1060
1199
  runBodyIssues,
1061
1200
  boundRepos: async (agentId) => bindingOf(await store.triggers.list(agentId), agentId),
@@ -1066,6 +1205,7 @@ async function startHolding(options, data, checked, stops) {
1066
1205
  // (called at request time, after they are assigned) rather than reading them before their declaration.
1067
1206
  told: (error) => told(error),
1068
1207
  runnable,
1208
+ pinFirst: (revision) => pinFirst(revision),
1069
1209
  readyFiles: (ids) => uploads.readyFiles(ids),
1070
1210
  files: { hold: (runId, ids) => uploads.hold(runId, ids), release: (runId) => uploads.release(runId) },
1071
1211
  fallbackPlace: (kind, tools) => fallbackPlace(kind, tools),
@@ -1118,12 +1258,13 @@ async function startHolding(options, data, checked, stops) {
1118
1258
  },
1119
1259
  shown: () => secretsShown(serverSecrets(), { local: true }),
1120
1260
  };
1121
- /** What a learning batch's loop reads of a run, from its view. */
1261
+ /** What a learning batch's loop reads of a run, from its view. Its `cost_usd` is the exact cost: a batch's figures say
1262
+ * no "at most", so a view cost marked `upper_bound` reads null there, as the run's stored cost does (RunRow.costUsd). */
1122
1263
  const batchRunView = async (runId) => {
1123
1264
  const v = (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())));
1124
1265
  if (!v)
1125
1266
  return undefined;
1126
- return { status: String(v.status), ended_at: v.ended_at ?? null, answer: typeof v.result?.final_answer === "string" ? v.result.final_answer : null, cost_usd: typeof v.cost?.usd === "number" ? v.cost.usd : null, learning_state: typeof v.learning?.state === "string" ? v.learning.state : null, error: typeof v.error?.message === "string" ? v.error.message : null };
1267
+ return { status: String(v.status), ended_at: v.ended_at ?? null, answer: typeof v.result?.final_answer === "string" ? v.result.final_answer : null, cost_usd: typeof v.cost?.usd === "number" && v.cost.upper_bound !== true ? v.cost.usd : null, learning_state: typeof v.learning?.state === "string" ? v.learning.state : null, error: typeof v.error?.message === "string" ? v.error.message : null };
1127
1268
  };
1128
1269
  // Learn from a CSV (learning-batch.ts): a batch's loop runs in this process over the run write half and the run view; its
1129
1270
  // state is the store's settings, so a batch still running when the server stopped takes up again as it starts. Its reads
@@ -1165,7 +1306,8 @@ async function startHolding(options, data, checked, stops) {
1165
1306
  // Every round the run kept (a review follow-up opens a round of its own), in order: what each one learned and merged.
1166
1307
  const newest = await store.learning.proposal(runId);
1167
1308
  const ends = await Promise.all(Array.from({ length: newest?.round ?? 1 }, (_, i) => runLearningEnd(store, runId, i + 1)));
1168
- return figuresOf(await costRunOf(store, run, 0), ends);
1309
+ // A run still going names no path yet (its end writes it): the batch reads it as the agent's until then.
1310
+ return figuresOf((await costRunOf(store, run, 0)) ?? { path: "agent", ...(await allInOf(store, run)) }, ends);
1169
1311
  },
1170
1312
  // A batch's reads are the learning routes' reads: the same cut, the same 403 when a sign-in can't be read here.
1171
1313
  shown: (agentId) => learningShown(agentId),
@@ -1212,7 +1354,7 @@ async function startHolding(options, data, checked, stops) {
1212
1354
  // shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
1213
1355
  // error's words. A run whose hand can't be read back here is withheld: none of its rows. A run's Timeline is read
1214
1356
  // from its journal, which keeps what the run said whole.
1215
- timelineRows: (forStore, runId, context) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses }, forStore, runId, context),
1357
+ timelineRows: (forStore, runId, context, calls) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses }, forStore, runId, context, calls),
1216
1358
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1217
1359
  });
1218
1360
  const triggerDeps = {
@@ -1326,6 +1468,17 @@ async function startHolding(options, data, checked, stops) {
1326
1468
  const githubConnection = () => github.view();
1327
1469
  /** What applying a template reads of the server (templates.ts TemplatesDeps). */
1328
1470
  const templateDeps = { githubConnection };
1471
+ // A template import reads GitHub's own hosts alone (a test's faux GitHub in their place), with an installation token of
1472
+ // the App when GitHub is connected (tokenForListing: metadata read, the least there is), else anonymously, and says why.
1473
+ const importDeps = {
1474
+ registry, store,
1475
+ reach: async (signal) => {
1476
+ const api = options.templateImportApi ?? GITHUB_API;
1477
+ const hosts = options.templateImportApi ? [new URL(options.templateImportApi).host] : GITHUB_HOSTS;
1478
+ const minted = options.templateImportApi ? { unusable: "it reads a test's GitHub" } : await githubConnect.tokenForListing(signal).catch((error) => ({ unusable: error.message }));
1479
+ return "token" in minted ? { api, hosts, token: minted.token } : { api, hosts, anonymous: "unusable" in minted ? minted.unusable : minted.failed };
1480
+ },
1481
+ };
1329
1482
  // A github_app MCP server's tools are listed with an installation token of the App, narrowed to one repository it covers
1330
1483
  // with metadata read (tokenForListing); a run's own is minted in the runner (runner/github-app.ts). Every token minted
1331
1484
  // is a server secret while it may be in use.
@@ -1338,7 +1491,9 @@ async function startHolding(options, data, checked, stops) {
1338
1491
  clock: options.triggerClock,
1339
1492
  ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1340
1493
  adapters,
1341
- unavailable: (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : undefined),
1494
+ unavailable: async (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : kind === "email" && !(await openAccount(store, sealKey)) ? noAccount() : undefined),
1495
+ // The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
1496
+ credentials: async (kind) => (kind === "email" ? openAccount(store, sealKey) : undefined),
1342
1497
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1343
1498
  // The trigger target policy (what a trigger may start or message, and in what words it is refused) is the one store's
1344
1499
  // (trigger-targets.ts, over the run write half and the run view): targetIssues, start, message, statusOf, runOf. The
@@ -1346,6 +1501,17 @@ async function startHolding(options, data, checked, stops) {
1346
1501
  ...targets,
1347
1502
  settings: (adapterId) => triggerSettings.get(adapterId),
1348
1503
  notify: (failed, key) => webhooks.emitTrigger(failed, key),
1504
+ // A Composio trigger's instance, and the project's subscription, are made and kept on Composio with its server's key.
1505
+ upstream: (kind) => (kind === "composio" ? composioTriggers : undefined),
1506
+ });
1507
+ const composioTriggers = new ComposioTriggers({
1508
+ control: options.composioControl ?? {},
1509
+ ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1510
+ sealed: triggerSettings.get("composio"),
1511
+ credential: (name, refusal) => mcpServers.composioOf(name, refusal),
1512
+ holders: () => triggers.ofKind("composio"),
1513
+ signal: stopping.signal,
1514
+ say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1349
1515
  });
1350
1516
  // A repair of the GitHub installations (below) stops before the triggers close, in a start that fails as in close.
1351
1517
  stops.push(() => githubConnect.close());
@@ -1371,7 +1537,7 @@ async function startHolding(options, data, checked, stops) {
1371
1537
  // not passed; the worker reads them from the store over the port (sealed rows it opens with the seal key among these
1372
1538
  // secrets), the same cut as the CLI's import, where a saved key and the server's own of the same name may differ.
1373
1539
  workerData: { task, data, home: options.sessionsHome?.home ?? homedir(), ...(options.sessionsHome?.temp ? { temp: options.sessionsHome.temp } : {}), secrets: Object.fromEntries(SECRET_NAMES.flatMap((name) => { const value = name === SEAL_KEY_ENV ? seal.text : secret(name); return value === undefined ? [] : [[name, value]]; })) },
1374
- // Started from a string (its launcher runs node --input-type=module -e), the server's flags are given again
1540
+ // Started from a string (node --input-type=module -e, as a test or a `--` command may), the server's flags are given again
1375
1541
  // without that string and its type: a worker started from a file with them is refused. Otherwise the worker
1376
1542
  // inherits them as Node passes them on, which leaves out the flags a worker may not take (on Node 24 a test
1377
1543
  // runner's child holds many).
@@ -1462,7 +1628,7 @@ async function startHolding(options, data, checked, stops) {
1462
1628
  throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
1463
1629
  return Buffer.concat(chunks);
1464
1630
  }
1465
- async function bodyOf(req) {
1631
+ async function bodyOf(req, max = MAX_BODY) {
1466
1632
  // Read once: the secret-write check reads a registered operation's body before its route does (secret-writes.ts).
1467
1633
  const read = bodies.get(req);
1468
1634
  if (read !== undefined)
@@ -1470,7 +1636,7 @@ async function startHolding(options, data, checked, stops) {
1470
1636
  const type = String(req.headers["content-type"] ?? "");
1471
1637
  if (!type.startsWith("application/json"))
1472
1638
  throw new ApiError("unsupported_media_type", "the body must be application/json");
1473
- const bytes = await bytesOf(req);
1639
+ const bytes = await bytesOf(req, max);
1474
1640
  let value;
1475
1641
  try {
1476
1642
  value = JSON.parse(bytes.toString("utf8") || "null");
@@ -1490,24 +1656,19 @@ async function startHolding(options, data, checked, stops) {
1490
1656
  const revision = (entry ?? (await needAgent(id))).revision;
1491
1657
  if (revision?.kind !== "agentic")
1492
1658
  return { tools: [], gated: {}, deniedBy: {} };
1493
- const [{ learnedDraftTools, mcpGrantsListed }, { permissionFrom }, { learnedAskFits }] = await Promise.all([import("./tools.js"), import("./tool-gate.js"), import("./learned-workflow.js")]);
1659
+ const [{ learnedDraftTools }, { permissionFrom }] = await Promise.all([import("./tools.js"), import("./tool-gate.js")]);
1494
1660
  const server = settings.get();
1495
1661
  // The revision row's body is the agentic body JSON (store-backed RevisionRow types it as unknown).
1496
1662
  const body = revision.body;
1497
- // A server's wildcard grant read as the tools its server lists now (tools.ts mcpGrantsListed, LS-07).
1498
- const rows = (body.tools ?? []).some((name) => /^mcp:[^/]+\/\*$/.test(name)) ? await store.mcp.servers().catch(() => []) : [];
1499
- const listed = new Map(rows.map((row) => [row.name, (row.tools ?? []).flatMap((tool) => (typeof tool?.name === "string" ? [tool.name] : []))]));
1500
1663
  const gate = (name) => permissionFrom(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask");
1501
1664
  // `deniedBy`: where each deny was set (the agent's tool settings, the server's), which a refused draft's words name.
1502
- const { tools, gated, deniedBy, asked } = learnedDraftTools(mcpGrantsListed(body.tools ?? [], (name) => listed.get(name) ?? []), (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
1503
- // #2424's card rule (learnedAskFits): a restored draft whose ask-set MCP tools would not all show is refused.
1504
- const ask = { asked, fits: learnedAskFits };
1665
+ const { tools, gated, deniedBy } = learnedDraftTools(body.tools ?? [], (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
1505
1666
  // A draft's decision nodes (LS-07), as a run's learning end checks them: on this server's decision providers (its
1506
1667
  // keys, saved ones among them: env), each held to the gate by its bare id; deny alone refuses one.
1507
1668
  const [{ decisionProvidersIn }, { DECISION_PROVIDER_KEYS }] = await Promise.all([import("./decisions.js"), import("./tool-plane.js")]);
1508
1669
  const providers = await decisionProvidersIn(env);
1509
1670
  if (!providers)
1510
- return { tools, gated, deniedBy, ask };
1671
+ return { tools, gated, deniedBy };
1511
1672
  const decided = {};
1512
1673
  const decisionDeniedBy = {};
1513
1674
  for (const provider of DECISION_PROVIDER_KEYS) {
@@ -1518,7 +1679,7 @@ async function startHolding(options, data, checked, stops) {
1518
1679
  if (permission === "deny")
1519
1680
  decisionDeniedBy[provider] = from;
1520
1681
  }
1521
- return { tools, gated, deniedBy, ask, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1682
+ return { tools, gated, deniedBy, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1522
1683
  }
1523
1684
  async function needAgent(id) {
1524
1685
  const entry = ID.test(id) ? await agents.get(id) : null;
@@ -1526,13 +1687,24 @@ async function startHolding(options, data, checked, stops) {
1526
1687
  throw new ApiError("not_found", `no agent ${id}`);
1527
1688
  return entry;
1528
1689
  }
1690
+ /** The agent `id` (needAgent), refused when it is archived (409 agent_not_runnable): every route that starts its runs,
1691
+ * a person's start (createRun) and a replay's (startLearnedWorkflowReplay), asks this before it reserves or writes anything. */
1692
+ async function needRunnableAgent(id) {
1693
+ const entry = await needAgent(id);
1694
+ if (entry.agent.archivedAt)
1695
+ throw new ApiError("agent_not_runnable", `The agent ${id} is archived: unarchive it to run it.`, { details: { archived_at: new Date(entry.agent.archivedAt).toISOString() } });
1696
+ return entry;
1697
+ }
1529
1698
  /** An agent view's extra fields (agents-store agentView): its saved sign-ins, its learning count, and its run counts.
1530
1699
  * The run counts read the store's runs (store-reads/runs.ts listRuns): `count` is every run the agent has, `live` those
1531
1700
  * still running (runReadState 'running': queued, running or parked), the same numbers the file-backed view showed. */
1532
1701
  const agentExtra = async (entry) => {
1533
1702
  const learning = await learningOfAgent(entry);
1703
+ const native = nativeOf(entry.revision?.body);
1704
+ const nativeStatus = native?.remote ? await new RemoteConnectors(store).status(native) : undefined;
1534
1705
  const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
1535
1706
  return {
1707
+ ...(nativeStatus ? { nativeStatus } : {}),
1536
1708
  signIns: await signIns.view(entry.agent.id),
1537
1709
  ...(learning ? { learning } : {}),
1538
1710
  runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length },
@@ -1616,8 +1788,55 @@ async function startHolding(options, data, checked, stops) {
1616
1788
  * starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
1617
1789
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
1618
1790
  async function runnable(revision, place, { capped = false } = {}) {
1791
+ if (sdkOf(revision.body))
1792
+ throw new ApiError("agent_not_runnable", "This agent runs in its backend SDK. Call its SDK wrapper to start a task; AgentRun does not launch its tools or credentials.");
1793
+ const native = nativeOf(revision.body);
1794
+ if (native) {
1795
+ const overrides = nativeModelOverrides(revision.body);
1796
+ if (overrides.length)
1797
+ throw new ApiError("agent_not_runnable", NATIVE_MODEL_SETTINGS_UNSUPPORTED, { fields: overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })) });
1798
+ const execution = nativeExecutionOverrides(revision.body);
1799
+ if (execution.length)
1800
+ throw new ApiError("agent_not_runnable", NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, { fields: execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })) });
1801
+ if ((revision.body.maxToolCalls ?? 0) > 0)
1802
+ throw new ApiError("agent_not_runnable", NATIVE_TOOL_BUDGET_UNSUPPORTED, { fields: [{ field: "definition.max_tool_calls", reason: "not_an_option", message: NATIVE_TOOL_BUDGET_UNSUPPORTED }] });
1803
+ if (!native.remote && (options.apiOnly || options.publicUrl || !isLoopback(host)))
1804
+ throw new ApiError("agent_not_runnable", "Native connections run only on an AgentRun server bound to loopback on the source machine, without a public URL.");
1805
+ if (capped)
1806
+ throw new ApiError("agent_not_runnable", "Native runs retain their own limits; AgentRun cannot enforce a dollar cap on this connection. Remove max_cost_usd and use native limits.");
1807
+ if (native.remote)
1808
+ await new RemoteConnectors(store).assertReady(native);
1809
+ else
1810
+ await launchNative(native);
1811
+ return;
1812
+ }
1619
1813
  const shape = { ...shapeOf(revision), place, ...(revision.body.place ? {} : { unnamed: true }) };
1620
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools, decisionPrice });
1814
+ // An agentic revision's MCP tools are checked as its save pinned them (its pin, never the server's listing now), for
1815
+ // a server still saved here; a granted tool its pin does not hold is said first, with how to pin it.
1816
+ const pin = (revision.mcpPin ?? {});
1817
+ if (revision.kind === "agentic") {
1818
+ const unpinned = (revision.body.tools ?? []).flatMap((tool, index) => {
1819
+ const named = mcpToolOf(tool);
1820
+ if (!named || !mcpMeta.has(named.server))
1821
+ return [];
1822
+ const pinned = Object.hasOwn(pin, named.server) && pin[named.server].tools.some((one) => one.name === named.tool);
1823
+ return pinned ? [] : [{ field: `definition.tools[${index}]`, reason: "not_an_option", message: `The MCP tool ${tool} was not pinned when this revision was saved: save the agent again to pin it.`, tool }];
1824
+ });
1825
+ if (unpinned.length)
1826
+ throw new ApiError("agent_not_runnable", unpinned.map((one) => one.message).join(" "), { fields: unpinned.map(({ tool: _tool, ...issue }) => issue), details: { unbound: unpinned.map((one) => one.tool), missing: {} } });
1827
+ }
1828
+ const pinnedTools = (server) => {
1829
+ const saved = mcpMeta.get(server);
1830
+ if (!saved || !Object.hasOwn(pin, server))
1831
+ return undefined;
1832
+ // A meta tool at the URL it was pinned on or at the server's URL now (a server moved to a provider's host since).
1833
+ return pin[server].tools.map((tool) => {
1834
+ const meta = metaToolOf(pin[server].url, tool.name) ?? metaToolOf(saved.url, tool.name);
1835
+ return meta ? { ...tool, grantable: false, reason: meta.reason } : tool;
1836
+ });
1837
+ };
1838
+ const monid = revision.monidPin ?? undefined;
1839
+ const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice });
1621
1840
  if (!blockers.length)
1622
1841
  return;
1623
1842
  const message = blockers.map((b) => b.message).join(" ");
@@ -1640,12 +1859,94 @@ async function startHolding(options, data, checked, stops) {
1640
1859
  }
1641
1860
  /** Where a revision of `kind` naming `tools` and no place runs here: the place a new agent would be saved with. */
1642
1861
  const fallbackPlace = (kind, tools) => defaultPlaceOf(kind, tools, boxOffers, (tool) => toolOf(tool)?.runnerOnly === true);
1643
- /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks. A
1644
- * revision that names no place is checked where it would run (fallbackPlace). */
1645
- async function saveable(revision) {
1862
+ /** What a save of `revision` pins of the MCP tools it grants (an agentic revision's: a workflow's nodes bind none): each
1863
+ * granted server listed once, now, with its saved credential (McpServersOverStore.pinListing), as `tools` each server's
1864
+ * listing in the harnesses' shape for the save's checks (blockersOf's `mcp`), and `pin` making the pin from them. A server
1865
+ * that cannot be listed keeps the agent's `previous` pin for it when every tool the save grants from it is already
1866
+ * there (an edit that grants nothing new from it, its instructions say); else the save is refused (422) in words naming
1867
+ * it: nothing is saved, and saving again once it answers pins it. */
1868
+ async function mcpListingOf(revision, previous) {
1869
+ const tools = revision.kind === "agentic" ? (revision.body.tools ?? []) : [];
1870
+ const granted = tools.filter((tool) => mcpToolOf(tool) !== undefined);
1871
+ const listings = new Map();
1872
+ // A server carried from the previous pin, as that pin holds it (its tools already in the harnesses' shape).
1873
+ const carried = new Map();
1874
+ const before = (previous && typeof previous === "object" ? previous : {});
1875
+ const carry = (server) => {
1876
+ const kept = Object.hasOwn(before, server) ? before[server] : undefined;
1877
+ const all = kept && granted.every((tool) => { const named = mcpToolOf(tool); return named.server !== server || kept.tools.some((one) => one.name === named.tool); });
1878
+ if (all)
1879
+ carried.set(server, kept);
1880
+ return all;
1881
+ };
1882
+ const refused = [];
1883
+ await Promise.all([...new Set(granted.map((tool) => mcpToolOf(tool).server))].map(async (server) => {
1884
+ try {
1885
+ const listing = await mcpServers.pinListing(server, stopping.signal);
1886
+ if (listing)
1887
+ listings.set(server, listing);
1888
+ }
1889
+ catch (error) {
1890
+ if (!(error instanceof ApiError))
1891
+ throw error;
1892
+ if (carry(server))
1893
+ return;
1894
+ const why = error.extra.fields?.[0]?.message ?? error.message;
1895
+ refused.push({ field: `definition.tools[${tools.findIndex((tool) => mcpToolOf(tool)?.server === server)}]`, reason: "unavailable", message: `${sentence(`The MCP server ${server} could not be listed to pin its tools: ${why}`)} Nothing was saved: save again once it answers.` });
1896
+ }
1897
+ }));
1898
+ if (refused.length)
1899
+ throw invalid(refused.sort((a, b) => a.field.localeCompare(b.field)));
1900
+ const bound = (server) => {
1901
+ const kept = carried.get(server);
1902
+ // A carried server's tools are checked as pinned, a meta tool marked at its URL then or now (as runnable does).
1903
+ if (kept)
1904
+ return kept.tools.map((tool) => { const meta = metaToolOf(kept.url, tool.name) ?? (mcpMeta.has(server) ? metaToolOf(mcpMeta.get(server).url, tool.name) : undefined); return meta ? { ...tool, grantable: false, reason: meta.reason } : tool; });
1905
+ return listings.get(server)?.tools.map((tool) => ({ ...boundTool(tool), ...(tool.grantable === false ? { grantable: false, reason: tool.reason } : {}) }));
1906
+ };
1907
+ return {
1908
+ // A workflow's grants are checked on the registry's listing, as before: its nodes bind no MCP tool, so the save refuses them.
1909
+ tools: revision.kind === "agentic" ? bound : mcpTools,
1910
+ pin: () => {
1911
+ if (!granted.length)
1912
+ return undefined;
1913
+ try {
1914
+ return mcpPinOf(granted, { server: (name) => { const kept = carried.get(name); if (kept)
1915
+ return kept; const listing = listings.get(name); return listing && { url: listing.url, tools: listing.tools.map(boundTool), prices: listing.prices }; } });
1916
+ }
1917
+ catch (error) {
1918
+ throw invalid([{ field: "definition.tools", reason: "not_an_option", message: error.message }]);
1919
+ }
1920
+ },
1921
+ };
1922
+ }
1923
+ /** The revision a run starts on, its MCP tools pinned: one saved with no pin that grants a tool of a server saved here is
1924
+ * pinned at this, its first run (mcp-pin-first.ts pinFirst, the claim's path too). One that can't be (a server that
1925
+ * can't be listed, or no longer lists a granted tool) is left unpinned, and runnable refuses it (409) as before. */
1926
+ async function pinFirst(revision) {
1927
+ if ((revision.mcpPin ?? null) !== null)
1928
+ return revision;
1929
+ const pin = await pinFirstOf(revision, { saved: (server) => mcpMeta.has(server), pinListing: (server) => mcpServers.pinListing(server, stopping.signal), pinOnce: (id, made) => store.agents.pinOnce(id, made) });
1930
+ return pin ? { ...revision, mcpPin: pin } : revision;
1931
+ }
1932
+ /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks, and
1933
+ * its pins (mcpListingOf, monidPinOf), each carrying from `previous` what its grants did not change. A revision that
1934
+ * names no place is checked where it would run (fallbackPlace). */
1935
+ async function saveable(revision, previous) {
1646
1936
  // The store's NewRevision keeps the revision's fields under `body` (AgenticBody|WorkflowBody); build the flat shape the
1647
1937
  // host checks (runnable.ts RevisionShape) from it, as shapeOf does for a run's Revision.
1648
1938
  const body = revision.body;
1939
+ if (nativeOf(body)) {
1940
+ const overrides = nativeModelOverrides(body);
1941
+ if (overrides.length)
1942
+ throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
1943
+ const execution = nativeExecutionOverrides(body);
1944
+ if (execution.length)
1945
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
1946
+ return { warnings: [], stamp: {} };
1947
+ }
1948
+ if (sdkOf(body))
1949
+ return { warnings: [], stamp: {} };
1649
1950
  // An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
1650
1951
  const install = revision.kind === "agentic" ? installs[harnessOfBody(body)] : undefined;
1651
1952
  if (install) {
@@ -1653,36 +1954,82 @@ async function startHolding(options, data, checked, stops) {
1653
1954
  }
1654
1955
  const named = (revision.kind === "agentic" ? { kind: "agentic", ...body } : workflowShape(body));
1655
1956
  const shape = named.place ? named : { ...named, place: fallbackPlace(named.kind, named.tools ?? []), unnamed: true };
1656
- const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools });
1957
+ const listing = await mcpListingOf(revision, previous?.mcpPin);
1958
+ const mcp = listing.tools;
1959
+ const { monid, warnings: usage = [] } = (await monidPinOf(revision, previous)) ?? {};
1960
+ const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp, monid });
1657
1961
  // An agent's default cap caps each run started without one of its own, and a web tool resolves by the cap: what a cap
1658
1962
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
1659
1963
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
1660
1964
  if ((body.maxCostUsd ?? 0) > 0) {
1661
1965
  const key = (b) => `${b.field}\n${b.message}`;
1662
- const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools })).map(key));
1663
- const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, computerReady, shellOf, offers, mcp: mcpTools, decisionPrice });
1966
+ const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, shellOf, offers, mcp, monid })).map(key));
1967
+ const capped = await blockersOf(env, shape, {}, { capped: true, capUsd: body.maxCostUsd, boxes: boxOffers, computerReady, shellOf, offers, mcp, monid, decisionPrice });
1664
1968
  // A model with no price (`unpriced`) is a setting this host fixes (AGENT_MODEL_PRICE): a warning, as it is; the
1665
- // agent saves and updates, and only a run under the cap is refused (409). A tool's pick a cap rules out refuses it.
1969
+ // agent saves and updates, and only a run under the cap is refused (409). So is a cap below what the model needs for
1970
+ // one more step and an answer (`short`): the agent saves, and its runs wrap up at their first tool call. A tool's
1971
+ // pick a cap rules out refuses it.
1666
1972
  const added = capped.filter((b) => !plain.has(key(b)));
1667
- blockers.push(...added.filter((b) => b.unpriced));
1668
- blockers.push(...added.filter((b) => !b.unpriced).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
1973
+ blockers.push(...added.filter((b) => b.unpriced || b.short));
1974
+ blockers.push(...added.filter((b) => !b.unpriced && !b.short).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
1669
1975
  }
1670
1976
  const never = blockers.filter((b) => !b.host);
1671
1977
  if (never.length)
1672
1978
  throw invalid(never.map(issueOf));
1673
- return blockers.map(issueOf);
1979
+ const mcpPin = listing.pin();
1980
+ return { warnings: [...blockers.map(issueOf), ...usage], stamp: { ...(mcpPin ? { mcpPin } : {}), ...(monid ? { monidPin: monid } : {}) } };
1981
+ }
1982
+ /** An agentic `revision`'s monid pin (monid.ts pinMonid) and a warning per endpoint priced by usage; a grant that
1983
+ * cannot be pinned refuses the save (422). Undefined when it grants none. */
1984
+ async function monidPinOf(revision, previous) {
1985
+ if (revision.kind !== "agentic")
1986
+ return undefined;
1987
+ const tools = revision.body.tools ?? [];
1988
+ const send = await checkFetch("monid");
1989
+ const before = previous?.kind === "agentic" ? { grants: previous.body.tools ?? [], pin: previous.monidPin } : undefined;
1990
+ // The key as the server reads it (env: what it was started with, its handed secrets and its saved keys).
1991
+ const pinned = await pinMonid(tools, { key: env[MONID_KEY_ENV]?.trim(), fetch: send ?? (async () => { throw new Error("no fake of monid's API under faux"); }), signal: stopping.signal, ...(before ? { previous: before } : {}) });
1992
+ if (pinned && "refused" in pinned)
1993
+ throw invalid(pinned.refused.map(({ tool, message }) => ({ field: tools.includes(tool) ? `definition.tools[${tools.indexOf(tool)}]` : "definition.tools", reason: "not_an_option", message })));
1994
+ return pinned && { monid: pinned.pin, warnings: pinned.warnings.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: PRICED_BY_USAGE, message })) };
1674
1995
  }
1675
1996
  /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
1676
1997
  * that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
1677
1998
  * tool the box refuses (browser) keeps the runner. */
1678
- async function createAgentOf(body) {
1999
+ async function createAgentOf(body, template) {
1679
2000
  let warnings = [];
1680
2001
  const definition = checkDefinitionBody(body);
1681
2002
  const named = Array.isArray(definition.definition.tools) ? definition.definition.tools : [];
1682
2003
  const fresh = named.some((tool) => typeof tool === "string" && toolOf(tool)?.runnerOnly) ? { reason: "" } : newAgentPlace(boxOffers);
1683
- const entry = await agents.create(definition, async (revision) => void (warnings = await saveable(revision)), "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined);
2004
+ const entry = await agents.create(definition, async (revision) => {
2005
+ const saved = await saveable(revision);
2006
+ warnings = saved.warnings;
2007
+ return saved.stamp;
2008
+ }, "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined, template);
1684
2009
  return { entry, warnings };
1685
2010
  }
2011
+ /** A replay's ports for agent `entry` (runner/promotion.ts askReplay, replayView): its learning folder where this server
2012
+ * reads it, cut of the host's secrets as the learning reads cut them, and a replay run's launch made as a run's start
2013
+ * makes one now (prepareLaunch: the agent's current revision, model, plane and learning start). */
2014
+ const replayAskOf = (entry) => ({
2015
+ store, agentId: entry.agent.id, context: ctx, log: (line) => void log?.(line),
2016
+ folder: () => learningFolderOf(data, entry.agent.id), shown: () => learningShown(entry.agent.id),
2017
+ launchOf: async (input) => {
2018
+ const { launch, revision } = await prepareLaunch(startDeps, entry, { input });
2019
+ return { launch, revisionId: revision.id };
2020
+ },
2021
+ });
2022
+ /** `act`, its ReplayRefused answered as the API's: 404 not_found, or 409 replay_conflict, in its words. */
2023
+ const replayAsked = async (act) => {
2024
+ try {
2025
+ return await act();
2026
+ }
2027
+ catch (error) {
2028
+ if (error instanceof ReplayRefused)
2029
+ throw new ApiError(error.kind === "missing" ? "not_found" : "replay_conflict", error.message);
2030
+ throw error;
2031
+ }
2032
+ };
1686
2033
  /** Agent `source`'s learned workflow `raw` made into a workflow agent of its own, as POST /agents makes one
1687
2034
  * (createAgentOf: the definition's checks, the workflow's validation and what this host refuses of it). Only an active
1688
2035
  * one, checked again as a restore checks it (learning-routes.ts promotable). Its revision is a workflow revision of the
@@ -1709,7 +2056,6 @@ async function startHolding(options, data, checked, stops) {
1709
2056
  ...(policy.toolSettings ? { tool_settings: policy.toolSettings } : {}),
1710
2057
  ...(policy.approvals === "never" ? { approvals: "never" } : {}),
1711
2058
  ...(policy.maxCostUsd !== undefined ? { max_cost_usd: policy.maxCostUsd } : {}),
1712
- ...(policy.capMode !== undefined ? { cap_mode: policy.capMode } : {}),
1713
2059
  });
1714
2060
  const note = `Made from the learned workflow ${learned.name} of agent ${id}.`;
1715
2061
  // Another promotion (or a create) may take the id between the read and the write: the next one is tried.
@@ -1731,22 +2077,32 @@ async function startHolding(options, data, checked, stops) {
1731
2077
  }
1732
2078
  /** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
1733
2079
  * servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
1734
- * agent made as POST /agents makes one, its MCP tools at the owner's own settings save those granted, set to allow (a
1735
- * deny the owner set on this server stays, with a warning), its body held to POST /agents' limit (413), on the first harness of its list this server runs and the model packageModel
2080
+ * agent made as POST /agents makes one, granted the MCP tools the owner ticked (grants) alone, with no permission written
2081
+ * (each call follows this server's tool settings: a write asks unless the owner allowed it there or approvals never; a deny the owner set on this server stays,
2082
+ * with a warning): a tool left unticked is not the agent's, under any approvals, its body held to POST /agents' limit (413), on the first harness of its list this server runs and the model packageModel
1736
2083
  * picks, then each trigger on it as POST /triggers makes one. A trigger refused undoes the apply: the triggers made
1737
2084
  * before it are deleted and the agent is archived (an agent store keeps every agent), and the refusal is the answer, a 422's fields under `triggers.<i>`; a
1738
2085
  * github trigger GitHub is not connected for is skipped instead, with a warning there, and one made is said there. A webhook
1739
2086
  * trigger's secret is not in the answer (the Idempotency-Key record would keep it): POST /triggers/{id}/secret makes one. */
1740
- async function applyTemplate(pkg, body) {
1741
- const { parameters, grants, model: override, approvals } = applyBodyOf(pkg, body);
1742
- const missing = pkg.secrets.filter((name) => !secret(name, storedKeys));
1743
- const saved = pkg.mcp.filter((need) => mcpMeta.has(need.server));
1744
- const unsaved = pkg.mcp.filter((need) => !saved.includes(need));
2087
+ async function applyTemplate(template, body) {
2088
+ const { parameters, grants: asked, servers: picks, model: override, choice, approvals } = applyBodyOf(template, body);
2089
+ // A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made.
2090
+ const missing = [...new Set([...template.secrets, ...(choice?.secrets ?? [])])].filter((name) => !secret(name, storedKeys));
2091
+ // Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
2092
+ // one: several and no pick is a 422); the package's
2093
+ // tool names, mcp:<toolkit>/<tool>, read as that server's from here on (templates.ts onServers).
2094
+ const mapped = serversFor(template, [...mcpMeta].map(([name, meta]) => ({ name, ...meta.source })), picks);
2095
+ const servers = Object.fromEntries(mapped.flatMap(({ need, server }) => (server ? [[need.toolkit, server]] : [])));
2096
+ const pkg = onServers(template, servers);
2097
+ const saved = mapped.flatMap(({ need, server }) => (server ? [{ ...need, server }] : []));
2098
+ const unsaved = mapped.filter(({ server }) => !server).map(({ need }) => need);
2099
+ // A grant of a need with no server here grants nothing: dropped before the names move, so it never reads as a tool
2100
+ // of a saved server that happens to be named as its toolkit.
2101
+ const grants = asked.filter((tool) => Object.hasOwn(servers, mcpToolOf(tool)?.server ?? "")).map((tool) => onServerName(tool, servers));
1745
2102
  const needed = unsaved.filter((need) => need.required);
1746
2103
  if (missing.length || needed.length) {
1747
2104
  const fix = "Add it in Settings → Model keys or Settings → Tool keys, or set it where AgentRun starts, then apply the template again.";
1748
- const server = "Add it in Settings → MCP servers, under that name, then apply the template again.";
1749
- throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `the MCP server ${need.server}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server.`, fix: server }))] });
2105
+ throw new ApiError("agent_not_runnable", `The ${pkg.name} template needs ${[...missing, ...needed.map((need) => `a ${need.source} MCP server of the toolkit ${need.toolkit}`)].join(" and ")}, which this server does not have. Nothing was created.`, { fields: [...missing.map((name) => ({ field: `secrets.${name}`, reason: NOT_SET_UP, message: `${name} is not set on this server.`, fix })), ...needed.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}.`, fix: mcpSetUp(need) }))] });
1750
2106
  }
1751
2107
  // The package's computer list: the first entry this server meets now (templates.ts pickComputer), written as the
1752
2108
  // agent's computer; a fallback, or a shell tool that computer does not run, said under `computer`. A list none of
@@ -1756,9 +2112,20 @@ async function startHolding(options, data, checked, stops) {
1756
2112
  throw new ApiError("agent_not_runnable", pick.refused, { fields: [{ field: "computer", reason: NOT_SET_UP, message: pick.refused, fix: COMPUTER_FIX }] });
1757
2113
  const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
1758
2114
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
1759
- const skipped = unsaved.map((need) => ({ field: `mcp.${need.server}`, reason: NOT_SET_UP, message: `No MCP server ${need.server} is saved on this server, so the agent was made without its tools (${need.tools.join(", ")}). Save it in Settings → MCP servers and apply again to grant them.` }));
1760
- const harness = pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
1761
- const picked = override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
2115
+ const skipped = unsaved.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}, so the agent was made without its tools (${need.tools.join(", ")}).`, fix: mcpSetUp(need) }));
2116
+ // A model choice the owner picked is its model on its harness, or a refusal naming the model: never the tier's model
2117
+ // in its place. So is a package's `prefer` (packageModel's `refused`), outside a gateway.
2118
+ const unrunnable = choice && (await choiceUnrunnable(env, choice, offers.find((offer) => offer.id === choice.harness)));
2119
+ if (choice && unrunnable) {
2120
+ const message = `The ${pkg.name} template's choice ${choice.label} runs ${choice.model} on ${choice.harness}, which this server can't run: ${unrunnable.replace(/\.$/, "")}. Nothing was created.`;
2121
+ throw new ApiError("agent_not_runnable", message, { fields: [{ field: "overrides.choice", reason: NOT_SET_UP, message, fix: "Apply with the default or another choice, or, where the model only wants a key, add it in Settings → Model keys." }] });
2122
+ }
2123
+ const harness = choice ? choice.harness : pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
2124
+ const picked = choice ? { model: choice.model } : override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
2125
+ if ("refused" in picked && picked.refused) {
2126
+ const message = `The ${pkg.name} template prefers ${pkg.model?.prefer}, which this server can't run on ${harness ?? DEFAULT_HARNESS}: ${picked.refused.why}. Nothing was created.`;
2127
+ throw new ApiError("agent_not_runnable", message, { fields: [{ field: "model", reason: NOT_SET_UP, message, fix: picked.refused.fix }] });
2128
+ }
1762
2129
  const model = picked.model;
1763
2130
  // Which model the agent got, where it is not the package's: a note, never a lack. The agent runs; only the package's
1764
2131
  // choice was not an option here (not_set_up_here would read as a run refused until the host has something).
@@ -1769,21 +2136,23 @@ async function startHolding(options, data, checked, stops) {
1769
2136
  // A grant never lifts a deny the owner set on this server: that tool keeps it, and the answer says so.
1770
2137
  const server = settings.get();
1771
2138
  const denied = grants.filter((tool) => { const set = permissionFrom(tool, server); return set.from === "server" && set.permission === "deny"; });
1772
- const kept = denied.map((tool) => ({ field: `grants.${tool}`, reason: "not_allowed", message: `${tool} is denied on this server (Settings → Tools), so the agent was not allowed it: its runs are refused it until the owner changes that setting.` }));
2139
+ const kept = denied.map((tool) => ({ field: `grants.${tool}`, reason: "not_allowed", message: `${tool} is denied on this server (Settings → Tools), so the agent's runs are refused it until the owner changes that setting.` }));
1773
2140
  // The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
1774
2141
  // never), else ask. Deny and pins hold either way.
1775
2142
  const chosenApprovals = approvals ?? pkg.approvals;
1776
- const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), ...(tiers.modelTiers ? { modelTiers: tiers.modelTiers } : {}), mcp: saved, defaultTools, grants: grants.filter((tool) => !denied.includes(tool)), ...(chosenApprovals ? { approvals: chosenApprovals } : {}), ...(pick ? { computer: pick } : {}) }, templateDeps);
2143
+ const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), ...(tiers.modelTiers ? { modelTiers: tiers.modelTiers } : {}), mcp: saved, defaultTools, grants, ...(chosenApprovals ? { approvals: chosenApprovals } : {}), ...(pick ? { computer: pick } : {}) }, templateDeps);
1777
2144
  // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
1778
- // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
1779
- const refusedTriggers = madeTriggerIssues(made.triggers, Date.now());
2145
+ // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>). "Passed"
2146
+ // by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
2147
+ const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema);
1780
2148
  if (refusedTriggers.length)
1781
2149
  throw invalid(refusedTriggers);
1782
2150
  // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
1783
2151
  for (const one of [made.agent, ...made.triggers])
1784
2152
  if (Buffer.byteLength(JSON.stringify(one)) > MAX_BODY)
1785
2153
  throw new ApiError("payload_too_large", `the ${pkg.name} template, its parameters filled in, makes a body over ${MAX_BODY} bytes`, { details: { limit: "max_body_bytes" } });
1786
- const { entry, warnings } = await createAgentOf(made.agent);
2154
+ // The agent keeps where it came from (its first revision's package): the package's id, version and, imported, its SHA.
2155
+ const { entry, warnings } = await createAgentOf(made.agent, { id: pkg.id, version: pkg.version, sha: pkg.origin?.sha ?? null });
1787
2156
  const ids = [];
1788
2157
  // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
1789
2158
  // /triggers hands back its own, so the owner can give it to the sender.
@@ -1826,10 +2195,12 @@ async function startHolding(options, data, checked, stops) {
1826
2195
  }
1827
2196
  // A pinned send whose destination parameter was not given is denied, never let go anywhere: said, by its gate name.
1828
2197
  const unpinned = made.unpinned.map(({ tool, parameters: named }) => ({ field: `pins.${tool}`, reason: NOT_SET_UP, message: `${tool}'s arguments are fixed by ${named.map((one) => `the ${one} parameter`).join(" and ")}, which was not given, so the agent was made with ${tool} set to deny: it can't call it at all. Apply again with ${named.join(" and ")} set to let it.` }));
1829
- // A GitHub tool the package grants that an installation of Connect GitHub's App does not hold the permission for (read
1830
- // from GitHub, never assumed), where the github MCP server runs on the App's tokens: said now, before a run's first
1831
- // call is refused; or that the check could not be made (template-github-permissions.ts).
1832
- const appShort = await appPermissionWarnings({ name: pkg.name, mcp: saved }, (server) => mcpMeta.get(server)?.auth === "github_app", () => githubConnect.installationPermissions(stopping.signal));
2198
+ // A GitHub tool the owner granted (ticked) that an installation of Connect GitHub's App does not hold the permission
2199
+ // for (read from GitHub, never assumed), where the github MCP server runs on the App's tokens: said now, before a run's
2200
+ // first call is refused; or that the check could not be made (template-github-permissions.ts). An unticked tool is
2201
+ // not the agent's, so nothing is said of it.
2202
+ const ticked = saved.map((need) => ({ ...need, tools: need.tools.filter((tool) => grants.includes(mcpToolName(need.server, tool))) }));
2203
+ const appShort = await appPermissionWarnings({ name: pkg.name, mcp: ticked }, (server) => mcpMeta.get(server)?.auth === "github_app", () => githubConnect.installationPermissions(stopping.signal));
1833
2204
  // A webhook trigger's secret is in no apply answer: each one's warning sends the person to the console for it.
1834
2205
  const hooks = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "webhook" ? [templateTriggerSecret(i)] : []));
1835
2206
  // Each github trigger: what it runs on, when made (a note, never a lack); skipped, what to do about it.
@@ -1839,17 +2210,20 @@ async function startHolding(options, data, checked, stops) {
1839
2210
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
1840
2211
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
1841
2212
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
1842
- const applied = { template: pkg.name, version: pkg.version, agent_id: entry.agent.id, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
2213
+ // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
2214
+ const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
2215
+ const applied = { template: pkg.id, version: pkg.version, agent_id: entry.agent.id, servers: used, trigger_ids: ids, ...templateWebhookSecrets([...minted.keys()], new Date().toISOString()), warnings: [...skipped, ...kept, ...modelWarnings, ...computerWarnings, ...unpinned, ...warnings, ...hooks, ...githubTriggers, ...appShort] };
1843
2216
  return { applied, minted };
1844
2217
  }
1845
- /** A run create's issues told from the input this server checks (explain.ts): an agentic run's `{content: string}`,
1846
- * with the documented run bodies; a workflow run's its workflow's input schema, never the agentic example. Each value
2218
+ /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
2219
+ * (`{content: string}` with none), with the documented run bodies;a workflow run's its workflow's input schema, never the agentic example. Each value
1847
2220
  * suggested must pass this route's own checks of the body, the workflow's input check among them. */
1848
2221
  async function explainRun(issues, body, revision) {
1849
2222
  const dsl = revision?.kind === "workflow" ? await import("@parcha/agentrun-dsl") : undefined;
1850
2223
  const workflow = dsl && revision?.kind === "workflow" ? revision.body.workflow : undefined;
1851
2224
  const declared = workflow?.input?.schemaId === undefined ? undefined : workflow.schemas[workflow.input.schemaId];
1852
- const input = !dsl ? DEFAULT_INPUT_SCHEMA : declared ? dsl.resolveSchemaForWorkflow(workflow, declared) : { type: "object" };
2225
+ const typed = revision?.kind === "agentic" ? inputSchemaOf(revision.body.inputSchema) : DEFAULT_INPUT_SCHEMA;
2226
+ const input = !dsl ? typed : declared ? dsl.resolveSchemaForWorkflow(workflow, declared) : { type: "object" };
1853
2227
  const base = deref(openapi, { $ref: "#/components/schemas/RunCreate" }) ?? {};
1854
2228
  const schema = { ...base, properties: { ...base.properties, input } };
1855
2229
  const check = (sent) => {
@@ -1857,14 +2231,15 @@ async function startHolding(options, data, checked, stops) {
1857
2231
  const issues = runBodyIssues(value);
1858
2232
  if (!revision || !isObject(value.input))
1859
2233
  return issues;
1860
- return [...issues, ...(dsl ? workflowInputIssues(dsl.validateWorkflow, revision, value.input) : inputIssues(value.input, DEFAULT_INPUT_SCHEMA))];
2234
+ return [...issues, ...(dsl ? workflowInputIssues(dsl.validateWorkflow, revision, value.input) : inputIssues(value.input, typed))];
1861
2235
  };
1862
2236
  return explain(issues, openapi, schema, { examples: dsl ? [] : examplesOf("createRun"), body, check });
1863
2237
  }
1864
- /** A run's input: an agentic run's `{content: string}`, a workflow run's what its workflow's input schema takes. */
2238
+ /** A run's input: an agentic run's what its revision's input schema in force takes (`{content: string}` with none), a
2239
+ * workflow run's what its workflow's input schema takes. */
1865
2240
  async function inputIssuesOf(revision, input) {
1866
2241
  if (revision.kind === "agentic")
1867
- return inputIssues(input, DEFAULT_INPUT_SCHEMA);
2242
+ return inputIssues(input, inputSchemaOf(revision.body.inputSchema));
1868
2243
  const { validateWorkflow } = await import("@parcha/agentrun-dsl");
1869
2244
  return workflowInputIssues(validateWorkflow, revision, input);
1870
2245
  }
@@ -1904,7 +2279,7 @@ async function startHolding(options, data, checked, stops) {
1904
2279
  const handed = mcpAuthOf(mcp_auth, issues);
1905
2280
  const auth = {};
1906
2281
  for (const [server, headers] of Object.entries(handed ?? {})) {
1907
- const row = await store.mcp.server(server);
2282
+ const row = await getMcpServer(store, server);
1908
2283
  if (row?.auth !== "per_run")
1909
2284
  issues.push({ field: `mcp_auth.${server}`, reason: "not_an_option", message: row ? `The MCP server ${server} keeps its own credential (auth ${row.auth}): only a per_run server takes one from a run.` : `No MCP server ${server} is saved here.` });
1910
2285
  else
@@ -1917,9 +2292,7 @@ async function startHolding(options, data, checked, stops) {
1917
2292
  return { body: rest, sealer };
1918
2293
  }
1919
2294
  async function createRun(req, agentId) {
1920
- const entry = await needAgent(agentId);
1921
- if (entry.agent.archivedAt)
1922
- throw new ApiError("agent_not_runnable", `The agent ${agentId} is archived: unarchive it to run it.`, { details: { archived_at: new Date(entry.agent.archivedAt).toISOString() } });
2295
+ const entry = await needRunnableAgent(agentId);
1923
2296
  const { body, sealer } = handedMcpAuth(await bodyOf(req));
1924
2297
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
1925
2298
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
@@ -1943,6 +2316,8 @@ async function startHolding(options, data, checked, stops) {
1943
2316
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
1944
2317
  async function createInlineRun(req) {
1945
2318
  const { body, sealer } = handedMcpAuth(await bodyOf(req));
2319
+ if (isObject(body.definition) && body.definition.native !== undefined)
2320
+ throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine; an inline definition cannot create one.");
1946
2321
  const { external, definition, skills, note, revision: pinned, ...run } = body;
1947
2322
  const given = { definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) };
1948
2323
  const issues = [
@@ -1956,16 +2331,23 @@ async function startHolding(options, data, checked, stops) {
1956
2331
  if (issues.length)
1957
2332
  throw invalid(issues);
1958
2333
  const checked = checkDefinitionBody(given);
1959
- const revision = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
1960
- // Refused where POST /agents refuses the definition (one this host can never run); what this host still lacks for it
1961
- // is the run's own refusal (prepareLaunch's runnable), as for a run of a stored agent.
1962
- await saveable(revision);
2334
+ const made = makeRevision(checked.definition, checked.skills ?? {}, checked.note);
2335
+ // A version's first run is its save: refused where POST /agents refuses the definition (one this host can never run),
2336
+ // its MCP tools pinned as a save pins them (a server down keeps the agent's current pin when this version grants nothing
2337
+ // new from it). A version already stored is a run of its revision, as a run of a stored agent is: no save, nothing
2338
+ // listed here, its pin as stored (one stored with no pin is pinned at this run, StartDeps.pinFirst). What this host
2339
+ // still lacks for either is the run's own refusal (prepareLaunch's runnable).
1963
2340
  const ref = external;
2341
+ const mapped = await store.agents.byExternal(externalKey(ref));
2342
+ const stored = mapped ? await store.agents.externalRevision(mapped.id, String(ref.version)) : undefined;
2343
+ const current = !stored && mapped?.currentRevision ? await store.agents.revision(mapped.currentRevision) : undefined;
2344
+ const revision = stored ? made : { ...made, ...(await saveable(made, current)).stamp };
1964
2345
  const inline = {
1965
2346
  external: { source: ref.source, kind: ref.kind, id: ref.id, version: String(ref.version) },
1966
2347
  name: checked.definition.name,
1967
2348
  description: typeof checked.definition.description === "string" ? checked.definition.description : null,
1968
2349
  revision,
2350
+ ...(stored ? { stored } : {}),
1969
2351
  };
1970
2352
  return idempotent(req, "/runs", body, async (origin) => {
1971
2353
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
@@ -2031,7 +2413,7 @@ async function startHolding(options, data, checked, stops) {
2031
2413
  }
2032
2414
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
2033
2415
  function runBodyIssues(body) {
2034
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "learning", "archil_disk", "repo", "hold", "hold_minutes"]);
2416
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes"]);
2035
2417
  issues.push(...holdIssues(body));
2036
2418
  if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
2037
2419
  issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
@@ -2051,10 +2433,10 @@ async function startHolding(options, data, checked, stops) {
2051
2433
  issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
2052
2434
  if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0 && Number.isFinite(body.max_cost_usd)))
2053
2435
  issues.push({ field: "max_cost_usd", reason: "wrong_type", message: "max_cost_usd is a number above 0" });
2054
- if (body.cap_mode !== undefined && !CAP_MODES.includes(body.cap_mode))
2055
- issues.push({ field: "cap_mode", reason: "not_an_option", message: `cap_mode is one of ${CAP_MODES.join(", ")}` });
2056
2436
  if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
2057
2437
  issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
2438
+ if (body.workflow_first !== undefined && typeof body.workflow_first !== "boolean")
2439
+ issues.push({ field: "workflow_first", reason: "wrong_type", message: "workflow_first is true or false" });
2058
2440
  if (body.learning !== undefined && body.learning !== RUN_LEARNING_USE)
2059
2441
  issues.push({ field: "learning", reason: "not_an_option", message: `learning is "${RUN_LEARNING_USE}" (the run starts from what its agent learned and keeps nothing), or absent (its agent's own)` });
2060
2442
  return issues;
@@ -2096,11 +2478,16 @@ async function startHolding(options, data, checked, stops) {
2096
2478
  if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
2097
2479
  throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
2098
2480
  const limit = asked === null ? PAGE_ROWS : Number(asked);
2481
+ // `calls=whole`: each call's arguments and its output's head too (tool_input, tool_result_text), for a grader.
2482
+ const shape = url.searchParams.get("calls");
2483
+ if (shape !== null && shape !== "whole")
2484
+ throw new ApiError("bad_request", "calls is whole, or absent");
2485
+ const calls = shape === "whole";
2099
2486
  // The run's page from the store (runTimelines): run_id/status/state/reset/rows/drop/next_after/unchanged/has_more/final/
2100
2487
  // cost, byte-identical to the old live page. TODO(learning-row freshness): a learning row approved or retired since the
2101
2488
  // journal wrote it reads its journal state here (store-view owns the fresh learning view); folded in with learning-1.
2102
2489
  if (!String(req.headers.accept ?? "").includes("text/event-stream")) {
2103
- const page = await timelines.page(store, runId, after, waitMs, limit);
2490
+ const page = await timelines.page(store, runId, after, waitMs, limit, calls);
2104
2491
  return send(res, 200, { ...page, poll_after_ms: page.final || page.has_more ? 0 : 1000 });
2105
2492
  }
2106
2493
  const last = req.headers["last-event-id"];
@@ -2124,7 +2511,7 @@ async function startHolding(options, data, checked, stops) {
2124
2511
  });
2125
2512
  try {
2126
2513
  for (let first = true; open; first = false) {
2127
- const page = await timelines.page(store, runId, cursor, 0, limit);
2514
+ const page = await timelines.page(store, runId, cursor, 0, limit, calls);
2128
2515
  if (!open)
2129
2516
  break;
2130
2517
  if (first || !page.unchanged || page.final)
@@ -2502,8 +2889,10 @@ async function startHolding(options, data, checked, stops) {
2502
2889
  // Archil on or off, or saving a key, changes them. So does a shell on the runner (bash on Archil's serverless exec
2503
2890
  // in Mode 2): where there is one, the document is made again with it (cheap), its tools available with no box.
2504
2891
  const runnerShell = shellTools(await shellOf({ kind: "none" }));
2892
+ await planNow();
2505
2893
  const answer = forCaller(runnerShell.size ? compose(runnerShell) : caps, byOwnerSession(req));
2506
- return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()) } });
2894
+ // features.triggers.public_url: whether Composio (or any sender) has a public address to reach, never the address.
2895
+ return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
2507
2896
  }
2508
2897
  if (found.name === "getOpenapi")
2509
2898
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
@@ -2515,7 +2904,7 @@ async function startHolding(options, data, checked, stops) {
2515
2904
  // read (push-handler.ts).
2516
2905
  if (found.name === "receiveHook") {
2517
2906
  // A body cut at its cap or its time is answered, then its socket closed: never read to its end.
2518
- const answer = await receivePush({ adapters, hooked: (id) => triggers.hookSource(id), ...(options.hookBodyMs !== undefined ? { bodyMs: options.hookBodyMs } : {}), ignored: (id, eventId) => triggers.ignored(id, eventId), listening: (kind) => triggers.listening(kind), notice: async (adapterId, event, body) => (adapterId === "github" && event === "installation" ? githubConnect.installationEvent(body, (detail) => triggers.turnOff("github", detail)) : undefined), receive: (id, eventId, payload, attrs) => triggers.receive(id, eventId, payload, attrs), scoped: (kind, scope) => triggers.scoped(kind, scope), setting: (adapterId, scope, field) => triggerSettings.get(adapterId)?.get(scope, field), refused: authFailed, say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)) }, req, /^\/hooks\/([^/]+)$/.exec(path)[1]);
2907
+ const answer = await receivePush({ adapters, hooked: (id) => triggers.hookSource(id), ...(options.hookBodyMs !== undefined ? { bodyMs: options.hookBodyMs } : {}), ignored: (id, eventId) => triggers.ignored(id, eventId), listening: (kind) => triggers.listening(kind), notice: async (adapterId, event, body) => (adapterId === "github" && event === "installation" ? githubConnect.installationEvent(body, (detail) => triggers.turnOff("github", detail)) : undefined), receive: (id, eventId, payload, attrs) => triggers.receive(id, eventId, payload, attrs), scoped: (kind, scope) => triggers.scoped(kind, scope), setting: (adapterId, scope, field) => triggerSettings.get(adapterId)?.get(scope, field), refused: authFailed, say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)) }, req, ...((([, segment, sub]) => [segment, sub])(/^\/hooks\/([^/]+)(?:\/([^/]+))?$/.exec(path))));
2519
2908
  return send(res, answer.status, answer.body, answer.headers ?? {});
2520
2909
  }
2521
2910
  // A paired computer's driver trading its pairing code for its token: the code is its credential (computer-attach.ts),
@@ -2584,6 +2973,12 @@ async function startHolding(options, data, checked, stops) {
2584
2973
  authFailed(`/v2${path}`, "promote_without_session");
2585
2974
  throw new ApiError("forbidden", owner ? "Making a learned workflow an agent takes the owner's password sign-in in the console, never a token." : "Making a learned workflow an agent takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
2586
2975
  }
2976
+ // A replay its owner starts runs the agent's graded inputs again at its cost, and may promote a revision that then
2977
+ // serves first: the same session as making one an agent.
2978
+ if (found.name === "startLearnedWorkflowReplay" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
2979
+ authFailed(`/v2${path}`, "replay_without_session");
2980
+ throw new ApiError("forbidden", owner ? "Replaying a learned workflow's revision takes the owner's password sign-in in the console, never a token." : "Replaying a learned workflow's revision takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
2981
+ }
2587
2982
  // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
2588
2983
  // approving a note is (never a token a run, an MCP client or a script may hold).
2589
2984
  if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
@@ -2624,17 +3019,130 @@ async function startHolding(options, data, checked, stops) {
2624
3019
  }
2625
3020
  secretSeen = checked.seen;
2626
3021
  }
3022
+ // Connector credentials have no authority over the ordinary API. Enrollment is a one-use owner grant;
3023
+ // subsequent calls are restricted to one connector and its explicitly imported target allowlist.
3024
+ if (found.name === "registerRemoteConnector") {
3025
+ const credential = String(req.headers.authorization ?? "").replace(/^Bearer /, "");
3026
+ return send(res, 200, await new RemoteConnectors(store).register(credential, await bodyOf(req)));
3027
+ }
3028
+ if (found.name === "revokeRemoteConnector" && String(req.headers.authorization ?? "").startsWith("Bearer ar_connector_")) {
3029
+ const connectorId = decodeURIComponent(found.pattern.exec(path)[1]);
3030
+ const broker = new RemoteConnectors(store);
3031
+ await broker.authenticate(connectorId, String(req.headers.authorization).slice(7));
3032
+ return send(res, 200, await broker.revoke(connectorId));
3033
+ }
3034
+ if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand"].includes(found.name)) {
3035
+ const parts = found.pattern.exec(path);
3036
+ const connectorId = decodeURIComponent(parts[1]);
3037
+ const broker = new RemoteConnectors(store);
3038
+ await broker.authenticate(connectorId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
3039
+ // History pages and command completions have separate bounded contracts; other JSON keeps MAX_BODY.
3040
+ const limit = found.name === "importRemoteHistory" ? REMOTE_HISTORY_BODY_BYTES
3041
+ : found.name === "completeRemoteCommand" ? REMOTE_COMPLETION_BODY_BYTES : MAX_BODY;
3042
+ const body = await bodyOf(req, limit);
3043
+ if (found.name === "importRemoteTarget")
3044
+ return send(res, 200, await broker.importTarget(connectorId, body));
3045
+ if (found.name === "importRemoteHistory")
3046
+ return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [token, String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
3047
+ if (found.name === "pollRemoteConnector")
3048
+ return send(res, 200, await broker.poll(connectorId, body));
3049
+ const commandId = decodeURIComponent(parts[2]);
3050
+ return send(res, 200, found.name === "remoteCommandEvents" ? await broker.events(connectorId, commandId, body) : await broker.complete(connectorId, commandId, body));
3051
+ }
3052
+ if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
3053
+ const runId = decodeURIComponent(found.pattern.exec(path)[1]);
3054
+ const sdk = new SdkRuns(store, data, token, serverSecrets);
3055
+ await sdk.authenticate(runId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
3056
+ if (found.name === "sdkRunEvents")
3057
+ return send(res, 200, await sdk.events(runId, await bodyOf(req)));
3058
+ if (found.name === "completeSdkRun")
3059
+ return send(res, 200, await sdk.complete(runId, await bodyOf(req)));
3060
+ return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
3061
+ }
2627
3062
  if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
2628
3063
  authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
2629
3064
  throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
2630
3065
  }
2631
3066
  if (found.capability)
2632
3067
  throw unsupported(found.capability, UNSUPPORTED[found.capability]);
3068
+ if (["discoverNative", "connectNative"].includes(found.name) && (options.apiOnly || options.publicUrl || !isLoopback(host)))
3069
+ throw new ApiError("forbidden", "Native connections require AgentRun on the source machine, bound to loopback without a public URL. A hosted browser cannot discover your laptop.");
2633
3070
  const [, first, second] = found.pattern.exec(path);
2634
3071
  const id = first ? decodeURIComponent(first) : "";
2635
3072
  switch (found.name) {
3073
+ case "startSdkRun": {
3074
+ if (!req.headers["idempotency-key"])
3075
+ throw new ApiError("bad_request", "An SDK run requires Idempotency-Key so a retried start never duplicates execution.");
3076
+ const body = await bodyOf(req), entry = await needAgent(id);
3077
+ let gradeModel = gradeModelOf(env, options.gradeModel);
3078
+ if (!gradeModel && sdkOf(entry.revision?.body) && learnsOf(entry.revision.body.learning) && learning !== "off") {
3079
+ try {
3080
+ const chosen = await runModelRef(env, (await pinnedOf(entry, {})).revision);
3081
+ if (chosen)
3082
+ gradeModel = `${chosen.provider}/${chosen.modelId}`;
3083
+ }
3084
+ catch { }
3085
+ }
3086
+ const sdk = new SdkRuns(store, data, token, serverSecrets);
3087
+ const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, { ...startDeps, ...(gradeModel ? { gradeModel } : {}) }, origin, async (model) => {
3088
+ try {
3089
+ const route = await gradeRouteFor({ model, agentId: id }, env, sdkModelRoute);
3090
+ await route.provider.credential();
3091
+ }
3092
+ catch {
3093
+ throw new ApiError("agent_not_runnable", "Self-improving SDK runs need a working server model key and grading model. Configure Model keys or turn self-improving off.");
3094
+ }
3095
+ }, linkOrigin(req)) }));
3096
+ // Re-read the pinned receipt even on an in-memory replay: credentials saved since
3097
+ // the first response must still be withheld without reselecting a different seed.
3098
+ const receipt = await sdk.receipt(answer.body.run_id, linkOrigin(req));
3099
+ return send(res, answer.status, receipt, answer.headers);
3100
+ }
3101
+ case "getObservations": {
3102
+ const days = Number(url.searchParams.get("days") ?? 30);
3103
+ if (!Number.isInteger(days) || days < 1 || days > 31)
3104
+ throw new ApiError("input_invalid", "Choose an observation window from 1 to 31 days.");
3105
+ return send(res, 200, await new Observations(store).snapshot(days, url.searchParams.get("session_id") ?? undefined));
3106
+ }
3107
+ case "listRemoteConnectors": return send(res, 200, await new RemoteConnectors(store).list());
3108
+ case "enrollRemoteConnector": return send(res, 200, await new RemoteConnectors(store).enroll(await bodyOf(req)));
3109
+ case "revokeRemoteConnector": return send(res, 200, await new RemoteConnectors(store).revoke(id));
3110
+ case "discoverNative": {
3111
+ const body = await bodyOf(req);
3112
+ if (typeof body.project !== "string" || (body.runtime !== undefined && !isNativeRuntime(body.runtime)))
3113
+ throw new ApiError("input_invalid", "Choose the project directory on this source machine and a supported CLI runtime.");
3114
+ return send(res, 200, await discoverNative({ project: body.project, ...(body.runtime ? { runtime: body.runtime } : {}) }));
3115
+ }
3116
+ case "connectNative": {
3117
+ const entry = await connectNative(store, await bodyOf(req));
3118
+ return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), native: nativeOf(entry.revision?.body) });
3119
+ }
3120
+ case "getNative": {
3121
+ const entry = await needAgent(id);
3122
+ const native = nativeOf(entry.revision?.body);
3123
+ return send(res, 200, { native: native?.remote ? await new RemoteConnectors(store).status(native) : native ?? null });
3124
+ }
3125
+ case "verifyNative": {
3126
+ const before = await needAgent(id);
3127
+ if (!nativeOf(before.revision?.body)?.remote && (options.apiOnly || options.publicUrl || !isLoopback(host)))
3128
+ throw new ApiError("forbidden", "Local native verification must run on the source machine.");
3129
+ const entry = nativeOf(before.revision?.body)?.remote ? await verifyRemote(store, before) : await verifyConnection(store, before);
3130
+ return send(res, 200, { native: nativeOf(entry.revision?.body) });
3131
+ }
3132
+ case "disconnectNative": {
3133
+ const entry = await needAgent(id);
3134
+ const native = nativeOf(entry.revision?.body);
3135
+ if (!native)
3136
+ throw new ApiError("not_found", "This agent has no native connection.");
3137
+ const changed = await updateNative(store, entry, { ...native, connected: false });
3138
+ if (native.remote)
3139
+ await new RemoteConnectors(store).disconnectTarget(native);
3140
+ return send(res, 200, { native: nativeOf(changed.revision?.body) });
3141
+ }
2636
3142
  case "createAgent": {
2637
3143
  const body = await bodyOf(req);
3144
+ if (isObject(body.definition) && body.definition.native !== undefined)
3145
+ throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine.");
2638
3146
  const answer = await idempotent(req, "/agents", body, async () => {
2639
3147
  const { entry, warnings } = await createAgentOf(body);
2640
3148
  return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
@@ -2653,7 +3161,20 @@ async function startHolding(options, data, checked, stops) {
2653
3161
  // The tools its current revision grants, as capabilities list them, each with its provider for this agent.
2654
3162
  // A tool of bash's family the agent's computer gives no shell for reads unavailable (runShellOf).
2655
3163
  const revision = entry.revision;
2656
- const tools = revision ? agentTools(env, settings.get(), await toolingOf(revision), caps.tools.map((tool) => tool.name), await shellOfRevision(revision)) : [];
3164
+ const tooling = revision ? await toolingOf(revision) : undefined;
3165
+ // An MCP tool's effect, what "allow reads" reads: as the revision's pin marks it (pinnedEffect), the marks its runs
3166
+ // read. A revision saved before pins were made at save holds none until its first run, which pins its saved
3167
+ // server's listing then (pinFirst): so until then, that listing now (mcp-servers-store.ts).
3168
+ const pin = revision?.mcpPin ?? undefined;
3169
+ const listed = !pin && tooling?.tools.some((name) => mcpToolOf(name)) ? new Map((await store.mcp.servers()).map((row) => [row.name, (row.tools ?? [])])) : undefined;
3170
+ const effectOf = (name) => {
3171
+ if (pin)
3172
+ return pinnedEffect(pin, name);
3173
+ const parsed = mcpToolOf(name);
3174
+ const tool = parsed && listed?.get(parsed.server)?.find((one) => one.name === parsed.tool);
3175
+ return tool ? toolEffect(tool.annotations) : undefined;
3176
+ };
3177
+ const tools = revision && tooling ? agentTools(env, settings.get(), tooling, caps.tools.map((tool) => tool.name), await shellOfRevision(revision), effectOf) : [];
2657
3178
  return send(res, 200, { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), tools }, { etag: etagOf(entry) });
2658
3179
  }
2659
3180
  case "updateDefinition": {
@@ -2666,6 +3187,16 @@ async function startHolding(options, data, checked, stops) {
2666
3187
  // contract's is the definition itself, and takes the contract's preconditions: If-Match, and a version past the
2667
3188
  // current one.
2668
3189
  const contract = !("definition" in body);
3190
+ const nativeEdit = contract ? body.native : isObject(body.definition) ? body.definition.native : undefined;
3191
+ if (nativeEdit !== undefined && stable(nativeEdit) !== stable(nativeOf(entry.revision?.body)))
3192
+ throw new ApiError("input_invalid", "Native references are changed only through the native connection endpoints. Normal edits retain the existing reference.");
3193
+ // Check explicit native selectors before canonicalization (the ordinary default harness, pi, is not stored).
3194
+ const definition = contract ? body : body.definition;
3195
+ if (nativeOf(entry.revision?.body) && isObject(definition)) {
3196
+ const execution = nativeExecutionOverrides({ ...definition, native: nativeOf(entry.revision?.body) });
3197
+ if (execution.length)
3198
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
3199
+ }
2669
3200
  if (contract) {
2670
3201
  if (match === undefined)
2671
3202
  throw new ApiError("precondition_failed", "If-Match is required: the agent's ETag, as GET /agents/{agent_id} returned it.");
@@ -2675,7 +3206,12 @@ async function startHolding(options, data, checked, stops) {
2675
3206
  // The check above is a fast path; the store compares If-Match again inside the commit, so of two edits that read
2676
3207
  // the same revision exactly one lands.
2677
3208
  let warnings = [];
2678
- const check = async (revision) => void (warnings = await saveable(revision));
3209
+ const check = async (revision, on) => {
3210
+ // The pins of the revision this try builds on (commitAgent's read, a retry's newer one) carry what it kept.
3211
+ const saved = await saveable(revision, on);
3212
+ warnings = saved.warnings;
3213
+ return saved.stamp;
3214
+ };
2679
3215
  const edited = await agents.commit(entry, checkDefinitionBody(contract ? { definition: body } : body, { creating: false }), { check, contract, ...(match === undefined ? {} : { ifCurrent: entry.revision?.id ?? null }) });
2680
3216
  reconcileComputer(id);
2681
3217
  return send(res, 200, { ...agentView(edited, linkOrigin(req), await agentExtra(edited)), warnings }, { etag: etagOf(edited) });
@@ -2698,8 +3234,19 @@ async function startHolding(options, data, checked, stops) {
2698
3234
  const revision = body.revision;
2699
3235
  if (typeof revision !== "string" || !ID.test(revision))
2700
3236
  throw invalid([{ field: "revision", reason: revision === undefined ? "missing" : "wrong_type", message: "revision is a revision id of this agent" }]);
2701
- if (!(await agents.revision(id, revision)))
3237
+ const candidate = await agents.revision(id, revision);
3238
+ if (!candidate)
2702
3239
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
3240
+ if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
3241
+ throw new ApiError("input_invalid", "This revision changes the native connection. Reconnect or verify through the native connection controls; ordinary revision restore cannot change its source or connection state.");
3242
+ if (nativeOf(candidate.revision.body)) {
3243
+ const overrides = nativeModelOverrides(candidate.revision.body);
3244
+ if (overrides.length)
3245
+ throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
3246
+ const execution = nativeExecutionOverrides(candidate.revision.body);
3247
+ if (execution.length)
3248
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
3249
+ }
2703
3250
  const moved = await agents.setCurrent(entry, revision);
2704
3251
  reconcileComputer(id);
2705
3252
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
@@ -2827,17 +3374,53 @@ async function startHolding(options, data, checked, stops) {
2827
3374
  // The owner's answer to a tool call that waits for approval (tool-gate.ts): the first answer wins.
2828
3375
  const run = await needRun(id);
2829
3376
  const body = await bodyOf(req);
2830
- const issues = Object.keys(body).filter((k) => k !== "decision" && k !== "note").map((k) => ({ field: k, reason: "not_allowed", message: `The body keeps no field ${k}.` }));
3377
+ const issues = Object.keys(body).filter((k) => k !== "decision" && k !== "note" && k !== "confirm_destructive").map((k) => ({ field: k, reason: "not_allowed", message: `The body keeps no field ${k}.` }));
3378
+ if (body.confirm_destructive !== undefined && body.confirm_destructive !== true)
3379
+ issues.push({ field: "confirm_destructive", reason: "wrong_type", message: "confirm_destructive is true when sent: the second confirm of a destructive call's allow" });
2831
3380
  if (body.decision !== "allow" && body.decision !== "deny")
2832
3381
  issues.push({ field: "decision", reason: body.decision === undefined ? "missing" : "not_an_option", message: "decision is allow or deny" });
2833
3382
  if (body.note !== undefined && (typeof body.note !== "string" || body.note.length > 2000))
2834
3383
  issues.push({ field: "note", reason: "wrong_type", message: "note is a string of at most 2000 characters" });
2835
3384
  if (issues.length)
2836
3385
  throw invalid(issues);
2837
- await approve(store, run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined);
3386
+ await approve(store, run, decodeURIComponent(second), body.decision, typeof body.note === "string" && body.note.trim() ? body.note.trim() : undefined, body.confirm_destructive === true);
2838
3387
  res.writeHead(204, { "cache-control": "no-store", "x-content-type-options": "nosniff" });
2839
3388
  return void res.end();
2840
3389
  }
3390
+ case "gradeRun": {
3391
+ const row = ID.test(id) ? await store.runs.get(id) : undefined;
3392
+ if (!row)
3393
+ throw new ApiError("not_found", `no run ${id}`);
3394
+ const body = await bodyOf(req);
3395
+ const extra = unknownFields(body, ["correct", "expected", "source", "label"]);
3396
+ if (extra.length)
3397
+ throw invalid(extra);
3398
+ if (typeof body.correct !== "boolean")
3399
+ throw invalid([{ field: "correct", reason: body.correct === undefined ? "missing" : "wrong_type", message: "correct is true or false: whether the run's answer was right" }]);
3400
+ if (body.expected !== undefined && !isObject(body.expected))
3401
+ throw invalid([{ field: "expected", reason: "wrong_type", message: "expected is an object: the fields a right answer's JSON holds" }]);
3402
+ if (body.source !== undefined && !GRADE_SOURCES.includes(body.source))
3403
+ throw invalid([{ field: "source", reason: "not_an_option", message: `source is one of ${GRADE_SOURCES.join(", ")}` }]);
3404
+ if (body.label !== undefined && (typeof body.label !== "string" || body.label.length > LABEL_MAX))
3405
+ throw invalid([{ field: "label", reason: "wrong_type", message: `label is a string of at most ${LABEL_MAX} characters: the grade's words` }]);
3406
+ if (!FINAL_STATES.includes(row.state))
3407
+ throw invalid([{ field: "run_id", reason: "not_allowed", message: "A run is graded once it has ended." }]);
3408
+ const m = (isObject(row.metrics) ? row.metrics : {});
3409
+ if (m.path === "replay")
3410
+ throw invalid([{ field: "run_id", reason: "not_allowed", message: "A replay run is never graded: its answer is scored against the run it replays." }]);
3411
+ const path = RUN_PATHS.includes(m.path) ? m.path : "agent";
3412
+ const grade = {
3413
+ run: row.id, correct: body.correct, ...(body.expected !== undefined ? { expected: body.expected } : {}), source: body.source ?? "feedback", at: new Date().toISOString(), path,
3414
+ ...(typeof m.workflow === "string" ? { workflow: m.workflow } : {}), ...(typeof m.workflow_digest === "string" ? { digest: m.workflow_digest } : {}),
3415
+ ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3416
+ };
3417
+ // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, a revision ask, or a look-back.
3418
+ const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined));
3419
+ // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3420
+ // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
3421
+ const shown = await learningShown(row.agentId).catch(() => undefined);
3422
+ return send(res, 200, { ...kept, workflow: kept.workflow === null ? null : shown ? shown.name(kept.workflow) : REDACTED });
3423
+ }
2841
3424
  case "archiveRun":
2842
3425
  case "unarchiveRun": {
2843
3426
  const run = await needRun(id);
@@ -2858,7 +3441,11 @@ async function startHolding(options, data, checked, stops) {
2858
3441
  const kept = await keptBrowserOf(store, run.id);
2859
3442
  // A desktop or a phone (the run's revision's computer) whose screen is not open now is still the run's computer:
2860
3443
  // none with its kind, never off as if the agent had none (#2170).
2861
- const viewed = family === "computer" ? await runViewedKind(store, run.id) : undefined;
3444
+ const own = family === "computer" ? await runComputerKind(store, run.id) : undefined;
3445
+ const viewed = own === "desktop" || own === "phone" ? own : undefined;
3446
+ // A parked run's desktop or phone is no screen being opened: its claim let it go, or kept it for the resume
3447
+ // (computer-kept.ts; the run's timeline says until when), and once its time passed, the timeout's words.
3448
+ const parked = family === "computer" && !run.terminal && (await store.runs.get(run.id))?.state === "parked";
2862
3449
  const view = await computerView({
2863
3450
  viewer: async () => {
2864
3451
  if (family === "browser") {
@@ -2867,8 +3454,9 @@ async function startHolding(options, data, checked, stops) {
2867
3454
  }
2868
3455
  return computerViewerLink(store, sealKey, run.id, answers);
2869
3456
  },
2870
- computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family)),
2871
- session: (kind) => sessionIn(kind, entries),
3457
+ computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family, own)),
3458
+ session: (kind) => sessionIn(kind, entries, run.terminal || (parked && kind !== "browser")),
3459
+ lapsed: async (kind) => (parked ? lapsedOf(kind, await readKept(store.settings, run.id).catch(() => undefined), Date.now()) : undefined),
2872
3460
  hold: () => hold,
2873
3461
  // A going run's browser let go while it waited for its person: the Screen tab says so, with when. One settings
2874
3462
  // row (browser-wait-ended.ts), never the run's journal: this is read on every Screen poll.
@@ -3118,6 +3706,35 @@ async function startHolding(options, data, checked, stops) {
3118
3706
  await toolKeys.remove(id);
3119
3707
  await keysChanged();
3120
3708
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3709
+ // Never through `idempotent`: its record keeps the body, and the body holds the password.
3710
+ case "getEmailAccount":
3711
+ case "saveEmailAccount":
3712
+ case "deleteEmailAccount":
3713
+ case "testEmailAccount": {
3714
+ const body = found.name === "saveEmailAccount" || found.name === "testEmailAccount" ? await bodyOf(req) : undefined;
3715
+ if (found.name === "saveEmailAccount" && stopping.signal.aborted)
3716
+ throw new ApiError("unavailable", "The server is shutting down: the account was not saved.");
3717
+ const answer = await emailRoute({ store, sealKey }, found.name, body);
3718
+ if (found.name === "saveEmailAccount")
3719
+ await heldEmailPassword();
3720
+ if (answer === undefined)
3721
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
3722
+ return send(res, 200, answer, { "cache-control": "no-store" });
3723
+ }
3724
+ // The ChatGPT sign-in (chatgpt-plan.ts): a step it refuses is 400 in its words; its token is in no answer.
3725
+ case "getChatGPTSignIn":
3726
+ await planNow();
3727
+ return send(res, 200, plan.view());
3728
+ case "startChatGPTSignIn":
3729
+ return send(res, 200, await planStep(() => plan.startSignIn()));
3730
+ case "finishChatGPTSignIn": {
3731
+ const body = (await bodyOf(req));
3732
+ return send(res, 200, await planStep(() => plan.finishSignIn(body?.redirect_url)));
3733
+ }
3734
+ case "signOutChatGPT": {
3735
+ const { revoked } = await plan.signOut();
3736
+ return send(res, 200, revoked ? { revoked } : { revoked, message: SIGN_OUT_UNCONFIRMED });
3737
+ }
3121
3738
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
3122
3739
  case "listMcpServers":
3123
3740
  return send(res, 200, await mcpServers.list());
@@ -3137,10 +3754,18 @@ async function startHolding(options, data, checked, stops) {
3137
3754
  // The name is checked before Composio is called: a refused name leaves nothing made there.
3138
3755
  mcpNameOf(id);
3139
3756
  const body = await bodyOf(req);
3140
- const answer = await composioSave(body, options.composioControl ?? {}, (mcp) => mcpServers.save(id, mcp, stopping.signal), id, stopping.signal, async () => (await mcpServers.get(id)).url);
3757
+ const answer = await composioSave(body, options.composioControl ?? {}, (mcp, made) => mcpServers.save(id, mcp, stopping.signal, undefined, made), id, stopping.signal, async () => (await mcpServers.get(id)).url);
3141
3758
  await refreshMcpMeta();
3142
3759
  return send(res, 200, answer, { "cache-control": "no-store" });
3143
3760
  }
3761
+ case "listComposioEvents":
3762
+ return send(res, 200, await composioTriggers.events(id), { "cache-control": "no-store" });
3763
+ case "listComposioTriggers":
3764
+ return send(res, 200, await composioTriggers.triggersOf(id), { "cache-control": "no-store" });
3765
+ case "rotateComposioSecret":
3766
+ return send(res, 200, await composioTriggers.rotate(id), { "cache-control": "no-store" });
3767
+ case "deleteComposioSubscription":
3768
+ return send(res, 200, await composioTriggers.forget(id), { "cache-control": "no-store" });
3144
3769
  case "refreshMcpServer": {
3145
3770
  const refreshed = await mcpServers.refresh(id, stopping.signal);
3146
3771
  await refreshMcpMeta();
@@ -3185,10 +3810,19 @@ async function startHolding(options, data, checked, stops) {
3185
3810
  return send(res, 200, await privateHostsRoute(mcpServers, { method: "GET" }), { "cache-control": "no-store" });
3186
3811
  case "putMcpPrivateHosts":
3187
3812
  return send(res, 200, await privateHostsRoute(mcpServers, { method: "PUT", body: () => bodyOf(req) }), { "cache-control": "no-store" });
3188
- case "deleteMcpServer":
3189
- await mcpServers.remove(id, secretSeen);
3813
+ case "deleteMcpServer": {
3814
+ // Our row goes first, by the checked removal (a 412 sends Composio nothing), and answers what it removed: a Composio
3815
+ // preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key.
3816
+ // Composio refusing or not answering, or a key that does not open, never keeps our row: the answer says what to
3817
+ // remove there by hand. One that Composio triggers still use is kept: refused, naming them, checked and deleted in
3818
+ // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting).
3819
+ const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
3190
3820
  await refreshMcpMeta();
3821
+ const forgotten = !made ? undefined : "unusable" in made ? composioNote(id) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal);
3822
+ if (forgotten && !forgotten.removed)
3823
+ return send(res, 200, { deleted: true, composio: forgotten }, { "cache-control": "no-store" });
3191
3824
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3825
+ }
3192
3826
  case "getToolSettings":
3193
3827
  return send(res, 200, withDefaults(settings.get()));
3194
3828
  case "putToolSettings": {
@@ -3227,13 +3861,20 @@ async function startHolding(options, data, checked, stops) {
3227
3861
  const read = await agentCostOverStore(store, id, limit);
3228
3862
  // Each workflow's name as the other learning reads show it: one that holds a secret or a sign-in's value is cut.
3229
3863
  const shown = await learningShown(id);
3230
- const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })) };
3864
+ const cost = { ...read, runs: read.runs.map((run) => (run.workflow === null ? run : { ...run, workflow: shown.name(run.workflow) })), workflows: read.workflows.map((one) => ({ ...one, workflow: shown.name(one.workflow) })) };
3231
3865
  if (csv) {
3232
3866
  res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-disposition": `attachment; filename="${id}-cost-per-run.csv"` });
3233
3867
  return void res.end(costCsv(cost.runs));
3234
3868
  }
3235
3869
  return send(res, 200, { agent: id, ...cost });
3236
3870
  }
3871
+ case "listLearningPromotions": {
3872
+ await needAgent(id);
3873
+ // Each learned workflow's promotion records, oldest first (learn/promote.ts): its replays' numbers and decisions,
3874
+ // its refits, its holds. Aggregates only; every text in them cut as the other learning reads cut theirs
3875
+ // (promotionsShown: a reason and a refit guard's label as well as each workflow's name).
3876
+ return send(res, 200, { agent: id, ...promotionsShown(await promotionsOf(store.settings, id), await learningShown(id)) });
3877
+ }
3237
3878
  case "createLearningBatch": {
3238
3879
  await needAgent(id);
3239
3880
  const made = await batches.create(id, await bodyOf(req));
@@ -3264,6 +3905,26 @@ async function startHolding(options, data, checked, stops) {
3264
3905
  });
3265
3906
  return send(res, answer.status, answer.body, answer.headers);
3266
3907
  }
3908
+ case "getLearningLoop": {
3909
+ await needAgent(id);
3910
+ // The loop's own record over the one store (store-reads/loop.ts): compile turns and guarded steps, aggregates only.
3911
+ // Names cut as the other learning reads cut them; a compile's error texts cut by its run's own cut as its run's
3912
+ // learning read cuts them (run-learning-served.ts), and left out when that run's handed values can't be read.
3913
+ const shown = await learningShown(id);
3914
+ const values = await learningValues(id);
3915
+ const read = await agentLoopOverStore(store, id);
3916
+ const compiles = await Promise.all(read.compiles.map(async (one) => {
3917
+ const cut = await runCutValues({ serverSecrets, signIns }, store, one.run_id).catch(() => "unreadable");
3918
+ const workflow = one.workflow === null ? null : shown.name(one.workflow);
3919
+ if (cut === "unreadable")
3920
+ return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok }) => ({ ok, errors: [] })), draft_errors: [], withheld: true };
3921
+ const all = [...values, ...cut.values];
3922
+ const said = (error) => shown.text(printable({ rule: "workflow", detail: error }, all).detail);
3923
+ return { ...one, workflow, from_notes: one.from_notes.map(shown.name), attempts: one.attempts.map(({ ok, errors }) => ({ ok, errors: errors.map(said) })), draft_errors: one.draft_errors.map(said), withheld: false };
3924
+ }));
3925
+ const guards = read.guards.map((one) => ({ ...one, workflow: shown.name(one.workflow), node: shown.text(one.node) }));
3926
+ return send(res, 200, { agent: id, compiles, guards });
3927
+ }
3267
3928
  case "listLearningNotes":
3268
3929
  case "listLearningLog":
3269
3930
  await needAgent(id);
@@ -3304,6 +3965,29 @@ async function startHolding(options, data, checked, stops) {
3304
3965
  });
3305
3966
  return send(res, answer.status, answer.body, answer.headers);
3306
3967
  }
3968
+ case "startLearnedWorkflowReplay": {
3969
+ const body = await bodyOf(req);
3970
+ // An archived agent starts no run: refused before the replay is reserved, as a person's start is.
3971
+ const entry = await needRunnableAgent(id);
3972
+ const extra = unknownFields(body, ["inputs"]);
3973
+ if (extra.length)
3974
+ throw invalid(extra);
3975
+ const inputs = body.inputs === undefined ? "held" : body.inputs;
3976
+ if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= GRADES_KEPT)) {
3977
+ throw new ApiError("bad_request", `inputs is "held" (the graded inputs the revision was last decided on, the default) or a whole number from 1 to ${GRADES_KEPT}: that many of the agent's newest graded inputs.`);
3978
+ }
3979
+ const [, , name, digest] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
3980
+ const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
3981
+ return send(res, 202, started, { location: `/v2/agents/${encodeURIComponent(id)}/learning/workflows/${encodeURIComponent(name)}/revisions/${encodeURIComponent(digest)}/replays/${started.replay}` });
3982
+ }
3983
+ case "getLearnedWorkflowReplay": {
3984
+ const entry = await needAgent(id);
3985
+ const [, , name, digest, replayId] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
3986
+ const view = await replayAsked(() => replayView(replayAskOf(entry), name, digest, replayId));
3987
+ // Its words cut as the promotions list cuts a record's (promotionsShown).
3988
+ const shown = await learningShown(id);
3989
+ return send(res, 200, { ...view, workflow: shown.name(view.workflow), ...(view.reason !== undefined ? { reason: shown.text(view.reason) } : {}) });
3990
+ }
3307
3991
  case "getRunLearning": {
3308
3992
  const run = await needRun(id);
3309
3993
  // The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
@@ -3355,26 +4039,32 @@ async function startHolding(options, data, checked, stops) {
3355
4039
  }
3356
4040
  case "listTemplates": {
3357
4041
  // Each package's computer list read against this server now: what an apply here would pick (pickComputer).
3358
- const here = templates.some((one) => one.computer) ? await shellHere() : undefined;
3359
- const pickView = (pkg) => {
3360
- const pick = here && pickComputer(pkg, here);
3361
- if (!pick)
3362
- return null;
3363
- if ("refused" in pick)
3364
- return { entry: null, computer: null, shell: null, dropped: [], note: pick.refused };
3365
- return { entry: pick.entry, computer: pick.computer, shell: pick.shell, dropped: pick.dropped, note: pick.note };
3366
- };
3367
- return send(res, 200, { templates: templates.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
4042
+ const listed = registry.list();
4043
+ const pickView = await computerHere(listed);
4044
+ return send(res, 200, { templates: listed.map((pkg) => ({ ...packageView(pkg), computer_here: pickView(pkg) })) });
4045
+ }
4046
+ case "importTemplate": {
4047
+ // Read from GitHub and checked; a dry run answers it (200), else it is stored and served (201). The answer shows the
4048
+ // package whole, its instructions and every skill file, for a person to read before they apply it.
4049
+ const body = await bodyOf(req);
4050
+ const done = new AbortController();
4051
+ res.once("close", () => done.abort());
4052
+ const imported = await importTemplate(importDeps, body, done.signal);
4053
+ const pickView = await computerHere([imported.pkg]);
4054
+ return send(res, imported.status, { template: { ...packageView(imported.pkg), computer_here: pickView(imported.pkg) }, ...(({ instructions, skill_files }) => ({ instructions, skill_files }))(packageDetail(imported.pkg)), publisher_trusted: imported.trusted, stored: imported.status === 201, replaced: imported.replaced, console_url: imported.status === 201 ? templateLink(linkOrigin(req), imported.pkg.id) : templateInstallLink(linkOrigin(req), imported.pkg.origin?.source ?? imported.pkg.id) });
3368
4055
  }
4056
+ case "deleteTemplate":
4057
+ await deleteTemplate(importDeps, id);
4058
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
3369
4059
  case "applyTemplate": {
3370
- const pkg = templates.find((t) => t.name === id);
4060
+ const pkg = registry.get(id);
3371
4061
  if (!pkg)
3372
4062
  throw new ApiError("not_found", `no template ${id}: GET /v2/templates lists them`);
3373
4063
  const body = await bodyOf(req);
3374
4064
  // The Idempotency-Key's record keeps the agent and triggers, so a retry under the key gets the same apply; it never
3375
4065
  // keeps a webhook trigger's secret (below).
3376
4066
  let minted = new Map();
3377
- const answer = await idempotent(req, `/templates/${pkg.name}/apply`, body, async () => {
4067
+ const answer = await idempotent(req, `/templates/${encodeURIComponent(pkg.id)}/apply`, body, async () => {
3378
4068
  const made = await applyTemplate(pkg, body);
3379
4069
  minted = made.minted;
3380
4070
  return { status: 201, body: made.applied, headers: { location: `/v2/agents/${made.applied.agent_id}` } };
@@ -3387,23 +4077,24 @@ async function startHolding(options, data, checked, stops) {
3387
4077
  }
3388
4078
  case "rotateTriggerSecret":
3389
4079
  // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
3390
- // A trigger whose sender gives its secret (Composio's) takes it as the body's `secret`; any other is made one.
3391
- return send(res, 200, await (async () => {
3392
- const empty = req.headers["transfer-encoding"] === undefined && !Number(req.headers["content-length"]);
3393
- const body = empty ? {} : await bodyOf(req);
3394
- const extra = Object.keys(body).filter((key) => key !== "secret");
3395
- if (extra.length)
3396
- throw invalid(extra.map((field) => ({ field, reason: "unknown_field", message: `${field} is not a field of this request: only secret` })));
3397
- return triggerRotated(id, (await triggers.rotate(id, body.secret)).secret, new Date().toISOString());
3398
- })());
4080
+ // It takes no body: the new secret is made here, never given. Any body is refused before it rotates, `{}` too: a
4081
+ // length other than 0, or one sent chunked, is a body whatever it holds.
4082
+ if (req.headers["transfer-encoding"] !== undefined || Number(req.headers["content-length"] ?? 0) !== 0) {
4083
+ throw invalid([{ field: "body", reason: "not_allowed", message: "Rotating a trigger's secret takes no body: send none, and the new secret is made here." }]);
4084
+ }
4085
+ return send(res, 200, triggerRotated(id, (await triggers.rotate(id)).secret, new Date().toISOString()));
3399
4086
  case "getTrigger":
3400
4087
  return send(res, 200, withSecretOf(await triggers.get(id)));
3401
4088
  case "updateTrigger":
3402
4089
  // Its secret's metadata as a read answers it, so a page showing the changed trigger keeps saying it is set.
3403
4090
  return send(res, 200, withSecretOf(await triggers.update(id, await bodyOf(req))));
3404
- case "deleteTrigger":
3405
- await triggers.remove(id);
4091
+ case "deleteTrigger": {
4092
+ // Deleted here whatever its sender says; what could not be removed there is answered (Composio's instance).
4093
+ const said = await triggers.remove(id);
4094
+ if (said)
4095
+ return send(res, 200, { deleted: true, ...said });
3406
4096
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
4097
+ }
3407
4098
  case "fireTrigger": {
3408
4099
  const key = req.headers["idempotency-key"];
3409
4100
  if (typeof key !== "string" || key.length < 1 || key.length > 255)
@@ -3502,8 +4193,12 @@ async function startHolding(options, data, checked, stops) {
3502
4193
  return void mcp(req, res).catch(fail);
3503
4194
  if (raw === "/llms.txt")
3504
4195
  return void answerLlms(req, res).catch(fail);
4196
+ if (raw === "/skills/agentrun-serve/SKILL.md")
4197
+ return void answerSkill(req, res).catch(fail);
3505
4198
  if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3506
4199
  return;
4200
+ if (isObservationRoute(raw))
4201
+ return void observationHttp(req, res, url, new Observations(store), token).catch(fail);
3507
4202
  if (!raw.startsWith("/v2/"))
3508
4203
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
3509
4204
  // A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
@@ -3627,7 +4322,10 @@ async function startHolding(options, data, checked, stops) {
3627
4322
  // change would be the next seam.
3628
4323
  const RUN_CHANGES_POLL_MS = 250;
3629
4324
  const final = (row) => FINAL_STATES.includes(row.state);
3630
- const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}) });
4325
+ /** A row its stop ended (stopEnd), which may stand at the person's stop (store.ts stoppedByPerson: an agentic run, its
4326
+ * status input_required and idle, a message continues it) and not have ended: its view says which. */
4327
+ const stopRow = (row) => row.state === "stopped" && row.outcome === "stopped" && row.importedFrom === null;
4328
+ const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}), ...(stopRow(row) ? { stop: true } : {}) });
3631
4329
  /** The run as the store holds it now, with its notice (the run list's own view of it); null when there is no such run. */
3632
4330
  const endNotice = async (id) => {
3633
4331
  const row = await store.runs.get(id);
@@ -3653,9 +4351,9 @@ async function startHolding(options, data, checked, stops) {
3653
4351
  /** When each held wait (a run waiting on its person with its claim held) was last read again. */
3654
4352
  const heldReadAt = new Map();
3655
4353
  const HELD_WAIT_REREAD_MS = 1_000;
3656
- const waitKinds = new Set(["question", "approval", "budget", "browser"]);
4354
+ const waitKinds = new Set(["question", "approval", "budget", "browser", "computer", "stopped"]);
3657
4355
  /** The wait of a run its runner left parked (or let go of), or holds in its claim, told once per ask: its marker the
3658
- * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). False when it
4356
+ * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (none when the run waits on no card). False when it
3659
4357
  * is not done (a read that failed, or its notice not saved): it is read again. */
3660
4358
  const tellWait = async (row) => {
3661
4359
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
@@ -3665,14 +4363,17 @@ async function startHolding(options, data, checked, stops) {
3665
4363
  if (view?.status !== "input_required")
3666
4364
  return (readWaits.set(row.id, seen), true);
3667
4365
  const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
3668
- // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last.
3669
- const marker = waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
4366
+ const card = view.pending?.kind;
4367
+ // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last. A stop's is when
4368
+ // its stop ended the row: rows its stopped turn still streams in (a late result, a charge) never move it.
4369
+ const marker = card === "stopped" && row.endedAt !== null ? `stopped:${new Date(row.endedAt).toISOString()}` : waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
3670
4370
  if (!marker)
3671
4371
  return (readWaits.set(row.id, seen), true);
3672
- const card = view.pending?.kind;
3673
- const kind = view.state !== "waiting" ? "stopped" : typeof card === "string" && waitKinds.has(card) ? card : "question";
3674
- const wait = { kind };
3675
- const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: wait };
4372
+ // Its kind is the read's own `pending.kind` (a stop's is stoppedTurn's), so the notice and GET never disagree; a wait
4373
+ // whose card is withheld is a question. A run idle on nothing named (its harness ended its turn on its own) names no kind.
4374
+ const kind = typeof card === "string" && waitKinds.has(card) ? card : view.state === "waiting" ? "question" : undefined;
4375
+ const wait = kind === undefined ? undefined : { kind };
4376
+ const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", ...(wait ? { pending: wait } : {}) };
3676
4377
  if (!(await toldAll(row.id, waitSubscribers.map((tell) => () => tell(notice, wait, marker)))))
3677
4378
  return false;
3678
4379
  readWaits.set(row.id, seen);
@@ -3724,6 +4425,17 @@ async function startHolding(options, data, checked, stops) {
3724
4425
  const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
3725
4426
  if (now === undefined)
3726
4427
  return false;
4428
+ // A person's stop of an agentic run ends its row but not the run: it reads input_required (pending kind stopped), so
4429
+ // it is told as that wait, run.needs_input, never as an end.
4430
+ if (now?.notice.status === "input_required") {
4431
+ const row = await rowNow(id);
4432
+ if (row === UNREAD)
4433
+ return (sayUnread(id, "its row could not be read"), false);
4434
+ const told = row === undefined || (await tellWait(row).catch((error) => (sayUnread(id, error.message), false)));
4435
+ if (told)
4436
+ unreadSaid.delete(id);
4437
+ return told;
4438
+ }
3727
4439
  readWaits.delete(id);
3728
4440
  heldReadAt.delete(id);
3729
4441
  if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
@@ -3762,7 +4474,7 @@ async function startHolding(options, data, checked, stops) {
3762
4474
  const row = await rowNow(id);
3763
4475
  if (row === UNREAD)
3764
4476
  return (sayUnread(id, "its row could not be read"), false);
3765
- if (row === undefined || !letGo(row))
4477
+ if (row === undefined || !(letGo(row) || stopRow(row)))
3766
4478
  return true;
3767
4479
  const told = await tellWait(row).catch((error) => (sayUnread(id, error.message), false));
3768
4480
  if (told)
@@ -3847,8 +4559,9 @@ async function startHolding(options, data, checked, stops) {
3847
4559
  const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
3848
4560
  for (const id of unsaved)
3849
4561
  endsLeft.add(id);
4562
+ // A run that stands at a person's stop waits too (tellWait reads its view: one its stop ended reads no wait).
3850
4563
  for (const row of rows)
3851
- if (!closing && letGo(row) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
4564
+ if (!closing && (letGo(row) || stopRow(row)) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
3852
4565
  waitsLeft.add(row.id);
3853
4566
  };
3854
4567
  followChanges();
@@ -3862,6 +4575,9 @@ async function startHolding(options, data, checked, stops) {
3862
4575
  // the store closes last.
3863
4576
  closing = true;
3864
4577
  stopping.abort();
4578
+ // Cancel a pending ChatGPT callback without signing out or changing the saved credential.
4579
+ plan.close();
4580
+ const observationStopped = stopObservationRetention();
3865
4581
  // A harness install under way stops with the server: npm gets SIGTERM, then SIGKILL, and nothing half installed stays.
3866
4582
  const installStopped = Promise.all(Object.values(installs).map((install) => install.stop()));
3867
4583
  // Aborted now, so nothing it writes races the next server on the same refresh token; drained before the store closes.
@@ -3879,6 +4595,7 @@ async function startHolding(options, data, checked, stops) {
3879
4595
  await Promise.all([...workers.values()].map((w) => w.exit));
3880
4596
  await importing;
3881
4597
  await installStopped;
4598
+ await observationStopped;
3882
4599
  // The ends' follower stops before the webhooks it feeds and the store it reads.
3883
4600
  clearTimeout(endsTimer);
3884
4601
  await endsRead;