@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.40

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 (423) hide show
  1. package/CHANGELOG.md +455 -0
  2. package/README.md +376 -125
  3. package/dist/adapters.d.ts +4 -1
  4. package/dist/adapters.js +4 -2
  5. package/dist/agent-rows.d.ts +0 -2
  6. package/dist/agents-store.d.ts +5 -5
  7. package/dist/agents-store.js +14 -14
  8. package/dist/bash-read-only.js +2 -1
  9. package/dist/cap-short.d.ts +12 -0
  10. package/dist/cap-short.js +60 -0
  11. package/dist/cap.d.ts +3 -10
  12. package/dist/cap.js +2 -5
  13. package/dist/catalog.d.ts +0 -5
  14. package/dist/catalog.js +1 -5
  15. package/dist/chatgpt-plan.d.ts +163 -0
  16. package/dist/chatgpt-plan.js +549 -0
  17. package/dist/cli.js +26 -6
  18. package/dist/composio-preset.d.ts +8 -0
  19. package/dist/composio-preset.js +8 -7
  20. package/dist/composio-triggers.d.ts +113 -0
  21. package/dist/composio-triggers.js +411 -0
  22. package/dist/computer-calls.js +2 -2
  23. package/dist/computer-commands.d.ts +2 -0
  24. package/dist/computer-commands.js +7 -3
  25. package/dist/computer-live.d.ts +7 -2
  26. package/dist/computer-live.js +9 -5
  27. package/dist/computer-routes.d.ts +2 -2
  28. package/dist/computer-routes.js +2 -2
  29. package/dist/computer-setting.d.ts +3 -3
  30. package/dist/computer-setting.js +5 -5
  31. package/dist/computer-view.d.ts +15 -0
  32. package/dist/computer-view.js +16 -2
  33. package/dist/computer-viewer.js +14 -1
  34. package/dist/computers.d.ts +5 -2
  35. package/dist/computers.js +9 -5
  36. package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
  37. package/dist/console/assets/index-Jbxjcmdp.js +705 -0
  38. package/dist/console/index.html +2 -2
  39. package/dist/console-links.js +3 -3
  40. package/dist/decision-cap.d.ts +2 -5
  41. package/dist/decision-cap.js +3 -6
  42. package/dist/decision-rows.js +11 -11
  43. package/dist/email/account.d.ts +83 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +15 -0
  46. package/dist/email/answer.js +217 -0
  47. package/dist/email/email-faux.d.ts +95 -0
  48. package/dist/email/email-faux.js +849 -0
  49. package/dist/email/labels.d.ts +1 -0
  50. package/dist/email/labels.js +84 -0
  51. package/dist/email/mail.d.ts +186 -0
  52. package/dist/email/mail.js +373 -0
  53. package/dist/email/names.d.ts +50 -0
  54. package/dist/email/names.js +74 -0
  55. package/dist/email/routes.d.ts +10 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +27 -0
  58. package/dist/email/tools.js +562 -0
  59. package/dist/environment.d.ts +17 -2
  60. package/dist/environment.js +36 -8
  61. package/dist/errors.d.ts +6 -0
  62. package/dist/errors.js +12 -0
  63. package/dist/eval-mailbox.d.ts +103 -0
  64. package/dist/eval-mailbox.js +236 -0
  65. package/dist/graph-view.d.ts +9 -2
  66. package/dist/graph-view.js +6 -2
  67. package/dist/harness-install.d.ts +28 -2
  68. package/dist/harness-install.js +147 -59
  69. package/dist/harness-opencode/adapter.js +2 -26
  70. package/dist/harness-opencode/facts.js +5 -2
  71. package/dist/harness-opencode/host/policy.d.ts +2 -0
  72. package/dist/harness-opencode/host/policy.js +10 -5
  73. package/dist/harness-opencode/index.d.ts +1 -1
  74. package/dist/harness-opencode/index.js +1 -1
  75. package/dist/harness-opencode/versions.d.ts +6 -0
  76. package/dist/harness-opencode/versions.js +6 -0
  77. package/dist/harness-table.js +8 -5
  78. package/dist/harness.d.ts +12 -0
  79. package/dist/harness.js +15 -3
  80. package/dist/hosted-search.d.ts +3 -1
  81. package/dist/hosted-search.js +51 -11
  82. package/dist/import-sources.d.ts +1 -1
  83. package/dist/import-sources.js +3 -3
  84. package/dist/import.d.ts +21 -0
  85. package/dist/import.js +186 -1
  86. package/dist/key-check.d.ts +0 -2
  87. package/dist/key-check.js +3 -4
  88. package/dist/key-refusal.d.ts +8 -2
  89. package/dist/key-refusal.js +16 -13
  90. package/dist/learn/check.d.ts +18 -3
  91. package/dist/learn/check.js +328 -3
  92. package/dist/learn/compile.d.ts +12 -4
  93. package/dist/learn/compile.js +57 -20
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +130 -64
  97. package/dist/learn/promote.js +113 -202
  98. package/dist/learn/refit.d.ts +21 -12
  99. package/dist/learn/refit.js +51 -23
  100. package/dist/learn/replay-calls.js +1 -1
  101. package/dist/learn/skills.d.ts +2 -7
  102. package/dist/learn/skills.js +28 -14
  103. package/dist/learned-nodes.d.ts +15 -7
  104. package/dist/learned-nodes.js +29 -5
  105. package/dist/learned-workflow.d.ts +41 -31
  106. package/dist/learned-workflow.js +122 -63
  107. package/dist/learning-batch.js +3 -3
  108. package/dist/learning-cost.d.ts +35 -8
  109. package/dist/learning-cost.js +27 -9
  110. package/dist/learning-routes.d.ts +2 -4
  111. package/dist/learning-routes.js +20 -3
  112. package/dist/learning-words.d.ts +1 -1
  113. package/dist/learning-words.js +4 -1
  114. package/dist/learning.d.ts +5 -5
  115. package/dist/link-check.d.ts +27 -0
  116. package/dist/link-check.js +164 -0
  117. package/dist/local-models.d.ts +39 -2
  118. package/dist/local-models.js +49 -5
  119. package/dist/mcp-pin-first.js +6 -0
  120. package/dist/mcp-secret-writes.js +3 -0
  121. package/dist/mcp-servers-store.d.ts +25 -16
  122. package/dist/mcp-servers-store.js +23 -3
  123. package/dist/model-form.d.ts +11 -0
  124. package/dist/model-form.js +17 -1
  125. package/dist/model.d.ts +26 -6
  126. package/dist/model.js +126 -18
  127. package/dist/monid.d.ts +26 -31
  128. package/dist/monid.js +84 -79
  129. package/dist/native/binding.d.ts +13 -0
  130. package/dist/native/binding.js +57 -0
  131. package/dist/native/cli.d.ts +2 -0
  132. package/dist/native/cli.js +48 -0
  133. package/dist/native/connection.d.ts +8 -0
  134. package/dist/native/connection.js +94 -0
  135. package/dist/native/context.d.ts +6 -0
  136. package/dist/native/context.js +22 -0
  137. package/dist/native/discovery.d.ts +27 -0
  138. package/dist/native/discovery.js +404 -0
  139. package/dist/native/environment.d.ts +4 -0
  140. package/dist/native/environment.js +18 -0
  141. package/dist/native/history.d.ts +20 -0
  142. package/dist/native/history.js +147 -0
  143. package/dist/native/instructions.d.ts +21 -0
  144. package/dist/native/instructions.js +173 -0
  145. package/dist/native/remote-worker-bridge.d.ts +3 -0
  146. package/dist/native/remote-worker-bridge.js +278 -0
  147. package/dist/native/remote.d.ts +187 -0
  148. package/dist/native/remote.js +492 -0
  149. package/dist/native/runtime.d.ts +17 -0
  150. package/dist/native/runtime.js +316 -0
  151. package/dist/native/runtimes.d.ts +66 -0
  152. package/dist/native/runtimes.js +41 -0
  153. package/dist/native/schema.d.ts +46 -0
  154. package/dist/native/schema.js +41 -0
  155. package/dist/native/types.d.ts +87 -0
  156. package/dist/native/types.js +1 -0
  157. package/dist/observation/http.d.ts +4 -0
  158. package/dist/observation/http.js +140 -0
  159. package/dist/observation/observer.d.ts +301 -0
  160. package/dist/observation/observer.js +919 -0
  161. package/dist/observation/schema.d.ts +52 -0
  162. package/dist/observation/schema.js +154 -0
  163. package/dist/openapi.d.ts +2 -1
  164. package/dist/openapi.js +404 -93
  165. package/dist/paid-calls.d.ts +8 -3
  166. package/dist/paid-calls.js +6 -2
  167. package/dist/place-offers.d.ts +4 -8
  168. package/dist/place-offers.js +4 -9
  169. package/dist/port-models.d.ts +10 -2
  170. package/dist/port-models.js +6 -2
  171. package/dist/print.d.ts +4 -2
  172. package/dist/print.js +4 -3
  173. package/dist/propose.d.ts +1 -2
  174. package/dist/propose.js +10 -1
  175. package/dist/provider.d.ts +5 -1
  176. package/dist/provider.js +8 -0
  177. package/dist/push-handler.d.ts +3 -2
  178. package/dist/push-handler.js +20 -6
  179. package/dist/refusal-words.d.ts +14 -0
  180. package/dist/refusal-words.js +16 -2
  181. package/dist/run-launch.d.ts +12 -1
  182. package/dist/run-launch.js +13 -4
  183. package/dist/run-learning-served.d.ts +75 -2
  184. package/dist/run-manifest.d.ts +3 -0
  185. package/dist/run-manifest.js +13 -1
  186. package/dist/run-reads-over-store.d.ts +3 -3
  187. package/dist/run-reads-over-store.js +13 -10
  188. package/dist/run-timeline-served.d.ts +3 -2
  189. package/dist/run-timeline-served.js +8 -9
  190. package/dist/run-view.d.ts +44 -38
  191. package/dist/run-view.js +93 -56
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +48 -13
  195. package/dist/runner/adapter-loop.js +691 -254
  196. package/dist/runner/adapter-run-spec.d.ts +38 -12
  197. package/dist/runner/adapter-run-spec.js +175 -106
  198. package/dist/runner/adapters/pi.d.ts +24 -0
  199. package/dist/runner/adapters/pi.js +59 -9
  200. package/dist/runner/beside.d.ts +3 -1
  201. package/dist/runner/beside.js +24 -8
  202. package/dist/runner/claim-secrets.d.ts +3 -1
  203. package/dist/runner/claim-secrets.js +28 -4
  204. package/dist/runner/cli-run-spec.d.ts +30 -0
  205. package/dist/runner/cli-run-spec.js +95 -50
  206. package/dist/runner/computer-channel.d.ts +5 -2
  207. package/dist/runner/computer-channel.js +3 -2
  208. package/dist/runner/computer-journal.d.ts +6 -0
  209. package/dist/runner/computer-journal.js +8 -10
  210. package/dist/runner/conformance/harness.js +6 -3
  211. package/dist/runner/end-of-run.d.ts +2 -0
  212. package/dist/runner/end-of-run.js +3 -1
  213. package/dist/runner/feedback-round.d.ts +40 -13
  214. package/dist/runner/feedback-round.js +64 -16
  215. package/dist/runner/harness-loops.js +17 -0
  216. package/dist/runner/journal-kinds.d.ts +59 -13
  217. package/dist/runner/journal-kinds.js +48 -5
  218. package/dist/runner/learning-dispatch.d.ts +3 -2
  219. package/dist/runner/learning-dispatch.js +6 -6
  220. package/dist/runner/learning-end.d.ts +4 -0
  221. package/dist/runner/learning-end.js +64 -36
  222. package/dist/runner/learning-factory.d.ts +3 -0
  223. package/dist/runner/learning-factory.js +8 -2
  224. package/dist/runner/learning-loop.d.ts +2 -0
  225. package/dist/runner/learning-loop.js +19 -4
  226. package/dist/runner/loop.d.ts +18 -0
  227. package/dist/runner/loop.js +34 -0
  228. package/dist/runner/main.d.ts +6 -1
  229. package/dist/runner/main.js +26 -4
  230. package/dist/runner/mcp-run.d.ts +4 -1
  231. package/dist/runner/mcp-run.js +11 -5
  232. package/dist/runner/meta-tools.d.ts +10 -3
  233. package/dist/runner/meta-tools.js +112 -36
  234. package/dist/runner/metrics.d.ts +80 -21
  235. package/dist/runner/metrics.js +114 -39
  236. package/dist/runner/model-route.d.ts +14 -3
  237. package/dist/runner/model-route.js +155 -19
  238. package/dist/runner/monid-run.d.ts +8 -6
  239. package/dist/runner/monid-run.js +117 -43
  240. package/dist/runner/native-loop.d.ts +11 -0
  241. package/dist/runner/native-loop.js +438 -0
  242. package/dist/runner/promotion.d.ts +76 -10
  243. package/dist/runner/promotion.js +476 -154
  244. package/dist/runner/redact.js +3 -0
  245. package/dist/runner/reflect-hook.js +9 -0
  246. package/dist/runner/runner.d.ts +7 -1
  247. package/dist/runner/runner.js +8 -4
  248. package/dist/runner/sdk-loop.d.ts +7 -0
  249. package/dist/runner/sdk-loop.js +470 -0
  250. package/dist/runner/spec-holds.d.ts +16 -2
  251. package/dist/runner/spec-holds.js +42 -14
  252. package/dist/runner/store-secrets.js +17 -2
  253. package/dist/runner/workflow-first.d.ts +30 -20
  254. package/dist/runner/workflow-first.js +22 -32
  255. package/dist/runner/workflow-loop.d.ts +1 -1
  256. package/dist/runner/workflow-loop.js +18 -12
  257. package/dist/runner/workflow-spec.d.ts +4 -1
  258. package/dist/runner/workflow-spec.js +56 -45
  259. package/dist/runs-over-store.d.ts +30 -2
  260. package/dist/runs-over-store.js +46 -14
  261. package/dist/sdk/runs.d.ts +115 -0
  262. package/dist/sdk/runs.js +422 -0
  263. package/dist/sdk/schema.d.ts +175 -0
  264. package/dist/sdk/schema.js +138 -0
  265. package/dist/sdk/workflows.d.ts +22 -0
  266. package/dist/sdk/workflows.js +39 -0
  267. package/dist/secrets.d.ts +2 -0
  268. package/dist/secrets.js +19 -1
  269. package/dist/server.d.ts +48 -32
  270. package/dist/server.js +568 -137
  271. package/dist/skill-route.d.ts +3 -0
  272. package/dist/skill-route.js +16 -0
  273. package/dist/skills/agentrun-serve/SKILL.md +368 -0
  274. package/dist/stats.d.ts +10 -10
  275. package/dist/store/agent-body.d.ts +12 -8
  276. package/dist/store/agent-body.js +9 -4
  277. package/dist/store/dialect.d.ts +3 -0
  278. package/dist/store/dialect.js +1 -0
  279. package/dist/store/index.d.ts +1 -1
  280. package/dist/store/native-command-owner.d.ts +10 -0
  281. package/dist/store/native-command-owner.js +47 -0
  282. package/dist/store/postgres/connection.d.ts +11 -5
  283. package/dist/store/postgres/connection.js +44 -17
  284. package/dist/store/postgres/dialect.js +5 -0
  285. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  286. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  287. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  288. package/dist/store/postgres/store.d.ts +7 -3
  289. package/dist/store/postgres/store.js +4 -0
  290. package/dist/store/schema.d.ts +7 -0
  291. package/dist/store/schema.js +20 -1
  292. package/dist/store/sqlite/connection.js +72 -8
  293. package/dist/store/sqlite/run-launch.d.ts +11 -0
  294. package/dist/store/sqlite/run-launch.js +8 -0
  295. package/dist/store/sqlite/run-patch.d.ts +8 -1
  296. package/dist/store/sqlite/run-patch.js +14 -3
  297. package/dist/store/sqlite/store.js +170 -34
  298. package/dist/store/sqlite/worker.d.ts +2 -0
  299. package/dist/store/sqlite/worker.js +13 -10
  300. package/dist/store/store.d.ts +67 -7
  301. package/dist/store-reads/analytics.d.ts +7 -7
  302. package/dist/store-reads/analytics.js +23 -5
  303. package/dist/store-reads/cap.js +8 -6
  304. package/dist/store-reads/journal.d.ts +5 -0
  305. package/dist/store-reads/journal.js +85 -41
  306. package/dist/store-reads/learning.d.ts +115 -18
  307. package/dist/store-reads/learning.js +170 -68
  308. package/dist/store-reads/runs.d.ts +5 -0
  309. package/dist/store-reads/runs.js +3 -2
  310. package/dist/store-view.js +75 -21
  311. package/dist/template-eval.d.ts +73 -11
  312. package/dist/template-eval.js +535 -75
  313. package/dist/templates.d.ts +84 -21
  314. package/dist/templates.js +254 -47
  315. package/dist/text-urls.d.ts +38 -0
  316. package/dist/text-urls.js +170 -0
  317. package/dist/timeline/index.d.ts +3 -2
  318. package/dist/timeline/index.js +3 -2
  319. package/dist/timeline/labels.d.ts +5 -2
  320. package/dist/timeline/labels.js +29 -6
  321. package/dist/timeline/origin.d.ts +1 -1
  322. package/dist/timeline/origin.js +2 -2
  323. package/dist/timeline/render-text.js +1 -1
  324. package/dist/timeline/timeline.d.ts +66 -4
  325. package/dist/timeline/timeline.js +160 -30
  326. package/dist/timeline/util.d.ts +5 -0
  327. package/dist/timeline/util.js +44 -8
  328. package/dist/timeline/web-calls.d.ts +17 -0
  329. package/dist/timeline/web-calls.js +106 -0
  330. package/dist/tool-gate.d.ts +46 -44
  331. package/dist/tool-gate.js +101 -92
  332. package/dist/tool-list.d.ts +4 -1
  333. package/dist/tool-list.js +8 -1
  334. package/dist/tool-names.d.ts +18 -13
  335. package/dist/tool-names.js +19 -17
  336. package/dist/tool-plane.d.ts +17 -13
  337. package/dist/tool-plane.js +12 -5
  338. package/dist/tools.d.ts +57 -16
  339. package/dist/tools.js +33 -28
  340. package/dist/trigger-adapter.d.ts +56 -5
  341. package/dist/trigger-adapter.js +6 -0
  342. package/dist/trigger-adapters.js +3 -1
  343. package/dist/trigger-composio.d.ts +10 -0
  344. package/dist/trigger-composio.js +122 -0
  345. package/dist/trigger-email.d.ts +4 -0
  346. package/dist/trigger-email.js +181 -0
  347. package/dist/trigger-signatures.d.ts +6 -10
  348. package/dist/trigger-signatures.js +16 -16
  349. package/dist/trigger-targets.d.ts +1 -1
  350. package/dist/trigger-targets.js +4 -3
  351. package/dist/trigger-webhook.js +6 -4
  352. package/dist/triggers.d.ts +105 -8
  353. package/dist/triggers.js +286 -62
  354. package/dist/uploads.d.ts +9 -0
  355. package/dist/uploads.js +27 -0
  356. package/dist/validate.js +1 -7
  357. package/dist/web-fake.d.ts +56 -0
  358. package/dist/web-fake.js +102 -0
  359. package/dist/web-fetch-direct.d.ts +3 -0
  360. package/dist/web-fetch-direct.js +4 -1
  361. package/dist/web-fetch.d.ts +5 -1
  362. package/dist/web-fetch.js +8 -31
  363. package/dist/web-search.d.ts +51 -2
  364. package/dist/web-search.js +116 -18
  365. package/dist/webhooks.d.ts +2 -1
  366. package/dist/webhooks.js +5 -1
  367. package/dist/workflow/decision-recovery.js +5 -2
  368. package/dist/workflow/decisions.d.ts +7 -0
  369. package/dist/workflow/node-runner.js +10 -2
  370. package/dist/workspace/archil-claim.d.ts +3 -0
  371. package/dist/workspace/archil-claim.js +9 -2
  372. package/dist/workspace/computer-deps.d.ts +22 -9
  373. package/dist/workspace/computer-deps.js +78 -37
  374. package/dist/workspace/computer-for-claim.d.ts +54 -4
  375. package/dist/workspace/computer-for-claim.js +179 -39
  376. package/dist/workspace/computer-janitor.d.ts +10 -3
  377. package/dist/workspace/computer-janitor.js +96 -29
  378. package/dist/workspace/computer-kept.d.ts +82 -0
  379. package/dist/workspace/computer-kept.js +147 -0
  380. package/dist/workspace/computer-mcp.js +4 -3
  381. package/dist/workspace/computer-ports.d.ts +23 -3
  382. package/dist/workspace/computer-ports.js +115 -5
  383. package/dist/workspace/index.d.ts +1 -2
  384. package/dist/workspace/index.js +1 -2
  385. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  386. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  387. package/dist/workspace/resolve-computer.d.ts +15 -3
  388. package/dist/workspace/resolve-computer.js +10 -7
  389. package/dist/workspace/revision-skills.d.ts +6 -2
  390. package/dist/workspace/revision-skills.js +12 -5
  391. package/dist/workspace/run-end-computers.d.ts +30 -0
  392. package/dist/workspace/run-end-computers.js +137 -0
  393. package/dist/workspace/run-tools.d.ts +28 -29
  394. package/dist/workspace/run-tools.js +29 -30
  395. package/dist/wrap-up.d.ts +19 -5
  396. package/dist/wrap-up.js +31 -4
  397. package/package.json +13 -9
  398. package/skills/agentrun-serve/SKILL.md +248 -10
  399. package/templates/README.md +117 -23
  400. package/templates/TOOLS.md +168 -0
  401. package/templates/code-review/agent.md +18 -4
  402. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  403. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  404. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  405. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  406. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  407. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  408. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  409. package/templates/code-review/skills/review/DEEP.md +2 -2
  410. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  411. package/templates/code-review/skills/review/SKILL.md +7 -3
  412. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  413. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  414. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  415. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  416. package/dist/console/assets/index-CjqQirbo.css +0 -1
  417. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  418. package/dist/host-calls.d.ts +0 -20
  419. package/dist/host-calls.js +0 -12
  420. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  421. package/dist/runner/adapters/pi-computer.js +0 -51
  422. package/dist/workspace/computer-script.d.ts +0 -53
  423. package/dist/workspace/computer-script.js +0 -172
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";
@@ -17,7 +29,7 @@ import { agentRevision, agentRevisions, agentView, commitAgent, createAgent, eta
17
29
  import { WORKFLOW_ADAPTERS } from "./runner/workflow-adapters.js";
18
30
  import { DECISION_ADAPTER, decisionsOf, FAUX_JEV_ENV, FAUX_OPENROUTER_ENV, FAUX_PARALLEL_ENV, fauxFetch } from "./decisions.js";
19
31
  import { FAUX_WEB_ENV } from "./web-fetch-direct.js";
20
- import { FAUX_MONID_ENV, MONID_KEY_ENV, pinMonid } from "./monid.js";
32
+ import { FAUX_MONID_ENV, MONID_KEY_ENV, pinMonid, PRICED_BY_USAGE } from "./monid.js";
21
33
  import { FAUX_EXA_ENV } from "./exa-keyless.js";
22
34
  import { FAUX_BROWSER_ENV, NODE_TOOLS, shellTools, toolingOf, toolOf, toolsView } from "./tools.js";
23
35
  import { ApiError, invalid, sentence, unsupported } from "./errors.js";
@@ -32,7 +44,8 @@ import { HarnessInstall, installDirOf, NPM_STOP_GRACE_MS, npmInstall } from "./h
32
44
  import { healthOf, hostMemory, maxRunsOf, MIN_FREE_MIB, runsThatFit } from "./host.js";
33
45
  import { IMPORT_ASKED } from "./import.js";
34
46
  import { answerStoreCall } from "./import-proxy.js";
35
- 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";
36
49
  import { agentLearning, learningLog, learningNotes, noteBody, pendingCount, promotable, readNote, secretsShown, sendNote, statusesOf, workflowRevisions, writeNote } from "./learning-routes.js";
37
50
  import { answerLlms, MCP_PATH, mcpEndpoint } from "./mcp.js";
38
51
  import { openapiDocument, servedOpenapi, UNSUPPORTED } from "./openapi.js";
@@ -44,11 +57,12 @@ import { answerPage, byOwnerSession, ConsoleSessions, heldSessions, isJson, over
44
57
  import { hostFix, hostName, loopbackNames } from "./host-check.js";
45
58
  import { computerViewerLink, familyReaches, liveViewerById, liveViewerFor, liveViewerLink, OpenViewers, proxyLiveUpgrade, serveViewerFile, viewerAnswers } from "./browser-live.js";
46
59
  import { browserHandBack, handBackTarget } from "./browser-commands.js";
47
- import { computerView, sessionIn } from "./computer-view.js";
60
+ import { computerView, lapsedOf, sessionIn } from "./computer-view.js";
61
+ import { readKept } from "./workspace/computer-kept.js";
48
62
  import { liveReachOf } from "./live-reach.js";
49
63
  import { screenWaitEnded } from "./browser-wait-ended.js";
50
64
  import { durationMs, logLine } from "./print.js";
51
- 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";
52
66
  import { factsOverStore, momentOverStore, summaryOverStore, timelineOverStore, viewOverStore, withheldOverStore } from "./store-view.js";
53
67
  import { HELD_WAITS } from "./runner/journal-kinds.js";
54
68
  import { servedTimelineRows } from "./run-timeline-served.js";
@@ -67,10 +81,11 @@ import { analytics as analyticsOverStore } from "./store-reads/analytics.js";
67
81
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
68
82
  import { openStore, sealRunMcpAuth, StoreOwned, storeTarget } from "./store/index.js";
69
83
  import { answerOf, logged } from "./agents.js";
70
- import { LABEL_MAX, openFeedbackRound } from "./runner/feedback-round.js";
84
+ import { keepGrade } from "./runner/feedback-round.js";
71
85
  import { FINAL_STATES, RUN_CHANGES_PAGE } from "./store/store.js";
72
- import { GRADE_SOURCES, gradeView, promotionsOf, promotionsShown, putGrade } from "./learn/promote.js";
86
+ import { GRADE_SOURCES, GRADES_KEPT, gradeView, LABEL_MAX, promotionsOf, promotionsShown } from "./learn/promote.js";
73
87
  import { runModelRef } from "./model.js";
88
+ import { REDACTED } from "./secret-cut.js";
74
89
  // The v2 run statuses, as the run view names them (run-view.ts Status), for the list filter's validation. */
75
90
  const STATUSES = ["queued", "working", "paused", "input_required", "completed", "failed", "cancelled"];
76
91
  import { runLines } from "./usage-lines.js";
@@ -79,10 +94,10 @@ import { dockerComputerRefusal, dockerPathsOf, FAUX_MOUNTINFO_ENV, remoteDockerO
79
94
  import { dockerDaemonCheck } from "./docker-daemon.js";
80
95
  import { hostAddressesOnce, noHostAddresses, unionOf } from "./docker-host-addresses.js";
81
96
  import { DOCUMENTS_ENV } from "./pdf-pages.js";
82
- import { CAP_MODES } from "./cap.js";
83
97
  import { blockersOf, CODE_NODES_ENV, issueOf, NOT_SET_UP } from "./runnable.js";
84
98
  import { hostSecrets, SECRET_NAMES, secret, withSecrets } from "./secrets.js";
85
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";
86
101
  import { bootSealKey, withSealKey } from "./seal-key.js";
87
102
  import { ServerLockHeldError, takeServerLock } from "./server-lock.js";
88
103
  import { DRAIN_TIMEOUT } from "./runner/beside.js";
@@ -99,6 +114,7 @@ import { SIGN_INS_DIR, vendorsOver } from "./sign-ins.js";
99
114
  import { signInsOverStore } from "./sign-ins-store.js";
100
115
  import { boundTool, MCP_AUTH_TYPES, marked, mcpAuthOf, nameOf as mcpNameOf } from "./mcp-probe.js";
101
116
  import { composioForget, composioNote, composioSave, composioTools } from "./composio-preset.js";
117
+ import { ComposioTriggers } from "./composio-triggers.js";
102
118
  import { mcpServersOverStore } from "./mcp-servers-store.js";
103
119
  import { getMcpServer, listMcpServers } from "./mcp-store.js";
104
120
  import { privateHostsRoute } from "./mcp-private-hosts.js";
@@ -119,10 +135,10 @@ import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
119
135
  import { webhook } from "./trigger-webhook.js";
120
136
  import { SCHEME_NAMES } from "./trigger-signatures.js";
121
137
  import { permissionFrom, pinnedEffect, toolEffect } from "./tool-gate.js";
122
- import { isMcpWildcard, mcpNameOf as mcpToolOf, mcpToolName, monidDroppedWords, monidNameOf } from "./tool-names.js";
123
- import { wireName } from "./catalog.js";
124
- import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, PAYLOAD_KEPT_BYTES, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
125
- import { applyBodyOf, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, serversFor, TemplateRegistry } from "./templates.js";
138
+ import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
139
+ import { CATCHUP_WINDOW_S, FAILURES_TO_PAUSE, HISTORY_KEPT, MIN_EVERY_S, SOURCE_KINDS, TARGET_KINDS, Triggers } from "./triggers.js";
140
+ import { PAYLOAD_KEPT_BYTES } from "./trigger-adapter.js";
141
+ import { applyBodyOf, choiceUnrunnable, COMPOSIO_TRIGGER_FIX, composioTriggerSkipped, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, notSetUpYet, serversFor, TemplateRegistry } from "./templates.js";
126
142
  import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
127
143
  import { templateInstallLink, templateLink } from "./console-links.js";
128
144
  import { GITHUB_HOSTS } from "./template-source.js";
@@ -134,12 +150,15 @@ import { readApprovers, writeApprovers } from "./server-approvers.js";
134
150
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
135
151
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
136
152
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
137
- import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runViewedKind } from "./computer-routes.js";
153
+ import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
138
154
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
139
155
  import { createAttachRoutes, pairedView } from "./computer-attach.js";
140
156
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
141
157
  import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
158
+ import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
142
159
  import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
160
+ import { noAccount, openAccount } from "./email/account.js";
161
+ import { emailRoute } from "./email/routes.js";
143
162
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
144
163
  import { computerOfPlace } from "./computer-setting.js";
145
164
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
@@ -206,6 +225,25 @@ const digest = (text) => createHash("sha256").update(text).digest();
206
225
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
207
226
  const SESSION_S = SESSION_MS / 1000;
208
227
  export const ROUTES = [
228
+ { method: "GET", pattern: /^\/observations$/, name: "getObservations" },
229
+ { method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
230
+ { method: "POST", pattern: /^\/connectors\/enrollment$/, name: "enrollRemoteConnector" },
231
+ { method: "POST", pattern: /^\/connectors$/, name: "registerRemoteConnector" },
232
+ { method: "DELETE", pattern: /^\/connectors\/([^/]+)$/, name: "revokeRemoteConnector" },
233
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/import$/, name: "importRemoteTarget" },
234
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/history$/, name: "importRemoteHistory" },
235
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/poll$/, name: "pollRemoteConnector" },
236
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/events$/, name: "remoteCommandEvents" },
237
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/complete$/, name: "completeRemoteCommand" },
238
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/sdk-runs$/, name: "startSdkRun" },
239
+ { method: "GET", pattern: /^\/sdk-runs\/([^/]+)$/, name: "getSdkRun" },
240
+ { method: "POST", pattern: /^\/sdk-runs\/([^/]+)\/events$/, name: "sdkRunEvents" },
241
+ { method: "POST", pattern: /^\/sdk-runs\/([^/]+)\/complete$/, name: "completeSdkRun" },
242
+ { method: "POST", pattern: /^\/native\/discover$/, name: "discoverNative" },
243
+ { method: "POST", pattern: /^\/native\/connect$/, name: "connectNative" },
244
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/native$/, name: "getNative" },
245
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/native\/verify$/, name: "verifyNative" },
246
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/native\/disconnect$/, name: "disconnectNative" },
209
247
  { method: "GET", pattern: /^\/capabilities$/, name: "getCapabilities" },
210
248
  { method: "GET", pattern: /^\/openapi\.json$/, name: "getOpenapi" },
211
249
  // Answered here only with accounts off: with accounts on, the owner's routes answer it before any route (ownerRoute).
@@ -288,12 +326,27 @@ export const ROUTES = [
288
326
  { method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
289
327
  { method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
290
328
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
329
+ // The server's email account (email/routes.ts): the owner's session's alone, its password in no answer.
330
+ { method: "GET", pattern: /^\/settings\/email$/, name: "getEmailAccount" },
331
+ { method: "PUT", pattern: /^\/settings\/email$/, name: "saveEmailAccount" },
332
+ { method: "DELETE", pattern: /^\/settings\/email$/, name: "deleteEmailAccount" },
333
+ { method: "POST", pattern: /^\/settings\/email\/test$/, name: "testEmailAccount" },
334
+ { method: "GET", pattern: /^\/settings\/chatgpt$/, name: "getChatGPTSignIn" },
335
+ { method: "DELETE", pattern: /^\/settings\/chatgpt$/, name: "signOutChatGPT" },
336
+ { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in$/, name: "startChatGPTSignIn" },
337
+ { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in\/finish$/, name: "finishChatGPTSignIn" },
291
338
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
292
339
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
293
340
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
294
341
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
295
342
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
296
343
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio$/, name: "saveComposioServer" },
344
+ // A saved Composio server's triggers (composio-triggers.ts): its toolkit's events, its triggers and their state on
345
+ // Composio, and the project's webhook subscription (its secret rotated, or the subscription deleted: secret writes).
346
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/events$/, name: "listComposioEvents" },
347
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/triggers$/, name: "listComposioTriggers" },
348
+ { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/rotate-secret$/, name: "rotateComposioSecret" },
349
+ { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/subscription$/, name: "deleteComposioSubscription" },
297
350
  { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
298
351
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
299
352
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/oauth\/start$/, name: "startMcpOAuth" },
@@ -324,7 +377,8 @@ export const ROUTES = [
324
377
  { method: "DELETE", pattern: /^\/templates\/([^/]+)$/, name: "deleteTemplate" },
325
378
  { method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
326
379
  // Answered before the bearer check: the request's signature is its credential.
327
- { method: "POST", pattern: /^\/hooks\/([^/]+)$/, name: "receiveHook" },
380
+ // A source that keeps its key per scope (Composio's projects) is served at /hooks/{source}/{scope}.
381
+ { method: "POST", pattern: /^\/hooks\/([^/]+)(?:\/([^/]+))?$/, name: "receiveHook" },
328
382
  { method: "GET", pattern: /^\/integrations\/github$/, name: "getGitHubConnection" },
329
383
  { method: "DELETE", pattern: /^\/integrations\/github$/, name: "disconnectGitHub" },
330
384
  { method: "POST", pattern: /^\/integrations\/github\/connect$/, name: "connectGitHub" },
@@ -351,6 +405,8 @@ export const ROUTES = [
351
405
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
352
406
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions$/, name: "listLearnedWorkflowRevisions" },
353
407
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
408
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays$/, name: "startLearnedWorkflowReplay" },
409
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays\/([^/]+)$/, name: "getLearnedWorkflowReplay" },
354
410
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
355
411
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
356
412
  ];
@@ -360,15 +416,19 @@ export const ROUTES = [
360
416
  * kept plane's (a run from before the plane names none, and is Browserbase's where it grants the tool) checked again as a
361
417
  * launch would be; off, saying why, where it has none or its browser resolves unavailable here. Where the agent's
362
418
  * computer is a browser, that browser, whose keys are the computer's (checked at the run's start), never the plane's.
419
+ * A run whose agent's computer is a sandbox (`own`, its revision's kind) and has no browser has a computer with no
420
+ * screen: off says so, never that its agent has none; its browser, where it has the tool, is its view, and why that
421
+ * browser is unavailable is said as for any run.
363
422
  * TODO: the agent's own `computer: {kind, provider?}` setting once definitions carry it (desktop, phone). */
364
- function computerOf(kept, env, family = "computer") {
423
+ function computerOf(kept, env, family = "computer", own) {
365
424
  if (kept === ON_COMPUTER)
366
425
  return { kind: "browser" };
367
426
  const browser = kept === undefined ? undefined : recheckPlane({ browser: kept }, env).browser;
368
427
  if (browser === undefined)
369
- return { off: family === "browser" ? "this run's agent has no browser tool" : "this run's agent has no computer" };
428
+ return { off: family === "browser" ? "this run's agent has no browser tool" : own === "sandbox" ? SANDBOX_NO_SCREEN : "this run's agent has no computer" };
370
429
  return isUnavailable(browser) ? { off: whyUnavailable(browser) } : { kind: "browser" };
371
430
  }
431
+ const SANDBOX_NO_SCREEN = "A sandbox has no screen: what the agent runs in it is on the timeline.";
372
432
  /** The run's kept browser vendor, over the store, as computerOf reads it: the vendor its launch plane resolved at start
373
433
  * (the same source the runner's claim reads), normalized to the vendor name (keptVendor) so recheckPlane re-resolves it as
374
434
  * a vendor, not a stored no-key sentinel; with no browser in the plane, the default vendor when the run's revision grants
@@ -420,7 +480,18 @@ export function offersEnvOf(env) {
420
480
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
421
481
  * saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
422
482
  * the offers probed again, never shown. */
423
- const offersInputs = (env) => SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]);
483
+ const offersInputs = (env) => [...SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]), planOf(env)?.state, planOf(env)?.models.join(" ")];
484
+ /** 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. */
485
+ async function planStep(step) {
486
+ try {
487
+ return await step();
488
+ }
489
+ catch (error) {
490
+ if (error instanceof PlanSignInRefused)
491
+ throw new ApiError("bad_request", error.message);
492
+ throw error;
493
+ }
494
+ }
424
495
  async function needsOf(env) {
425
496
  const chosen = await chooseModel(env, undefined);
426
497
  if ("why" in chosen)
@@ -559,6 +630,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
559
630
  idempotency_ttl_s: IDEMPOTENCY_TTL_S,
560
631
  input_wait_s: null,
561
632
  max_cost_usd: null,
633
+ // The most requests on free models a run makes (AGENTRUN_FREE_MODEL_REQUESTS, else 60): each costs $0, so the
634
+ // dollar cap cannot stop them, and this does (the kernel cap's free.ts). ChatGPT-plan requests don't count.
635
+ free_model_requests: freeModelRequestsOf(env),
562
636
  },
563
637
  };
564
638
  }
@@ -615,6 +689,8 @@ export async function startServe(options) {
615
689
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
616
690
  const learning = learningOf(process.env, options.learning);
617
691
  const learningBudget = learningBudgetOf(process.env, options.learningBudget);
692
+ // A limit on a run's requests on free models that is no whole number above 0 stops the start, naming its variable.
693
+ freeModelRequestsOf(process.env);
618
694
  const minFreeMib = process.env.AGENTRUN_MIN_FREE_MB ? Number(process.env.AGENTRUN_MIN_FREE_MB) : MIN_FREE_MIB;
619
695
  if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
620
696
  throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
@@ -707,11 +783,15 @@ async function startHolding(options, data, checked, stops) {
707
783
  warn: (message) => void process.stderr.write(`agentrun-serve: ${message}\n`),
708
784
  ...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
709
785
  }), (error) => onSqlite && error instanceof StoreOwned, replacedUntil, waitingForReplaced);
710
- stops.push(() => store.close());
786
+ let stopObservationRetention = async () => undefined;
787
+ stops.push(async () => { await stopObservationRetention(); await store.close(); });
711
788
  // The packages served: the bundled ones, read and checked before the start, and those imported here, which the store
712
789
  // keeps and are checked again as they load (template-import.ts). One that no longer checks is left out, said in the log.
713
790
  const registry = new TemplateRegistry(templates);
714
791
  await loadImported({ registry, store }, (id, why) => log?.(logLine("template_import_skipped", { template: id, why })));
792
+ stopObservationRetention = await maintainObservations(new Observations(store), {
793
+ onError: () => { process.stderr.write("agentrun-serve: observation retention failed; retrying on the next sweep\n"); },
794
+ });
715
795
  // The person's own computers paired with this server (computer-attach.ts): their live sockets are this process's hub,
716
796
  // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
717
797
  // store is refused above (its owner lock).
@@ -798,7 +878,12 @@ async function startHolding(options, data, checked, stops) {
798
878
  // settings, caps; a save or delete of a key, env and caps, and the offers only when what they are made from changed,
799
879
  // which no tool key is. So a write answers at once, and capabilities, save checks and run checks after it see it, with
800
880
  // no restart and no request opening the file. The offers are probed once saved keys are read (below), at the start.
801
- let env = own(withSecrets(base, "all", storedKeys));
881
+ // The ChatGPT sign-in, sealed in the store: on every reading of env (chatgpt-plan.ts withPlan), so a plan model runs
882
+ // 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.
883
+ 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() });
884
+ await plan.load();
885
+ stops.push(async () => plan.close());
886
+ let env = withPlan(own(withSecrets(base, "all", storedKeys)), plan);
802
887
  let offers;
803
888
  let caps;
804
889
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -830,7 +915,7 @@ async function startHolding(options, data, checked, stops) {
830
915
  const keysChanged = async () => {
831
916
  // 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
832
917
  // serverSecrets live, store-view), so a key change needs no cache invalidation here.
833
- env = own(withSecrets(base, "all", storedKeys));
918
+ env = withPlan(own(withSecrets(base, "all", storedKeys)), plan);
834
919
  const mine = ++needsAsked;
835
920
  const next = await needsOf(env);
836
921
  if (mine === needsAsked)
@@ -841,6 +926,12 @@ async function startHolding(options, data, checked, stops) {
841
926
  else
842
927
  await probe("key");
843
928
  };
929
+ /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again. */
930
+ const planNow = async () => {
931
+ const was = plan.state;
932
+ if ((await plan.load()).state !== was)
933
+ await keysChanged();
934
+ };
844
935
  // The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
845
936
  // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
846
937
  // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
@@ -1023,6 +1114,16 @@ async function startHolding(options, data, checked, stops) {
1023
1114
  };
1024
1115
  ({ 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`))));
1025
1116
  secretStores.add("server", () => [token]);
1117
+ // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1118
+ // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1119
+ const emailPasswords = new Set();
1120
+ const heldEmailPassword = async () => {
1121
+ const password = (await openAccount(store, sealKey).catch(() => undefined))?.password;
1122
+ if (password)
1123
+ emailPasswords.add(password);
1124
+ };
1125
+ await heldEmailPassword();
1126
+ secretStores.add("email", () => [...emailPasswords]);
1026
1127
  // Each agent's saved sign-ins, over the one store (module A, sign-ins-store): the vendor's calls on the server's keys
1027
1128
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
1028
1129
  // (a live run's sign_in_handed) and who was handed it, so this takes no `holds`/`handedTo` callback — one store, one lock.
@@ -1066,11 +1167,16 @@ async function startHolding(options, data, checked, stops) {
1066
1167
  const lock = options.harnessLocks?.[entry.id];
1067
1168
  // npm past its SIGTERM's grace (it waits on a tarball once it writes): killed, and the line says so.
1068
1169
  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` }));
1069
- return [entry.id, new HarnessInstall(entry, installDirOf(data, entry.id), pins, (entry, dir, pins, signal) => npmInstall(entry, dir, pins, { signal, onKilled, ...(lock ? { lock } : {}) }), (ms) => {
1170
+ 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) => {
1070
1171
  log?.(logLine("harness_installed", { harness: entry.id, ms, dir: installDirOf(data, entry.id) }));
1071
1172
  void probe(`${entry.id}_installed`).catch(() => undefined);
1072
1173
  })];
1073
1174
  }));
1175
+ // Each harness found installed as this server starts has what earlier installs left beside it swept (HarnessInstall
1176
+ // needed): the point sure to come after an install that could not remove one (a crashed server's npm still writing in
1177
+ // it), since no install runs again until the pin changes. Not waited for; the close waits for it (install.stop).
1178
+ for (const install of Object.values(installs))
1179
+ void install.needed().catch(() => undefined);
1074
1180
  // A capped start prices each OpenRouter Decisions model a workflow pins (runnable.ts) from OpenRouter's public catalog,
1075
1181
  // read once for this server (and again after a read that failed), through the faux one under --faux.
1076
1182
  let pricing;
@@ -1089,7 +1195,7 @@ async function startHolding(options, data, checked, stops) {
1089
1195
  // no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
1090
1196
  // needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
1091
1197
  // reads launch.model alone).
1092
- const modelOf = (_entry, revision) => runModelRef(env, revision);
1198
+ const modelOf = (_entry, revision) => nativeOf(revision.body) ? Promise.resolve(undefined) : runModelRef(env, revision);
1093
1199
  const startDeps = {
1094
1200
  runBodyIssues,
1095
1201
  boundRepos: async (agentId) => bindingOf(await store.triggers.list(agentId), agentId),
@@ -1153,12 +1259,13 @@ async function startHolding(options, data, checked, stops) {
1153
1259
  },
1154
1260
  shown: () => secretsShown(serverSecrets(), { local: true }),
1155
1261
  };
1156
- /** What a learning batch's loop reads of a run, from its view. */
1262
+ /** 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
1263
+ * no "at most", so a view cost marked `upper_bound` reads null there, as the run's stored cost does (RunRow.costUsd). */
1157
1264
  const batchRunView = async (runId) => {
1158
1265
  const v = (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())));
1159
1266
  if (!v)
1160
1267
  return undefined;
1161
- 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 };
1268
+ 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 };
1162
1269
  };
1163
1270
  // 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
1164
1271
  // state is the store's settings, so a batch still running when the server stopped takes up again as it starts. Its reads
@@ -1248,7 +1355,7 @@ async function startHolding(options, data, checked, stops) {
1248
1355
  // shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
1249
1356
  // 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
1250
1357
  // from its journal, which keeps what the run said whole.
1251
- timelineRows: (forStore, runId, context) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses }, forStore, runId, context),
1358
+ timelineRows: (forStore, runId, context, calls) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses }, forStore, runId, context, calls),
1252
1359
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1253
1360
  });
1254
1361
  const triggerDeps = {
@@ -1385,7 +1492,9 @@ async function startHolding(options, data, checked, stops) {
1385
1492
  clock: options.triggerClock,
1386
1493
  ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1387
1494
  adapters,
1388
- 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),
1495
+ 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),
1496
+ // The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
1497
+ credentials: async (kind) => (kind === "email" ? openAccount(store, sealKey) : undefined),
1389
1498
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1390
1499
  // The trigger target policy (what a trigger may start or message, and in what words it is refused) is the one store's
1391
1500
  // (trigger-targets.ts, over the run write half and the run view): targetIssues, start, message, statusOf, runOf. The
@@ -1393,6 +1502,17 @@ async function startHolding(options, data, checked, stops) {
1393
1502
  ...targets,
1394
1503
  settings: (adapterId) => triggerSettings.get(adapterId),
1395
1504
  notify: (failed, key) => webhooks.emitTrigger(failed, key),
1505
+ // A Composio trigger's instance, and the project's subscription, are made and kept on Composio with its server's key.
1506
+ upstream: (kind) => (kind === "composio" ? composioTriggers : undefined),
1507
+ });
1508
+ const composioTriggers = new ComposioTriggers({
1509
+ control: options.composioControl ?? {},
1510
+ ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1511
+ sealed: triggerSettings.get("composio"),
1512
+ credential: (name, refusal) => mcpServers.composioOf(name, refusal),
1513
+ holders: () => triggers.ofKind("composio"),
1514
+ signal: stopping.signal,
1515
+ say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1396
1516
  });
1397
1517
  // A repair of the GitHub installations (below) stops before the triggers close, in a start that fails as in close.
1398
1518
  stops.push(() => githubConnect.close());
@@ -1509,7 +1629,7 @@ async function startHolding(options, data, checked, stops) {
1509
1629
  throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
1510
1630
  return Buffer.concat(chunks);
1511
1631
  }
1512
- async function bodyOf(req) {
1632
+ async function bodyOf(req, max = MAX_BODY) {
1513
1633
  // Read once: the secret-write check reads a registered operation's body before its route does (secret-writes.ts).
1514
1634
  const read = bodies.get(req);
1515
1635
  if (read !== undefined)
@@ -1517,7 +1637,7 @@ async function startHolding(options, data, checked, stops) {
1517
1637
  const type = String(req.headers["content-type"] ?? "");
1518
1638
  if (!type.startsWith("application/json"))
1519
1639
  throw new ApiError("unsupported_media_type", "the body must be application/json");
1520
- const bytes = await bytesOf(req);
1640
+ const bytes = await bytesOf(req, max);
1521
1641
  let value;
1522
1642
  try {
1523
1643
  value = JSON.parse(bytes.toString("utf8") || "null");
@@ -1537,24 +1657,19 @@ async function startHolding(options, data, checked, stops) {
1537
1657
  const revision = (entry ?? (await needAgent(id))).revision;
1538
1658
  if (revision?.kind !== "agentic")
1539
1659
  return { tools: [], gated: {}, deniedBy: {} };
1540
- const [{ learnedDraftTools, mcpGrantsListed }, { permissionFrom }, { learnedAskFits }] = await Promise.all([import("./tools.js"), import("./tool-gate.js"), import("./learned-workflow.js")]);
1660
+ const [{ learnedDraftTools }, { permissionFrom }] = await Promise.all([import("./tools.js"), import("./tool-gate.js")]);
1541
1661
  const server = settings.get();
1542
1662
  // The revision row's body is the agentic body JSON (store-backed RevisionRow types it as unknown).
1543
1663
  const body = revision.body;
1544
- // A server's wildcard grant read as the tools its server lists now (tools.ts mcpGrantsListed, LS-07).
1545
- const rows = (body.tools ?? []).some(isMcpWildcard) ? await listMcpServers(store).catch(() => []) : [];
1546
- const listed = new Map(rows.map((row) => [row.name, (row.tools ?? []).flatMap((tool) => (typeof tool?.name === "string" ? [tool.name] : []))]));
1547
1664
  const gate = (name) => permissionFrom(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask");
1548
1665
  // `deniedBy`: where each deny was set (the agent's tool settings, the server's), which a refused draft's words name.
1549
- 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) });
1550
- // #2424's card rule (learnedAskFits): a restored draft whose ask-set MCP tools would not all show is refused.
1551
- const ask = { asked, fits: learnedAskFits };
1666
+ const { tools, gated, deniedBy } = learnedDraftTools(body.tools ?? [], (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
1552
1667
  // A draft's decision nodes (LS-07), as a run's learning end checks them: on this server's decision providers (its
1553
1668
  // keys, saved ones among them: env), each held to the gate by its bare id; deny alone refuses one.
1554
1669
  const [{ decisionProvidersIn }, { DECISION_PROVIDER_KEYS }] = await Promise.all([import("./decisions.js"), import("./tool-plane.js")]);
1555
1670
  const providers = await decisionProvidersIn(env);
1556
1671
  if (!providers)
1557
- return { tools, gated, deniedBy, ask };
1672
+ return { tools, gated, deniedBy };
1558
1673
  const decided = {};
1559
1674
  const decisionDeniedBy = {};
1560
1675
  for (const provider of DECISION_PROVIDER_KEYS) {
@@ -1565,7 +1680,7 @@ async function startHolding(options, data, checked, stops) {
1565
1680
  if (permission === "deny")
1566
1681
  decisionDeniedBy[provider] = from;
1567
1682
  }
1568
- return { tools, gated, deniedBy, ask, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1683
+ return { tools, gated, deniedBy, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1569
1684
  }
1570
1685
  async function needAgent(id) {
1571
1686
  const entry = ID.test(id) ? await agents.get(id) : null;
@@ -1573,13 +1688,24 @@ async function startHolding(options, data, checked, stops) {
1573
1688
  throw new ApiError("not_found", `no agent ${id}`);
1574
1689
  return entry;
1575
1690
  }
1691
+ /** The agent `id` (needAgent), refused when it is archived (409 agent_not_runnable): every route that starts its runs,
1692
+ * a person's start (createRun) and a replay's (startLearnedWorkflowReplay), asks this before it reserves or writes anything. */
1693
+ async function needRunnableAgent(id) {
1694
+ const entry = await needAgent(id);
1695
+ if (entry.agent.archivedAt)
1696
+ 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() } });
1697
+ return entry;
1698
+ }
1576
1699
  /** An agent view's extra fields (agents-store agentView): its saved sign-ins, its learning count, and its run counts.
1577
1700
  * The run counts read the store's runs (store-reads/runs.ts listRuns): `count` is every run the agent has, `live` those
1578
1701
  * still running (runReadState 'running': queued, running or parked), the same numbers the file-backed view showed. */
1579
1702
  const agentExtra = async (entry) => {
1580
1703
  const learning = await learningOfAgent(entry);
1704
+ const native = nativeOf(entry.revision?.body);
1705
+ const nativeStatus = native?.remote ? await new RemoteConnectors(store).status(native) : undefined;
1581
1706
  const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
1582
1707
  return {
1708
+ ...(nativeStatus ? { nativeStatus } : {}),
1583
1709
  signIns: await signIns.view(entry.agent.id),
1584
1710
  ...(learning ? { learning } : {}),
1585
1711
  runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length },
@@ -1663,6 +1789,28 @@ async function startHolding(options, data, checked, stops) {
1663
1789
  * starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
1664
1790
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
1665
1791
  async function runnable(revision, place, { capped = false } = {}) {
1792
+ if (sdkOf(revision.body))
1793
+ 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.");
1794
+ const native = nativeOf(revision.body);
1795
+ if (native) {
1796
+ const overrides = nativeModelOverrides(revision.body);
1797
+ if (overrides.length)
1798
+ 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 })) });
1799
+ const execution = nativeExecutionOverrides(revision.body);
1800
+ if (execution.length)
1801
+ 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 })) });
1802
+ if ((revision.body.maxToolCalls ?? 0) > 0)
1803
+ 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 }] });
1804
+ if (!native.remote && (options.apiOnly || options.publicUrl || !isLoopback(host)))
1805
+ 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.");
1806
+ if (capped)
1807
+ 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.");
1808
+ if (native.remote)
1809
+ await new RemoteConnectors(store).assertReady(native);
1810
+ else
1811
+ await launchNative(native);
1812
+ return;
1813
+ }
1666
1814
  const shape = { ...shapeOf(revision), place, ...(revision.body.place ? {} : { unnamed: true }) };
1667
1815
  // An agentic revision's MCP tools are checked as its save pinned them (its pin, never the server's listing now), for
1668
1816
  // a server still saved here; a granted tool its pin does not hold is said first, with how to pin it.
@@ -1688,7 +1836,8 @@ async function startHolding(options, data, checked, stops) {
1688
1836
  return meta ? { ...tool, grantable: false, reason: meta.reason } : tool;
1689
1837
  });
1690
1838
  };
1691
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, decisionPrice });
1839
+ const monid = revision.monidPin ?? undefined;
1840
+ const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice });
1692
1841
  if (!blockers.length)
1693
1842
  return;
1694
1843
  const message = blockers.map((b) => b.message).join(" ");
@@ -1782,12 +1931,23 @@ async function startHolding(options, data, checked, stops) {
1782
1931
  return pin ? { ...revision, mcpPin: pin } : revision;
1783
1932
  }
1784
1933
  /** A definition being saved: refused (422 by field) when it can never run here; else what this host still lacks, and
1785
- * what the save stamps on it (its MCP pin, mcpListingOf; its monid pin, on its body). A revision that names no place is
1786
- * checked where it would run (fallbackPlace). */
1934
+ * its pins (mcpListingOf, monidPinOf), each carrying from `previous` what its grants did not change. A revision that
1935
+ * names no place is checked where it would run (fallbackPlace). */
1787
1936
  async function saveable(revision, previous) {
1788
1937
  // The store's NewRevision keeps the revision's fields under `body` (AgenticBody|WorkflowBody); build the flat shape the
1789
1938
  // host checks (runnable.ts RevisionShape) from it, as shapeOf does for a run's Revision.
1790
1939
  const body = revision.body;
1940
+ if (nativeOf(body)) {
1941
+ const overrides = nativeModelOverrides(body);
1942
+ if (overrides.length)
1943
+ throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
1944
+ const execution = nativeExecutionOverrides(body);
1945
+ if (execution.length)
1946
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
1947
+ return { warnings: [], stamp: {} };
1948
+ }
1949
+ if (sdkOf(body))
1950
+ return { warnings: [], stamp: {} };
1791
1951
  // 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.
1792
1952
  const install = revision.kind === "agentic" ? installs[harnessOfBody(body)] : undefined;
1793
1953
  if (install) {
@@ -1795,51 +1955,44 @@ async function startHolding(options, data, checked, stops) {
1795
1955
  }
1796
1956
  const named = (revision.kind === "agentic" ? { kind: "agentic", ...body } : workflowShape(body));
1797
1957
  const shape = named.place ? named : { ...named, place: fallbackPlace(named.kind, named.tools ?? []), unnamed: true };
1798
- const listing = await mcpListingOf(revision, previous);
1958
+ const listing = await mcpListingOf(revision, previous?.mcpPin);
1799
1959
  const mcp = listing.tools;
1800
- const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp });
1960
+ const { monid, warnings: usage = [] } = (await monidPinOf(revision, previous)) ?? {};
1961
+ const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp, monid });
1801
1962
  // 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
1802
1963
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
1803
1964
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
1804
1965
  if ((body.maxCostUsd ?? 0) > 0) {
1805
1966
  const key = (b) => `${b.field}\n${b.message}`;
1806
- const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, shellOf, offers, mcp })).map(key));
1807
- const capped = await blockersOf(env, shape, {}, { capped: true, boxes: boxOffers, computerReady, shellOf, offers, mcp, decisionPrice });
1967
+ const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, shellOf, offers, mcp, monid })).map(key));
1968
+ const capped = await blockersOf(env, shape, {}, { capped: true, capUsd: body.maxCostUsd, boxes: boxOffers, computerReady, shellOf, offers, mcp, monid, decisionPrice });
1808
1969
  // A model with no price (`unpriced`) is a setting this host fixes (AGENT_MODEL_PRICE): a warning, as it is; the
1809
- // agent saves and updates, and only a run under the cap is refused (409). A tool's pick a cap rules out refuses it.
1970
+ // agent saves and updates, and only a run under the cap is refused (409). So is a cap below what the model needs for
1971
+ // one more step and an answer (`short`): the agent saves, and its runs wrap up at their first tool call. A tool's
1972
+ // pick a cap rules out refuses it.
1810
1973
  const added = capped.filter((b) => !plain.has(key(b)));
1811
- blockers.push(...added.filter((b) => b.unpriced));
1812
- 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 })));
1974
+ blockers.push(...added.filter((b) => b.unpriced || b.short));
1975
+ 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 })));
1813
1976
  }
1814
1977
  const never = blockers.filter((b) => !b.host);
1815
1978
  if (never.length)
1816
1979
  throw invalid(never.map(issueOf));
1817
- // Its monid grants pinned against what monid lists now, on this server's monid key (monid.ts pinMonid): the pin is
1818
- // stamped on the revision's body, and its runs read it, never monid's listing. A grant monid does not list is refused
1819
- // here. An endpoint a wildcard left out (priced by usage: monid.ts unboundedWords) is a warning at the wildcard's grant.
1820
- const leftOut = [];
1821
- if (revision.kind === "agentic") {
1822
- const send = await checkFetch("monid");
1823
- // The key as the server reads it (env: what it was started with, its handed secrets and its saved keys).
1824
- const pinned = await pinMonid(body.tools ?? [], { key: env[MONID_KEY_ENV]?.trim(), fetch: send ?? (async () => { throw new Error("no fake of monid's API under faux"); }), signal: stopping.signal });
1825
- if (pinned && "refused" in pinned)
1826
- throw invalid(pinned.refused.map(({ tool, message }) => ({ field: (body.tools ?? []).includes(tool) ? `definition.tools[${body.tools.indexOf(tool)}]` : "definition.tools", reason: "not_an_option", message })));
1827
- if (pinned) {
1828
- // Each pinned endpoint's input held to the harness's own measured refusals, as an MCP grant is (runnable.ts
1829
- // mcpGrant): one it would drop or retype refuses the save at the grant that named it, never every run.
1830
- const harness = body.harness ?? DEFAULT_HARNESS;
1831
- const problems = harnessOf(env, harness)?.facts?.schemaProblems;
1832
- const tools = body.tools ?? [];
1833
- const grantOf = (tool) => (tools.includes(tool) ? tools.indexOf(tool) : tools.indexOf(`monid:${monidNameOf(tool)?.provider}/*`));
1834
- const dropped = problems ? Object.entries(pinned.pin).flatMap(([tool, { input }]) => problems(wireName(tool), input).slice(0, 1).map((first) => ({ tool, first }))) : [];
1835
- if (dropped.length)
1836
- throw invalid(dropped.map(({ tool, first }) => ({ field: `definition.tools[${grantOf(tool)}]`, reason: "not_an_option", message: monidDroppedWords(tool, harness, first) })));
1837
- revision.body.monidPin = pinned.pin;
1838
- leftOut.push(...pinned.leftOut.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: "not_an_option", message })));
1839
- }
1840
- }
1841
1980
  const mcpPin = listing.pin();
1842
- return { warnings: [...blockers.map(issueOf), ...leftOut], stamp: mcpPin ? { mcpPin } : {} };
1981
+ return { warnings: [...blockers.map(issueOf), ...usage], stamp: { ...(mcpPin ? { mcpPin } : {}), ...(monid ? { monidPin: monid } : {}) } };
1982
+ }
1983
+ /** An agentic `revision`'s monid pin (monid.ts pinMonid) and a warning per endpoint priced by usage; a grant that
1984
+ * cannot be pinned refuses the save (422). Undefined when it grants none. */
1985
+ async function monidPinOf(revision, previous) {
1986
+ if (revision.kind !== "agentic")
1987
+ return undefined;
1988
+ const tools = revision.body.tools ?? [];
1989
+ const send = await checkFetch("monid");
1990
+ const before = previous?.kind === "agentic" ? { grants: previous.body.tools ?? [], pin: previous.monidPin } : undefined;
1991
+ // The key as the server reads it (env: what it was started with, its handed secrets and its saved keys).
1992
+ 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 } : {}) });
1993
+ if (pinned && "refused" in pinned)
1994
+ throw invalid(pinned.refused.map(({ tool, message }) => ({ field: tools.includes(tool) ? `definition.tools[${tools.indexOf(tool)}]` : "definition.tools", reason: "not_an_option", message })));
1995
+ return pinned && { monid: pinned.pin, warnings: pinned.warnings.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: PRICED_BY_USAGE, message })) };
1843
1996
  }
1844
1997
  /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
1845
1998
  * that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
@@ -1856,6 +2009,28 @@ async function startHolding(options, data, checked, stops) {
1856
2009
  }, "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined, template);
1857
2010
  return { entry, warnings };
1858
2011
  }
2012
+ /** A replay's ports for agent `entry` (runner/promotion.ts askReplay, replayView): its learning folder where this server
2013
+ * 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
2014
+ * makes one now (prepareLaunch: the agent's current revision, model, plane and learning start). */
2015
+ const replayAskOf = (entry) => ({
2016
+ store, agentId: entry.agent.id, context: ctx, log: (line) => void log?.(line),
2017
+ folder: () => learningFolderOf(data, entry.agent.id), shown: () => learningShown(entry.agent.id),
2018
+ launchOf: async (input) => {
2019
+ const { launch, revision } = await prepareLaunch(startDeps, entry, { input });
2020
+ return { launch, revisionId: revision.id };
2021
+ },
2022
+ });
2023
+ /** `act`, its ReplayRefused answered as the API's: 404 not_found, or 409 replay_conflict, in its words. */
2024
+ const replayAsked = async (act) => {
2025
+ try {
2026
+ return await act();
2027
+ }
2028
+ catch (error) {
2029
+ if (error instanceof ReplayRefused)
2030
+ throw new ApiError(error.kind === "missing" ? "not_found" : "replay_conflict", error.message);
2031
+ throw error;
2032
+ }
2033
+ };
1859
2034
  /** Agent `source`'s learned workflow `raw` made into a workflow agent of its own, as POST /agents makes one
1860
2035
  * (createAgentOf: the definition's checks, the workflow's validation and what this host refuses of it). Only an active
1861
2036
  * one, checked again as a restore checks it (learning-routes.ts promotable). Its revision is a workflow revision of the
@@ -1882,7 +2057,6 @@ async function startHolding(options, data, checked, stops) {
1882
2057
  ...(policy.toolSettings ? { tool_settings: policy.toolSettings } : {}),
1883
2058
  ...(policy.approvals === "never" ? { approvals: "never" } : {}),
1884
2059
  ...(policy.maxCostUsd !== undefined ? { max_cost_usd: policy.maxCostUsd } : {}),
1885
- ...(policy.capMode !== undefined ? { cap_mode: policy.capMode } : {}),
1886
2060
  });
1887
2061
  const note = `Made from the learned workflow ${learned.name} of agent ${id}.`;
1888
2062
  // Another promotion (or a create) may take the id between the read and the write: the next one is tried.
@@ -1904,15 +2078,17 @@ async function startHolding(options, data, checked, stops) {
1904
2078
  }
1905
2079
  /** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
1906
2080
  * servers it names (409, nothing made; an MCP server it can do without is skipped, with a warning), then its
1907
- * agent made as POST /agents makes one, granted the MCP tools the owner ticked (grants) alone, each set to allow (a
1908
- * deny the owner set on this server stays, 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
2081
+ * agent made as POST /agents makes one, granted the MCP tools the owner ticked (grants) alone, with no permission written
2082
+ * (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,
2083
+ * 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
1909
2084
  * picks, then each trigger on it as POST /triggers makes one. A trigger refused undoes the apply: the triggers made
1910
2085
  * 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
1911
2086
  * github trigger GitHub is not connected for is skipped instead, with a warning there, and one made is said there. A webhook
1912
2087
  * trigger's secret is not in the answer (the Idempotency-Key record would keep it): POST /triggers/{id}/secret makes one. */
1913
2088
  async function applyTemplate(template, body) {
1914
- const { parameters, grants: asked, servers: picks, model: override, approvals } = applyBodyOf(template, body);
1915
- const missing = template.secrets.filter((name) => !secret(name, storedKeys));
2089
+ const { parameters, grants: asked, servers: picks, model: override, choice, approvals } = applyBodyOf(template, body);
2090
+ // A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made.
2091
+ const missing = [...new Set([...template.secrets, ...(choice?.secrets ?? [])])].filter((name) => !secret(name, storedKeys));
1916
2092
  // Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
1917
2093
  // one: several and no pick is a 422); the package's
1918
2094
  // tool names, mcp:<toolkit>/<tool>, read as that server's from here on (templates.ts onServers).
@@ -1938,8 +2114,19 @@ async function startHolding(options, data, checked, stops) {
1938
2114
  const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
1939
2115
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
1940
2116
  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) }));
1941
- const harness = pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
1942
- const picked = override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
2117
+ // A model choice the owner picked is its model on its harness, or a refusal naming the model: never the tier's model
2118
+ // in its place. So is a package's `prefer` (packageModel's `refused`), outside a gateway.
2119
+ const unrunnable = choice && (await choiceUnrunnable(env, choice, offers.find((offer) => offer.id === choice.harness)));
2120
+ if (choice && unrunnable) {
2121
+ 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.`;
2122
+ 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." }] });
2123
+ }
2124
+ const harness = choice ? choice.harness : pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
2125
+ const picked = choice ? { model: choice.model } : override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
2126
+ if ("refused" in picked && picked.refused) {
2127
+ 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.`;
2128
+ throw new ApiError("agent_not_runnable", message, { fields: [{ field: "model", reason: NOT_SET_UP, message, fix: picked.refused.fix }] });
2129
+ }
1943
2130
  const model = picked.model;
1944
2131
  // Which model the agent got, where it is not the package's: a note, never a lack. The agent runs; only the package's
1945
2132
  // choice was not an option here (not_set_up_here would read as a run refused until the host has something).
@@ -1950,14 +2137,15 @@ async function startHolding(options, data, checked, stops) {
1950
2137
  // A grant never lifts a deny the owner set on this server: that tool keeps it, and the answer says so.
1951
2138
  const server = settings.get();
1952
2139
  const denied = grants.filter((tool) => { const set = permissionFrom(tool, server); return set.from === "server" && set.permission === "deny"; });
1953
- 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.` }));
2140
+ 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.` }));
1954
2141
  // The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
1955
2142
  // never), else ask. Deny and pins hold either way.
1956
2143
  const chosenApprovals = approvals ?? pkg.approvals;
1957
- const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), ...(tiers.modelTiers ? { modelTiers: tiers.modelTiers } : {}), mcp: saved, defaultTools, grants, held: denied, ...(chosenApprovals ? { approvals: chosenApprovals } : {}), ...(pick ? { computer: pick } : {}) }, templateDeps);
2144
+ 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);
1958
2145
  // Every trigger is checked as POST /triggers checks it, its parameters filled, before anything is made: a schedule
1959
- // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>).
1960
- const refusedTriggers = madeTriggerIssues(made.triggers, Date.now(), pkg.inputSchema);
2146
+ // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>). "Passed"
2147
+ // by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
2148
+ const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema);
1961
2149
  if (refusedTriggers.length)
1962
2150
  throw invalid(refusedTriggers);
1963
2151
  // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
@@ -1970,9 +2158,10 @@ async function startHolding(options, data, checked, stops) {
1970
2158
  // Each webhook trigger's signing secret, minted as it is made: handed back in the apply's first answer alone, as POST
1971
2159
  // /triggers hands back its own, so the owner can give it to the sender.
1972
2160
  const secrets = [];
1973
- // A github trigger on a server GitHub is not connected to is skipped, never the apply: the agent stands, and the
1974
- // answer says to connect GitHub and apply again (a warning under triggers.<i>).
1975
- const unconnected = new Set();
2161
+ // A trigger this server can't set up yet (templates.ts TRIGGER_NOT_SET_UP_YET: a github one with GitHub not connected,
2162
+ // a composio one Composio can't reach or run as here) is skipped, never the apply: the agent stands, and the answer
2163
+ // says what to do (a warning under triggers.<i>). Kept with its refusal, whose words the warning carries.
2164
+ const unconnected = new Map();
1976
2165
  try {
1977
2166
  for (const [i, trigger] of made.triggers.entries()) {
1978
2167
  try {
@@ -1982,8 +2171,8 @@ async function startHolding(options, data, checked, stops) {
1982
2171
  secrets.push({ trigger_id: madeId, secret });
1983
2172
  }
1984
2173
  catch (error) {
1985
- if (error instanceof ApiError && error.code === "github_not_connected" && isObject(trigger.source) && trigger.source.kind === "github") {
1986
- unconnected.add(i);
2174
+ if (error instanceof ApiError && isObject(trigger.source) && notSetUpYet(trigger.source.kind, error.code)) {
2175
+ unconnected.set(i, error);
1987
2176
  continue;
1988
2177
  }
1989
2178
  if (error instanceof ApiError && error.code === "input_invalid" && error.extra.fields)
@@ -2020,12 +2209,17 @@ async function startHolding(options, data, checked, stops) {
2020
2209
  const githubTriggers = made.triggers.flatMap((trigger, i) => (isObject(trigger.source) && trigger.source.kind === "github"
2021
2210
  ? [unconnected.has(i) ? { field: `triggers.${i}`, reason: NOT_SET_UP, message: githubTriggerUnconnected(pkg.name, trigger.source) } : { field: `triggers.${i}`, reason: "not_an_option", message: githubTriggerWords(pkg.name, trigger.source) }]
2022
2211
  : []));
2212
+ // Each composio trigger it skipped: which, the refusal's words, and where to make it once that's fixed.
2213
+ const composioSkipped = made.triggers.flatMap((trigger, i) => {
2214
+ const refused = unconnected.get(i);
2215
+ return refused && isObject(trigger.source) && trigger.source.kind === "composio" ? [{ field: `triggers.${i}`, reason: NOT_SET_UP, message: composioTriggerSkipped(pkg.name, trigger, refused.message), fix: COMPOSIO_TRIGGER_FIX }] : [];
2216
+ });
2023
2217
  // Each trigger it made, a webhook trigger's with its secret's metadata; the values go back beside the answer, never in it
2024
2218
  // (the route adds them to the first answer to the owner's session, after the Idempotency-Key's record is written).
2025
2219
  const minted = new Map(secrets.map(({ trigger_id, secret }) => [trigger_id, secret]));
2026
2220
  // Which saved server each MCP need runs on (null: none here, said under mcp.<toolkit>).
2027
2221
  const used = Object.fromEntries(mapped.map(({ need, server }) => [need.toolkit, server]));
2028
- 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] };
2222
+ 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, ...composioSkipped, ...appShort] };
2029
2223
  return { applied, minted };
2030
2224
  }
2031
2225
  /** A run create's issues told from the input this server checks (explain.ts): an agentic run's input schema in force
@@ -2105,9 +2299,7 @@ async function startHolding(options, data, checked, stops) {
2105
2299
  return { body: rest, sealer };
2106
2300
  }
2107
2301
  async function createRun(req, agentId) {
2108
- const entry = await needAgent(agentId);
2109
- if (entry.agent.archivedAt)
2110
- 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() } });
2302
+ const entry = await needRunnableAgent(agentId);
2111
2303
  const { body, sealer } = handedMcpAuth(await bodyOf(req));
2112
2304
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
2113
2305
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
@@ -2131,6 +2323,8 @@ async function startHolding(options, data, checked, stops) {
2131
2323
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
2132
2324
  async function createInlineRun(req) {
2133
2325
  const { body, sealer } = handedMcpAuth(await bodyOf(req));
2326
+ if (isObject(body.definition) && body.definition.native !== undefined)
2327
+ throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine; an inline definition cannot create one.");
2134
2328
  const { external, definition, skills, note, revision: pinned, ...run } = body;
2135
2329
  const given = { definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) };
2136
2330
  const issues = [
@@ -2154,10 +2348,7 @@ async function startHolding(options, data, checked, stops) {
2154
2348
  const mapped = await store.agents.byExternal(externalKey(ref));
2155
2349
  const stored = mapped ? await store.agents.externalRevision(mapped.id, String(ref.version)) : undefined;
2156
2350
  const current = !stored && mapped?.currentRevision ? await store.agents.revision(mapped.currentRevision) : undefined;
2157
- // A version already stored keeps its revision's monid pin, not what monid lists now: its definition never changes
2158
- // here, so it compares equal to the stored one (startInline), and monid's listing is not read again.
2159
- const keptMonid = stored?.kind === "agentic" ? stored.body.monidPin : undefined;
2160
- const revision = stored ? (keptMonid ? { ...made, body: { ...made.body, monidPin: keptMonid } } : made) : { ...made, ...(await saveable(made, current?.mcpPin)).stamp };
2351
+ const revision = stored ? made : { ...made, ...(await saveable(made, current)).stamp };
2161
2352
  const inline = {
2162
2353
  external: { source: ref.source, kind: ref.kind, id: ref.id, version: String(ref.version) },
2163
2354
  name: checked.definition.name,
@@ -2229,7 +2420,7 @@ async function startHolding(options, data, checked, stops) {
2229
2420
  }
2230
2421
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
2231
2422
  function runBodyIssues(body) {
2232
- const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "cap_mode", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes"]);
2423
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes"]);
2233
2424
  issues.push(...holdIssues(body));
2234
2425
  if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
2235
2426
  issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
@@ -2249,8 +2440,6 @@ async function startHolding(options, data, checked, stops) {
2249
2440
  issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
2250
2441
  if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0 && Number.isFinite(body.max_cost_usd)))
2251
2442
  issues.push({ field: "max_cost_usd", reason: "wrong_type", message: "max_cost_usd is a number above 0" });
2252
- if (body.cap_mode !== undefined && !CAP_MODES.includes(body.cap_mode))
2253
- issues.push({ field: "cap_mode", reason: "not_an_option", message: `cap_mode is one of ${CAP_MODES.join(", ")}` });
2254
2443
  if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
2255
2444
  issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
2256
2445
  if (body.workflow_first !== undefined && typeof body.workflow_first !== "boolean")
@@ -2296,11 +2485,16 @@ async function startHolding(options, data, checked, stops) {
2296
2485
  if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
2297
2486
  throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
2298
2487
  const limit = asked === null ? PAGE_ROWS : Number(asked);
2488
+ // `calls=whole`: each call's arguments and its output's head too (tool_input, tool_result_text), for a grader.
2489
+ const shape = url.searchParams.get("calls");
2490
+ if (shape !== null && shape !== "whole")
2491
+ throw new ApiError("bad_request", "calls is whole, or absent");
2492
+ const calls = shape === "whole";
2299
2493
  // The run's page from the store (runTimelines): run_id/status/state/reset/rows/drop/next_after/unchanged/has_more/final/
2300
2494
  // cost, byte-identical to the old live page. TODO(learning-row freshness): a learning row approved or retired since the
2301
2495
  // journal wrote it reads its journal state here (store-view owns the fresh learning view); folded in with learning-1.
2302
2496
  if (!String(req.headers.accept ?? "").includes("text/event-stream")) {
2303
- const page = await timelines.page(store, runId, after, waitMs, limit);
2497
+ const page = await timelines.page(store, runId, after, waitMs, limit, calls);
2304
2498
  return send(res, 200, { ...page, poll_after_ms: page.final || page.has_more ? 0 : 1000 });
2305
2499
  }
2306
2500
  const last = req.headers["last-event-id"];
@@ -2324,7 +2518,7 @@ async function startHolding(options, data, checked, stops) {
2324
2518
  });
2325
2519
  try {
2326
2520
  for (let first = true; open; first = false) {
2327
- const page = await timelines.page(store, runId, cursor, 0, limit);
2521
+ const page = await timelines.page(store, runId, cursor, 0, limit, calls);
2328
2522
  if (!open)
2329
2523
  break;
2330
2524
  if (first || !page.unchanged || page.final)
@@ -2702,8 +2896,10 @@ async function startHolding(options, data, checked, stops) {
2702
2896
  // Archil on or off, or saving a key, changes them. So does a shell on the runner (bash on Archil's serverless exec
2703
2897
  // in Mode 2): where there is one, the document is made again with it (cheap), its tools available with no box.
2704
2898
  const runnerShell = shellTools(await shellOf({ kind: "none" }));
2899
+ await planNow();
2705
2900
  const answer = forCaller(runnerShell.size ? compose(runnerShell) : caps, byOwnerSession(req));
2706
- return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()) } });
2901
+ // features.triggers.public_url: whether Composio (or any sender) has a public address to reach, never the address.
2902
+ return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
2707
2903
  }
2708
2904
  if (found.name === "getOpenapi")
2709
2905
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
@@ -2715,7 +2911,7 @@ async function startHolding(options, data, checked, stops) {
2715
2911
  // read (push-handler.ts).
2716
2912
  if (found.name === "receiveHook") {
2717
2913
  // A body cut at its cap or its time is answered, then its socket closed: never read to its end.
2718
- 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]);
2914
+ 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))));
2719
2915
  return send(res, answer.status, answer.body, answer.headers ?? {});
2720
2916
  }
2721
2917
  // A paired computer's driver trading its pairing code for its token: the code is its credential (computer-attach.ts),
@@ -2784,6 +2980,12 @@ async function startHolding(options, data, checked, stops) {
2784
2980
  authFailed(`/v2${path}`, "promote_without_session");
2785
2981
  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).");
2786
2982
  }
2983
+ // A replay its owner starts runs the agent's graded inputs again at its cost, and may promote a revision that then
2984
+ // serves first: the same session as making one an agent.
2985
+ if (found.name === "startLearnedWorkflowReplay" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
2986
+ authFailed(`/v2${path}`, "replay_without_session");
2987
+ 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).");
2988
+ }
2787
2989
  // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
2788
2990
  // approving a note is (never a token a run, an MCP client or a script may hold).
2789
2991
  if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
@@ -2824,17 +3026,130 @@ async function startHolding(options, data, checked, stops) {
2824
3026
  }
2825
3027
  secretSeen = checked.seen;
2826
3028
  }
3029
+ // Connector credentials have no authority over the ordinary API. Enrollment is a one-use owner grant;
3030
+ // subsequent calls are restricted to one connector and its explicitly imported target allowlist.
3031
+ if (found.name === "registerRemoteConnector") {
3032
+ const credential = String(req.headers.authorization ?? "").replace(/^Bearer /, "");
3033
+ return send(res, 200, await new RemoteConnectors(store).register(credential, await bodyOf(req)));
3034
+ }
3035
+ if (found.name === "revokeRemoteConnector" && String(req.headers.authorization ?? "").startsWith("Bearer ar_connector_")) {
3036
+ const connectorId = decodeURIComponent(found.pattern.exec(path)[1]);
3037
+ const broker = new RemoteConnectors(store);
3038
+ await broker.authenticate(connectorId, String(req.headers.authorization).slice(7));
3039
+ return send(res, 200, await broker.revoke(connectorId));
3040
+ }
3041
+ if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand"].includes(found.name)) {
3042
+ const parts = found.pattern.exec(path);
3043
+ const connectorId = decodeURIComponent(parts[1]);
3044
+ const broker = new RemoteConnectors(store);
3045
+ await broker.authenticate(connectorId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
3046
+ // History pages and command completions have separate bounded contracts; other JSON keeps MAX_BODY.
3047
+ const limit = found.name === "importRemoteHistory" ? REMOTE_HISTORY_BODY_BYTES
3048
+ : found.name === "completeRemoteCommand" ? REMOTE_COMPLETION_BODY_BYTES : MAX_BODY;
3049
+ const body = await bodyOf(req, limit);
3050
+ if (found.name === "importRemoteTarget")
3051
+ return send(res, 200, await broker.importTarget(connectorId, body));
3052
+ if (found.name === "importRemoteHistory")
3053
+ return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [token, String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
3054
+ if (found.name === "pollRemoteConnector")
3055
+ return send(res, 200, await broker.poll(connectorId, body));
3056
+ const commandId = decodeURIComponent(parts[2]);
3057
+ return send(res, 200, found.name === "remoteCommandEvents" ? await broker.events(connectorId, commandId, body) : await broker.complete(connectorId, commandId, body));
3058
+ }
3059
+ if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
3060
+ const runId = decodeURIComponent(found.pattern.exec(path)[1]);
3061
+ const sdk = new SdkRuns(store, data, token, serverSecrets);
3062
+ await sdk.authenticate(runId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
3063
+ if (found.name === "sdkRunEvents")
3064
+ return send(res, 200, await sdk.events(runId, await bodyOf(req)));
3065
+ if (found.name === "completeSdkRun")
3066
+ return send(res, 200, await sdk.complete(runId, await bodyOf(req)));
3067
+ return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
3068
+ }
2827
3069
  if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
2828
3070
  authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
2829
3071
  throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
2830
3072
  }
2831
3073
  if (found.capability)
2832
3074
  throw unsupported(found.capability, UNSUPPORTED[found.capability]);
3075
+ if (["discoverNative", "connectNative"].includes(found.name) && (options.apiOnly || options.publicUrl || !isLoopback(host)))
3076
+ 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.");
2833
3077
  const [, first, second] = found.pattern.exec(path);
2834
3078
  const id = first ? decodeURIComponent(first) : "";
2835
3079
  switch (found.name) {
3080
+ case "startSdkRun": {
3081
+ if (!req.headers["idempotency-key"])
3082
+ throw new ApiError("bad_request", "An SDK run requires Idempotency-Key so a retried start never duplicates execution.");
3083
+ const body = await bodyOf(req), entry = await needAgent(id);
3084
+ let gradeModel = gradeModelOf(env, options.gradeModel);
3085
+ if (!gradeModel && sdkOf(entry.revision?.body) && learnsOf(entry.revision.body.learning) && learning !== "off") {
3086
+ try {
3087
+ const chosen = await runModelRef(env, (await pinnedOf(entry, {})).revision);
3088
+ if (chosen)
3089
+ gradeModel = `${chosen.provider}/${chosen.modelId}`;
3090
+ }
3091
+ catch { }
3092
+ }
3093
+ const sdk = new SdkRuns(store, data, token, serverSecrets);
3094
+ const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, { ...startDeps, ...(gradeModel ? { gradeModel } : {}) }, origin, async (model) => {
3095
+ try {
3096
+ const route = await gradeRouteFor({ model, agentId: id }, env, sdkModelRoute);
3097
+ await route.provider.credential();
3098
+ }
3099
+ catch {
3100
+ 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.");
3101
+ }
3102
+ }, linkOrigin(req)) }));
3103
+ // Re-read the pinned receipt even on an in-memory replay: credentials saved since
3104
+ // the first response must still be withheld without reselecting a different seed.
3105
+ const receipt = await sdk.receipt(answer.body.run_id, linkOrigin(req));
3106
+ return send(res, answer.status, receipt, answer.headers);
3107
+ }
3108
+ case "getObservations": {
3109
+ const days = Number(url.searchParams.get("days") ?? 30);
3110
+ if (!Number.isInteger(days) || days < 1 || days > 31)
3111
+ throw new ApiError("input_invalid", "Choose an observation window from 1 to 31 days.");
3112
+ return send(res, 200, await new Observations(store).snapshot(days, url.searchParams.get("session_id") ?? undefined));
3113
+ }
3114
+ case "listRemoteConnectors": return send(res, 200, await new RemoteConnectors(store).list());
3115
+ case "enrollRemoteConnector": return send(res, 200, await new RemoteConnectors(store).enroll(await bodyOf(req)));
3116
+ case "revokeRemoteConnector": return send(res, 200, await new RemoteConnectors(store).revoke(id));
3117
+ case "discoverNative": {
3118
+ const body = await bodyOf(req);
3119
+ if (typeof body.project !== "string" || (body.runtime !== undefined && !isNativeRuntime(body.runtime)))
3120
+ throw new ApiError("input_invalid", "Choose the project directory on this source machine and a supported CLI runtime.");
3121
+ return send(res, 200, await discoverNative({ project: body.project, ...(body.runtime ? { runtime: body.runtime } : {}) }));
3122
+ }
3123
+ case "connectNative": {
3124
+ const entry = await connectNative(store, await bodyOf(req));
3125
+ return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), native: nativeOf(entry.revision?.body) });
3126
+ }
3127
+ case "getNative": {
3128
+ const entry = await needAgent(id);
3129
+ const native = nativeOf(entry.revision?.body);
3130
+ return send(res, 200, { native: native?.remote ? await new RemoteConnectors(store).status(native) : native ?? null });
3131
+ }
3132
+ case "verifyNative": {
3133
+ const before = await needAgent(id);
3134
+ if (!nativeOf(before.revision?.body)?.remote && (options.apiOnly || options.publicUrl || !isLoopback(host)))
3135
+ throw new ApiError("forbidden", "Local native verification must run on the source machine.");
3136
+ const entry = nativeOf(before.revision?.body)?.remote ? await verifyRemote(store, before) : await verifyConnection(store, before);
3137
+ return send(res, 200, { native: nativeOf(entry.revision?.body) });
3138
+ }
3139
+ case "disconnectNative": {
3140
+ const entry = await needAgent(id);
3141
+ const native = nativeOf(entry.revision?.body);
3142
+ if (!native)
3143
+ throw new ApiError("not_found", "This agent has no native connection.");
3144
+ const changed = await updateNative(store, entry, { ...native, connected: false });
3145
+ if (native.remote)
3146
+ await new RemoteConnectors(store).disconnectTarget(native);
3147
+ return send(res, 200, { native: nativeOf(changed.revision?.body) });
3148
+ }
2836
3149
  case "createAgent": {
2837
3150
  const body = await bodyOf(req);
3151
+ if (isObject(body.definition) && body.definition.native !== undefined)
3152
+ throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine.");
2838
3153
  const answer = await idempotent(req, "/agents", body, async () => {
2839
3154
  const { entry, warnings } = await createAgentOf(body);
2840
3155
  return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
@@ -2879,6 +3194,16 @@ async function startHolding(options, data, checked, stops) {
2879
3194
  // contract's is the definition itself, and takes the contract's preconditions: If-Match, and a version past the
2880
3195
  // current one.
2881
3196
  const contract = !("definition" in body);
3197
+ const nativeEdit = contract ? body.native : isObject(body.definition) ? body.definition.native : undefined;
3198
+ if (nativeEdit !== undefined && stable(nativeEdit) !== stable(nativeOf(entry.revision?.body)))
3199
+ throw new ApiError("input_invalid", "Native references are changed only through the native connection endpoints. Normal edits retain the existing reference.");
3200
+ // Check explicit native selectors before canonicalization (the ordinary default harness, pi, is not stored).
3201
+ const definition = contract ? body : body.definition;
3202
+ if (nativeOf(entry.revision?.body) && isObject(definition)) {
3203
+ const execution = nativeExecutionOverrides({ ...definition, native: nativeOf(entry.revision?.body) });
3204
+ if (execution.length)
3205
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
3206
+ }
2882
3207
  if (contract) {
2883
3208
  if (match === undefined)
2884
3209
  throw new ApiError("precondition_failed", "If-Match is required: the agent's ETag, as GET /agents/{agent_id} returned it.");
@@ -2889,9 +3214,8 @@ async function startHolding(options, data, checked, stops) {
2889
3214
  // the same revision exactly one lands.
2890
3215
  let warnings = [];
2891
3216
  const check = async (revision, on) => {
2892
- // The pin of the revision this try builds on (commitAgent's read, a retry's newer one): a server down now keeps
2893
- // it when the edit grants nothing new from it.
2894
- const saved = await saveable(revision, on?.mcpPin);
3217
+ // The pins of the revision this try builds on (commitAgent's read, a retry's newer one) carry what it kept.
3218
+ const saved = await saveable(revision, on);
2895
3219
  warnings = saved.warnings;
2896
3220
  return saved.stamp;
2897
3221
  };
@@ -2917,8 +3241,19 @@ async function startHolding(options, data, checked, stops) {
2917
3241
  const revision = body.revision;
2918
3242
  if (typeof revision !== "string" || !ID.test(revision))
2919
3243
  throw invalid([{ field: "revision", reason: revision === undefined ? "missing" : "wrong_type", message: "revision is a revision id of this agent" }]);
2920
- if (!(await agents.revision(id, revision)))
3244
+ const candidate = await agents.revision(id, revision);
3245
+ if (!candidate)
2921
3246
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
3247
+ if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
3248
+ 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.");
3249
+ if (nativeOf(candidate.revision.body)) {
3250
+ const overrides = nativeModelOverrides(candidate.revision.body);
3251
+ if (overrides.length)
3252
+ throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
3253
+ const execution = nativeExecutionOverrides(candidate.revision.body);
3254
+ if (execution.length)
3255
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
3256
+ }
2922
3257
  const moved = await agents.setCurrent(entry, revision);
2923
3258
  reconcileComputer(id);
2924
3259
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
@@ -3084,11 +3419,14 @@ async function startHolding(options, data, checked, stops) {
3084
3419
  const grade = {
3085
3420
  run: row.id, correct: body.correct, ...(body.expected !== undefined ? { expected: body.expected } : {}), source: body.source ?? "feedback", at: new Date().toISOString(), path,
3086
3421
  ...(typeof m.workflow === "string" ? { workflow: m.workflow } : {}), ...(typeof m.workflow_digest === "string" ? { digest: m.workflow_digest } : {}),
3422
+ ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3087
3423
  };
3088
- await putGrade(store.settings, row.agentId, grade);
3089
- // What the grade asks of the run's learning (runner/feedback-round.ts): nothing, a revision ask, or a look-back.
3090
- const feedback = await openFeedbackRound(store, grade, typeof body.label === "string" ? body.label : undefined);
3091
- return send(res, 200, { ...gradeView(grade), feedback });
3424
+ // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, a revision ask, or a look-back.
3425
+ const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined));
3426
+ // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3427
+ // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
3428
+ const shown = await learningShown(row.agentId).catch(() => undefined);
3429
+ return send(res, 200, { ...kept, workflow: kept.workflow === null ? null : shown ? shown.name(kept.workflow) : REDACTED });
3092
3430
  }
3093
3431
  case "archiveRun":
3094
3432
  case "unarchiveRun": {
@@ -3110,7 +3448,11 @@ async function startHolding(options, data, checked, stops) {
3110
3448
  const kept = await keptBrowserOf(store, run.id);
3111
3449
  // A desktop or a phone (the run's revision's computer) whose screen is not open now is still the run's computer:
3112
3450
  // none with its kind, never off as if the agent had none (#2170).
3113
- const viewed = family === "computer" ? await runViewedKind(store, run.id) : undefined;
3451
+ const own = family === "computer" ? await runComputerKind(store, run.id) : undefined;
3452
+ const viewed = own === "desktop" || own === "phone" ? own : undefined;
3453
+ // A parked run's desktop or phone is no screen being opened: its claim let it go, or kept it for the resume
3454
+ // (computer-kept.ts; the run's timeline says until when), and once its time passed, the timeout's words.
3455
+ const parked = family === "computer" && !run.terminal && (await store.runs.get(run.id))?.state === "parked";
3114
3456
  const view = await computerView({
3115
3457
  viewer: async () => {
3116
3458
  if (family === "browser") {
@@ -3119,8 +3461,9 @@ async function startHolding(options, data, checked, stops) {
3119
3461
  }
3120
3462
  return computerViewerLink(store, sealKey, run.id, answers);
3121
3463
  },
3122
- computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family)),
3123
- session: (kind) => sessionIn(kind, entries, run.terminal),
3464
+ computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family, own)),
3465
+ session: (kind) => sessionIn(kind, entries, run.terminal || (parked && kind !== "browser")),
3466
+ lapsed: async (kind) => (parked ? lapsedOf(kind, await readKept(store.settings, run.id).catch(() => undefined), Date.now()) : undefined),
3124
3467
  hold: () => hold,
3125
3468
  // A going run's browser let go while it waited for its person: the Screen tab says so, with when. One settings
3126
3469
  // row (browser-wait-ended.ts), never the run's journal: this is read on every Screen poll.
@@ -3370,6 +3713,35 @@ async function startHolding(options, data, checked, stops) {
3370
3713
  await toolKeys.remove(id);
3371
3714
  await keysChanged();
3372
3715
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3716
+ // Never through `idempotent`: its record keeps the body, and the body holds the password.
3717
+ case "getEmailAccount":
3718
+ case "saveEmailAccount":
3719
+ case "deleteEmailAccount":
3720
+ case "testEmailAccount": {
3721
+ const body = found.name === "saveEmailAccount" || found.name === "testEmailAccount" ? await bodyOf(req) : undefined;
3722
+ if (found.name === "saveEmailAccount" && stopping.signal.aborted)
3723
+ throw new ApiError("unavailable", "The server is shutting down: the account was not saved.");
3724
+ const answer = await emailRoute({ store, sealKey }, found.name, body);
3725
+ if (found.name === "saveEmailAccount")
3726
+ await heldEmailPassword();
3727
+ if (answer === undefined)
3728
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
3729
+ return send(res, 200, answer, { "cache-control": "no-store" });
3730
+ }
3731
+ // The ChatGPT sign-in (chatgpt-plan.ts): a step it refuses is 400 in its words; its token is in no answer.
3732
+ case "getChatGPTSignIn":
3733
+ await planNow();
3734
+ return send(res, 200, plan.view());
3735
+ case "startChatGPTSignIn":
3736
+ return send(res, 200, await planStep(() => plan.startSignIn()));
3737
+ case "finishChatGPTSignIn": {
3738
+ const body = (await bodyOf(req));
3739
+ return send(res, 200, await planStep(() => plan.finishSignIn(body?.redirect_url)));
3740
+ }
3741
+ case "signOutChatGPT": {
3742
+ const { revoked } = await plan.signOut();
3743
+ return send(res, 200, revoked ? { revoked } : { revoked, message: SIGN_OUT_UNCONFIRMED });
3744
+ }
3373
3745
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
3374
3746
  case "listMcpServers":
3375
3747
  return send(res, 200, await mcpServers.list());
@@ -3393,6 +3765,14 @@ async function startHolding(options, data, checked, stops) {
3393
3765
  await refreshMcpMeta();
3394
3766
  return send(res, 200, answer, { "cache-control": "no-store" });
3395
3767
  }
3768
+ case "listComposioEvents":
3769
+ return send(res, 200, await composioTriggers.events(id), { "cache-control": "no-store" });
3770
+ case "listComposioTriggers":
3771
+ return send(res, 200, await composioTriggers.triggersOf(id), { "cache-control": "no-store" });
3772
+ case "rotateComposioSecret":
3773
+ return send(res, 200, await composioTriggers.rotate(id), { "cache-control": "no-store" });
3774
+ case "deleteComposioSubscription":
3775
+ return send(res, 200, await composioTriggers.forget(id), { "cache-control": "no-store" });
3396
3776
  case "refreshMcpServer": {
3397
3777
  const refreshed = await mcpServers.refresh(id, stopping.signal);
3398
3778
  await refreshMcpMeta();
@@ -3441,8 +3821,9 @@ async function startHolding(options, data, checked, stops) {
3441
3821
  // Our row goes first, by the checked removal (a 412 sends Composio nothing), and answers what it removed: a Composio
3442
3822
  // preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key.
3443
3823
  // Composio refusing or not answering, or a key that does not open, never keeps our row: the answer says what to
3444
- // remove there by hand.
3445
- const { composio: made } = await mcpServers.remove(id, secretSeen);
3824
+ // remove there by hand. One that Composio triggers still use is kept: refused, naming them, checked and deleted in
3825
+ // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting).
3826
+ const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
3446
3827
  await refreshMcpMeta();
3447
3828
  const forgotten = !made ? undefined : "unusable" in made ? composioNote(id) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal);
3448
3829
  if (forgotten && !forgotten.removed)
@@ -3591,6 +3972,29 @@ async function startHolding(options, data, checked, stops) {
3591
3972
  });
3592
3973
  return send(res, answer.status, answer.body, answer.headers);
3593
3974
  }
3975
+ case "startLearnedWorkflowReplay": {
3976
+ const body = await bodyOf(req);
3977
+ // An archived agent starts no run: refused before the replay is reserved, as a person's start is.
3978
+ const entry = await needRunnableAgent(id);
3979
+ const extra = unknownFields(body, ["inputs"]);
3980
+ if (extra.length)
3981
+ throw invalid(extra);
3982
+ const inputs = body.inputs === undefined ? "held" : body.inputs;
3983
+ if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= GRADES_KEPT)) {
3984
+ 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.`);
3985
+ }
3986
+ const [, , name, digest] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
3987
+ const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
3988
+ return send(res, 202, started, { location: `/v2/agents/${encodeURIComponent(id)}/learning/workflows/${encodeURIComponent(name)}/revisions/${encodeURIComponent(digest)}/replays/${started.replay}` });
3989
+ }
3990
+ case "getLearnedWorkflowReplay": {
3991
+ const entry = await needAgent(id);
3992
+ const [, , name, digest, replayId] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
3993
+ const view = await replayAsked(() => replayView(replayAskOf(entry), name, digest, replayId));
3994
+ // Its words cut as the promotions list cuts a record's (promotionsShown).
3995
+ const shown = await learningShown(id);
3996
+ return send(res, 200, { ...view, workflow: shown.name(view.workflow), ...(view.reason !== undefined ? { reason: shown.text(view.reason) } : {}) });
3997
+ }
3594
3998
  case "getRunLearning": {
3595
3999
  const run = await needRun(id);
3596
4000
  // The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
@@ -3680,23 +4084,24 @@ async function startHolding(options, data, checked, stops) {
3680
4084
  }
3681
4085
  case "rotateTriggerSecret":
3682
4086
  // A secret write: the dispatch's one check let only the owner's session this far (trigger-secrets-shown.ts).
3683
- // A trigger whose sender gives its secret (Composio's) takes it as the body's `secret`; any other is made one.
3684
- return send(res, 200, await (async () => {
3685
- const empty = req.headers["transfer-encoding"] === undefined && !Number(req.headers["content-length"]);
3686
- const body = empty ? {} : await bodyOf(req);
3687
- const extra = Object.keys(body).filter((key) => key !== "secret");
3688
- if (extra.length)
3689
- throw invalid(extra.map((field) => ({ field, reason: "unknown_field", message: `${field} is not a field of this request: only secret` })));
3690
- return triggerRotated(id, (await triggers.rotate(id, body.secret)).secret, new Date().toISOString());
3691
- })());
4087
+ // It takes no body: the new secret is made here, never given. Any body is refused before it rotates, `{}` too: a
4088
+ // length other than 0, or one sent chunked, is a body whatever it holds.
4089
+ if (req.headers["transfer-encoding"] !== undefined || Number(req.headers["content-length"] ?? 0) !== 0) {
4090
+ 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." }]);
4091
+ }
4092
+ return send(res, 200, triggerRotated(id, (await triggers.rotate(id)).secret, new Date().toISOString()));
3692
4093
  case "getTrigger":
3693
4094
  return send(res, 200, withSecretOf(await triggers.get(id)));
3694
4095
  case "updateTrigger":
3695
4096
  // Its secret's metadata as a read answers it, so a page showing the changed trigger keeps saying it is set.
3696
4097
  return send(res, 200, withSecretOf(await triggers.update(id, await bodyOf(req))));
3697
- case "deleteTrigger":
3698
- await triggers.remove(id);
4098
+ case "deleteTrigger": {
4099
+ // Deleted here whatever its sender says; what could not be removed there is answered (Composio's instance).
4100
+ const said = await triggers.remove(id);
4101
+ if (said)
4102
+ return send(res, 200, { deleted: true, ...said });
3699
4103
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
4104
+ }
3700
4105
  case "fireTrigger": {
3701
4106
  const key = req.headers["idempotency-key"];
3702
4107
  if (typeof key !== "string" || key.length < 1 || key.length > 255)
@@ -3795,8 +4200,12 @@ async function startHolding(options, data, checked, stops) {
3795
4200
  return void mcp(req, res).catch(fail);
3796
4201
  if (raw === "/llms.txt")
3797
4202
  return void answerLlms(req, res).catch(fail);
4203
+ if (raw === "/skills/agentrun-serve/SKILL.md")
4204
+ return void answerSkill(req, res).catch(fail);
3798
4205
  if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3799
4206
  return;
4207
+ if (isObservationRoute(raw))
4208
+ return void observationHttp(req, res, url, new Observations(store), token).catch(fail);
3800
4209
  if (!raw.startsWith("/v2/"))
3801
4210
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
3802
4211
  // 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
@@ -3920,7 +4329,10 @@ async function startHolding(options, data, checked, stops) {
3920
4329
  // change would be the next seam.
3921
4330
  const RUN_CHANGES_POLL_MS = 250;
3922
4331
  const final = (row) => FINAL_STATES.includes(row.state);
3923
- const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}) });
4332
+ /** A row its stop ended (stopEnd), which may stand at the person's stop (store.ts stoppedByPerson: an agentic run, its
4333
+ * status input_required and idle, a message continues it) and not have ended: its view says which. */
4334
+ const stopRow = (row) => row.state === "stopped" && row.outcome === "stopped" && row.importedFrom === null;
4335
+ 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 } : {}) });
3924
4336
  /** 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. */
3925
4337
  const endNotice = async (id) => {
3926
4338
  const row = await store.runs.get(id);
@@ -3946,9 +4358,9 @@ async function startHolding(options, data, checked, stops) {
3946
4358
  /** When each held wait (a run waiting on its person with its claim held) was last read again. */
3947
4359
  const heldReadAt = new Map();
3948
4360
  const HELD_WAIT_REREAD_MS = 1_000;
3949
- const waitKinds = new Set(["question", "approval", "budget", "browser"]);
4361
+ const waitKinds = new Set(["question", "approval", "budget", "browser", "computer", "stopped"]);
3950
4362
  /** 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
3951
- * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (a stop's when it waits on no card). False when it
4363
+ * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (none when the run waits on no card). False when it
3952
4364
  * is not done (a read that failed, or its notice not saved): it is read again. */
3953
4365
  const tellWait = async (row) => {
3954
4366
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
@@ -3958,14 +4370,17 @@ async function startHolding(options, data, checked, stops) {
3958
4370
  if (view?.status !== "input_required")
3959
4371
  return (readWaits.set(row.id, seen), true);
3960
4372
  const rows = (await timelineOverStore(store, row.id, viewDepsFor(ownOriginOf()))) ?? [];
3961
- // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last.
3962
- const marker = waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
4373
+ const card = view.pending?.kind;
4374
+ // 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
4375
+ // its stop ended the row: rows its stopped turn still streams in (a late result, a charge) never move it.
4376
+ const marker = card === "stopped" && row.endedAt !== null ? `stopped:${new Date(row.endedAt).toISOString()}` : waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
3963
4377
  if (!marker)
3964
4378
  return (readWaits.set(row.id, seen), true);
3965
- const card = view.pending?.kind;
3966
- const kind = view.state !== "waiting" ? "stopped" : typeof card === "string" && waitKinds.has(card) ? card : "question";
3967
- const wait = { kind };
3968
- const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", pending: wait };
4379
+ // Its kind is the read's own `pending.kind` (a stop's is stoppedTurn's), so the notice and GET never disagree; a wait
4380
+ // whose card is withheld is a question. A run idle on nothing named (its harness ended its turn on its own) names no kind.
4381
+ const kind = typeof card === "string" && waitKinds.has(card) ? card : view.state === "waiting" ? "question" : undefined;
4382
+ const wait = kind === undefined ? undefined : { kind };
4383
+ const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", ...(wait ? { pending: wait } : {}) };
3969
4384
  if (!(await toldAll(row.id, waitSubscribers.map((tell) => () => tell(notice, wait, marker)))))
3970
4385
  return false;
3971
4386
  readWaits.set(row.id, seen);
@@ -4017,6 +4432,17 @@ async function startHolding(options, data, checked, stops) {
4017
4432
  const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
4018
4433
  if (now === undefined)
4019
4434
  return false;
4435
+ // A person's stop of an agentic run ends its row but not the run: it reads input_required (pending kind stopped), so
4436
+ // it is told as that wait, run.needs_input, never as an end.
4437
+ if (now?.notice.status === "input_required") {
4438
+ const row = await rowNow(id);
4439
+ if (row === UNREAD)
4440
+ return (sayUnread(id, "its row could not be read"), false);
4441
+ const told = row === undefined || (await tellWait(row).catch((error) => (sayUnread(id, error.message), false)));
4442
+ if (told)
4443
+ unreadSaid.delete(id);
4444
+ return told;
4445
+ }
4020
4446
  readWaits.delete(id);
4021
4447
  heldReadAt.delete(id);
4022
4448
  if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
@@ -4055,7 +4481,7 @@ async function startHolding(options, data, checked, stops) {
4055
4481
  const row = await rowNow(id);
4056
4482
  if (row === UNREAD)
4057
4483
  return (sayUnread(id, "its row could not be read"), false);
4058
- if (row === undefined || !letGo(row))
4484
+ if (row === undefined || !(letGo(row) || stopRow(row)))
4059
4485
  return true;
4060
4486
  const told = await tellWait(row).catch((error) => (sayUnread(id, error.message), false));
4061
4487
  if (told)
@@ -4140,8 +4566,9 @@ async function startHolding(options, data, checked, stops) {
4140
4566
  const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
4141
4567
  for (const id of unsaved)
4142
4568
  endsLeft.add(id);
4569
+ // A run that stands at a person's stop waits too (tellWait reads its view: one its stop ended reads no wait).
4143
4570
  for (const row of rows)
4144
- if (!closing && letGo(row) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
4571
+ if (!closing && (letGo(row) || stopRow(row)) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
4145
4572
  waitsLeft.add(row.id);
4146
4573
  };
4147
4574
  followChanges();
@@ -4155,6 +4582,9 @@ async function startHolding(options, data, checked, stops) {
4155
4582
  // the store closes last.
4156
4583
  closing = true;
4157
4584
  stopping.abort();
4585
+ // Cancel a pending ChatGPT callback without signing out or changing the saved credential.
4586
+ plan.close();
4587
+ const observationStopped = stopObservationRetention();
4158
4588
  // A harness install under way stops with the server: npm gets SIGTERM, then SIGKILL, and nothing half installed stays.
4159
4589
  const installStopped = Promise.all(Object.values(installs).map((install) => install.stop()));
4160
4590
  // Aborted now, so nothing it writes races the next server on the same refresh token; drained before the store closes.
@@ -4172,6 +4602,7 @@ async function startHolding(options, data, checked, stops) {
4172
4602
  await Promise.all([...workers.values()].map((w) => w.exit));
4173
4603
  await importing;
4174
4604
  await installStopped;
4605
+ await observationStopped;
4175
4606
  // The ends' follower stops before the webhooks it feeds and the store it reads.
4176
4607
  clearTimeout(endsTimer);
4177
4608
  await endsRead;