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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (410) hide show
  1. package/CHANGELOG.md +418 -0
  2. package/README.md +325 -124
  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-BNhZs-jp.css +1 -0
  37. package/dist/console/assets/index-BQv5aOGB.js +700 -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 +84 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +10 -0
  46. package/dist/email/answer.js +182 -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 +380 -0
  53. package/dist/email/names.d.ts +20 -0
  54. package/dist/email/names.js +40 -0
  55. package/dist/email/routes.d.ts +9 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +20 -0
  58. package/dist/email/tools.js +517 -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 +9 -2
  93. package/dist/learn/compile.js +52 -16
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +106 -51
  97. package/dist/learn/promote.js +82 -189
  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 +26 -8
  109. package/dist/learning-cost.js +17 -7
  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 +33 -2
  118. package/dist/local-models.js +43 -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 +1 -0
  164. package/dist/openapi.js +394 -85
  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 +7 -2
  170. package/dist/port-models.js +5 -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 +11 -0
  180. package/dist/refusal-words.js +13 -2
  181. package/dist/run-launch.d.ts +10 -1
  182. package/dist/run-launch.js +11 -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 +42 -35
  191. package/dist/run-view.js +79 -44
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +42 -11
  195. package/dist/runner/adapter-loop.js +651 -247
  196. package/dist/runner/adapter-run-spec.d.ts +37 -12
  197. package/dist/runner/adapter-run-spec.js +139 -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 +94 -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 +37 -13
  217. package/dist/runner/journal-kinds.js +9 -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 +12 -3
  237. package/dist/runner/model-route.js +139 -18
  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 +74 -8
  243. package/dist/runner/promotion.js +365 -124
  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 +554 -130
  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/index.d.ts +1 -1
  278. package/dist/store/native-command-owner.d.ts +10 -0
  279. package/dist/store/native-command-owner.js +47 -0
  280. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  281. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  282. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  283. package/dist/store/postgres/store.js +3 -0
  284. package/dist/store/schema.d.ts +7 -0
  285. package/dist/store/schema.js +20 -1
  286. package/dist/store/sqlite/run-patch.d.ts +8 -1
  287. package/dist/store/sqlite/run-patch.js +14 -3
  288. package/dist/store/sqlite/store.js +133 -18
  289. package/dist/store/store.d.ts +52 -7
  290. package/dist/store-reads/analytics.d.ts +7 -7
  291. package/dist/store-reads/analytics.js +23 -5
  292. package/dist/store-reads/cap.js +8 -6
  293. package/dist/store-reads/journal.d.ts +5 -0
  294. package/dist/store-reads/journal.js +85 -41
  295. package/dist/store-reads/learning.d.ts +85 -5
  296. package/dist/store-reads/learning.js +45 -17
  297. package/dist/store-reads/runs.d.ts +5 -0
  298. package/dist/store-reads/runs.js +3 -2
  299. package/dist/store-view.js +75 -21
  300. package/dist/template-eval.d.ts +73 -11
  301. package/dist/template-eval.js +535 -75
  302. package/dist/templates.d.ts +70 -20
  303. package/dist/templates.js +191 -34
  304. package/dist/text-urls.d.ts +38 -0
  305. package/dist/text-urls.js +170 -0
  306. package/dist/timeline/index.d.ts +3 -2
  307. package/dist/timeline/index.js +3 -2
  308. package/dist/timeline/labels.d.ts +5 -2
  309. package/dist/timeline/labels.js +29 -6
  310. package/dist/timeline/origin.d.ts +1 -1
  311. package/dist/timeline/origin.js +2 -2
  312. package/dist/timeline/render-text.js +1 -1
  313. package/dist/timeline/timeline.d.ts +66 -4
  314. package/dist/timeline/timeline.js +160 -30
  315. package/dist/timeline/util.d.ts +5 -0
  316. package/dist/timeline/util.js +44 -8
  317. package/dist/timeline/web-calls.d.ts +17 -0
  318. package/dist/timeline/web-calls.js +106 -0
  319. package/dist/tool-gate.d.ts +42 -42
  320. package/dist/tool-gate.js +97 -91
  321. package/dist/tool-list.d.ts +4 -1
  322. package/dist/tool-list.js +8 -1
  323. package/dist/tool-names.d.ts +18 -13
  324. package/dist/tool-names.js +19 -17
  325. package/dist/tool-plane.d.ts +17 -13
  326. package/dist/tool-plane.js +12 -5
  327. package/dist/tools.d.ts +44 -16
  328. package/dist/tools.js +28 -28
  329. package/dist/trigger-adapter.d.ts +85 -5
  330. package/dist/trigger-adapter.js +6 -0
  331. package/dist/trigger-adapters.js +3 -1
  332. package/dist/trigger-composio.d.ts +10 -0
  333. package/dist/trigger-composio.js +122 -0
  334. package/dist/trigger-email.d.ts +4 -0
  335. package/dist/trigger-email.js +228 -0
  336. package/dist/trigger-signatures.d.ts +6 -10
  337. package/dist/trigger-signatures.js +16 -16
  338. package/dist/trigger-targets.d.ts +1 -1
  339. package/dist/trigger-targets.js +4 -3
  340. package/dist/trigger-webhook.js +6 -4
  341. package/dist/triggers.d.ts +94 -9
  342. package/dist/triggers.js +263 -62
  343. package/dist/uploads.d.ts +9 -0
  344. package/dist/uploads.js +27 -0
  345. package/dist/validate.js +1 -7
  346. package/dist/web-fake.d.ts +56 -0
  347. package/dist/web-fake.js +102 -0
  348. package/dist/web-fetch-direct.d.ts +3 -0
  349. package/dist/web-fetch-direct.js +4 -1
  350. package/dist/web-fetch.d.ts +5 -1
  351. package/dist/web-fetch.js +8 -31
  352. package/dist/web-search.d.ts +51 -2
  353. package/dist/web-search.js +116 -18
  354. package/dist/webhooks.d.ts +2 -1
  355. package/dist/webhooks.js +5 -1
  356. package/dist/workflow/node-runner.js +10 -2
  357. package/dist/workspace/archil-claim.d.ts +3 -0
  358. package/dist/workspace/archil-claim.js +9 -2
  359. package/dist/workspace/computer-deps.d.ts +22 -9
  360. package/dist/workspace/computer-deps.js +78 -37
  361. package/dist/workspace/computer-for-claim.d.ts +54 -4
  362. package/dist/workspace/computer-for-claim.js +179 -39
  363. package/dist/workspace/computer-janitor.d.ts +10 -3
  364. package/dist/workspace/computer-janitor.js +96 -29
  365. package/dist/workspace/computer-kept.d.ts +82 -0
  366. package/dist/workspace/computer-kept.js +147 -0
  367. package/dist/workspace/computer-mcp.js +4 -3
  368. package/dist/workspace/computer-ports.d.ts +23 -3
  369. package/dist/workspace/computer-ports.js +115 -5
  370. package/dist/workspace/index.d.ts +1 -2
  371. package/dist/workspace/index.js +1 -2
  372. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  373. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  374. package/dist/workspace/resolve-computer.d.ts +15 -3
  375. package/dist/workspace/resolve-computer.js +10 -7
  376. package/dist/workspace/revision-skills.d.ts +6 -2
  377. package/dist/workspace/revision-skills.js +12 -5
  378. package/dist/workspace/run-end-computers.d.ts +30 -0
  379. package/dist/workspace/run-end-computers.js +137 -0
  380. package/dist/workspace/run-tools.d.ts +28 -29
  381. package/dist/workspace/run-tools.js +29 -30
  382. package/dist/wrap-up.d.ts +19 -5
  383. package/dist/wrap-up.js +31 -4
  384. package/package.json +13 -9
  385. package/skills/agentrun-serve/SKILL.md +248 -10
  386. package/templates/README.md +117 -23
  387. package/templates/TOOLS.md +168 -0
  388. package/templates/code-review/agent.md +18 -4
  389. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  390. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  391. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  392. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  393. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  394. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  395. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  396. package/templates/code-review/skills/review/DEEP.md +2 -2
  397. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  398. package/templates/code-review/skills/review/SKILL.md +7 -3
  399. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  400. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  401. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  402. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  403. package/dist/console/assets/index-CjqQirbo.css +0 -1
  404. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  405. package/dist/host-calls.d.ts +0 -20
  406. package/dist/host-calls.js +0 -12
  407. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  408. package/dist/runner/adapters/pi-computer.js +0 -51
  409. package/dist/workspace/computer-script.d.ts +0 -53
  410. 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,9 @@ 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";
138
+ import { mcpNameOf as mcpToolOf, mcpToolName } from "./tool-names.js";
124
139
  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";
140
+ import { applyBodyOf, choiceUnrunnable, COMPUTER_FIX, compiled, githubTriggerUnconnected, githubTriggerWords, madeTriggerIssues, mcpSetUp, onServerName, onServers, packageDetail, packageModel, packageTiers, packageView, pickComputer, readPackages, serversFor, TemplateRegistry } from "./templates.js";
126
141
  import { deleteTemplate, importTemplate, loadImported } from "./template-import.js";
127
142
  import { templateInstallLink, templateLink } from "./console-links.js";
128
143
  import { GITHUB_HOSTS } from "./template-source.js";
@@ -134,12 +149,15 @@ import { readApprovers, writeApprovers } from "./server-approvers.js";
134
149
  import { MAX_FILES_PER_RUN, MAX_UPLOAD_BYTES, Uploads, UPLOADS_DIR } from "./uploads.js";
135
150
  import { entryAt, listFiles, sendFile as sendWorkspaceFile, viewOf } from "./run-files.js";
136
151
  import { heldRoute, holdIssues, runComputerRead } from "./computer-held-routes.js";
137
- import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runViewedKind } from "./computer-routes.js";
152
+ import { COMPUTER_ROUTES, computerHoldOf, computerRoute, runComputerKind } from "./computer-routes.js";
138
153
  import { ATTACH_PATH, AttachHub, PROVIDERS as COMPUTER_PROVIDERS, SETTING_KINDS, servingRefusals } from "@parcha/agentrun-computer";
139
154
  import { createAttachRoutes, pairedView } from "./computer-attach.js";
140
155
  import { pairedRefusal, withPaired } from "./workspace/attached-computers.js";
141
156
  import { COMPUTER_TOOLS, hostToolDefs } from "@parcha/agentrun-kernel/kernel";
157
+ import { freeModelRequestsOf } from "@parcha/agentrun-kernel/kernel/cap";
142
158
  import { archilRoute, createArchilRoutes, liveRunsOnDisk } from "./archil-routes.js";
159
+ import { noAccount, openAccount } from "./email/account.js";
160
+ import { emailRoute } from "./email/routes.js";
143
161
  import { agentDiskOf, ARCHIL_DISK_ID, archilSettingsFromEnv, inArchilMode } from "./archil-settings.js";
144
162
  import { computerOfPlace } from "./computer-setting.js";
145
163
  import { computerCapabilities, createComputerRoutes, folderModeOf, hostCommandRefusals, settingsComputerRoute } from "./computers.js";
@@ -206,6 +224,25 @@ const digest = (text) => createHash("sha256").update(text).digest();
206
224
  const sha256Hex = (text) => createHash("sha256").update(text).digest("hex");
207
225
  const SESSION_S = SESSION_MS / 1000;
208
226
  export const ROUTES = [
227
+ { method: "GET", pattern: /^\/observations$/, name: "getObservations" },
228
+ { method: "GET", pattern: /^\/connectors$/, name: "listRemoteConnectors" },
229
+ { method: "POST", pattern: /^\/connectors\/enrollment$/, name: "enrollRemoteConnector" },
230
+ { method: "POST", pattern: /^\/connectors$/, name: "registerRemoteConnector" },
231
+ { method: "DELETE", pattern: /^\/connectors\/([^/]+)$/, name: "revokeRemoteConnector" },
232
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/import$/, name: "importRemoteTarget" },
233
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/targets\/([^/]+)\/history$/, name: "importRemoteHistory" },
234
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/poll$/, name: "pollRemoteConnector" },
235
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/events$/, name: "remoteCommandEvents" },
236
+ { method: "POST", pattern: /^\/connectors\/([^/]+)\/commands\/([^/]+)\/complete$/, name: "completeRemoteCommand" },
237
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/sdk-runs$/, name: "startSdkRun" },
238
+ { method: "GET", pattern: /^\/sdk-runs\/([^/]+)$/, name: "getSdkRun" },
239
+ { method: "POST", pattern: /^\/sdk-runs\/([^/]+)\/events$/, name: "sdkRunEvents" },
240
+ { method: "POST", pattern: /^\/sdk-runs\/([^/]+)\/complete$/, name: "completeSdkRun" },
241
+ { method: "POST", pattern: /^\/native\/discover$/, name: "discoverNative" },
242
+ { method: "POST", pattern: /^\/native\/connect$/, name: "connectNative" },
243
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/native$/, name: "getNative" },
244
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/native\/verify$/, name: "verifyNative" },
245
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/native\/disconnect$/, name: "disconnectNative" },
209
246
  { method: "GET", pattern: /^\/capabilities$/, name: "getCapabilities" },
210
247
  { method: "GET", pattern: /^\/openapi\.json$/, name: "getOpenapi" },
211
248
  // Answered here only with accounts off: with accounts on, the owner's routes answer it before any route (ownerRoute).
@@ -288,12 +325,27 @@ export const ROUTES = [
288
325
  { method: "GET", pattern: /^\/settings\/tool-keys$/, name: "listToolKeys" },
289
326
  { method: "PUT", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "saveToolKey" },
290
327
  { method: "DELETE", pattern: /^\/settings\/tool-keys\/([^/]+)$/, name: "deleteToolKey" },
328
+ // The server's email account (email/routes.ts): the owner's session's alone, its password in no answer.
329
+ { method: "GET", pattern: /^\/settings\/email$/, name: "getEmailAccount" },
330
+ { method: "PUT", pattern: /^\/settings\/email$/, name: "saveEmailAccount" },
331
+ { method: "DELETE", pattern: /^\/settings\/email$/, name: "deleteEmailAccount" },
332
+ { method: "POST", pattern: /^\/settings\/email\/test$/, name: "testEmailAccount" },
333
+ { method: "GET", pattern: /^\/settings\/chatgpt$/, name: "getChatGPTSignIn" },
334
+ { method: "DELETE", pattern: /^\/settings\/chatgpt$/, name: "signOutChatGPT" },
335
+ { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in$/, name: "startChatGPTSignIn" },
336
+ { method: "POST", pattern: /^\/settings\/chatgpt\/sign-in\/finish$/, name: "finishChatGPTSignIn" },
291
337
  { method: "GET", pattern: /^\/settings\/mcp-servers$/, name: "listMcpServers" },
292
338
  { method: "POST", pattern: /^\/settings\/mcp-servers\/preview$/, name: "previewMcpServer" },
293
339
  { method: "POST", pattern: /^\/settings\/mcp-servers\/composio\/tools$/, name: "listComposioTools" },
294
340
  { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "getMcpServer" },
295
341
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "saveMcpServer" },
296
342
  { method: "PUT", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio$/, name: "saveComposioServer" },
343
+ // A saved Composio server's triggers (composio-triggers.ts): its toolkit's events, its triggers and their state on
344
+ // Composio, and the project's webhook subscription (its secret rotated, or the subscription deleted: secret writes).
345
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/events$/, name: "listComposioEvents" },
346
+ { method: "GET", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/triggers$/, name: "listComposioTriggers" },
347
+ { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/rotate-secret$/, name: "rotateComposioSecret" },
348
+ { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)\/composio\/subscription$/, name: "deleteComposioSubscription" },
297
349
  { method: "DELETE", pattern: /^\/settings\/mcp-servers\/([^/]+)$/, name: "deleteMcpServer" },
298
350
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/refresh$/, name: "refreshMcpServer" },
299
351
  { method: "POST", pattern: /^\/settings\/mcp-servers\/([^/]+)\/oauth\/start$/, name: "startMcpOAuth" },
@@ -324,7 +376,8 @@ export const ROUTES = [
324
376
  { method: "DELETE", pattern: /^\/templates\/([^/]+)$/, name: "deleteTemplate" },
325
377
  { method: "POST", pattern: /^\/templates\/([^/]+)\/apply$/, name: "applyTemplate" },
326
378
  // Answered before the bearer check: the request's signature is its credential.
327
- { method: "POST", pattern: /^\/hooks\/([^/]+)$/, name: "receiveHook" },
379
+ // A source that keeps its key per scope (Composio's projects) is served at /hooks/{source}/{scope}.
380
+ { method: "POST", pattern: /^\/hooks\/([^/]+)(?:\/([^/]+))?$/, name: "receiveHook" },
328
381
  { method: "GET", pattern: /^\/integrations\/github$/, name: "getGitHubConnection" },
329
382
  { method: "DELETE", pattern: /^\/integrations\/github$/, name: "disconnectGitHub" },
330
383
  { method: "POST", pattern: /^\/integrations\/github\/connect$/, name: "connectGitHub" },
@@ -351,6 +404,8 @@ export const ROUTES = [
351
404
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/files\/([^/]+)\/restore$/, name: "restoreLearningFile" },
352
405
  { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions$/, name: "listLearnedWorkflowRevisions" },
353
406
  { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/promote$/, name: "promoteLearnedWorkflow" },
407
+ { method: "POST", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays$/, name: "startLearnedWorkflowReplay" },
408
+ { method: "GET", pattern: /^\/agents\/([^/]+)\/learning\/workflows\/([^/]+)\/revisions\/([^/]+)\/replays\/([^/]+)$/, name: "getLearnedWorkflowReplay" },
354
409
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning$/, name: "getRunLearning" },
355
410
  { method: "GET", pattern: /^\/runs\/([^/]+)\/learning\/diff$/, name: "getRunLearningDiff" },
356
411
  ];
@@ -360,15 +415,19 @@ export const ROUTES = [
360
415
  * kept plane's (a run from before the plane names none, and is Browserbase's where it grants the tool) checked again as a
361
416
  * launch would be; off, saying why, where it has none or its browser resolves unavailable here. Where the agent's
362
417
  * computer is a browser, that browser, whose keys are the computer's (checked at the run's start), never the plane's.
418
+ * A run whose agent's computer is a sandbox (`own`, its revision's kind) and has no browser has a computer with no
419
+ * screen: off says so, never that its agent has none; its browser, where it has the tool, is its view, and why that
420
+ * browser is unavailable is said as for any run.
363
421
  * TODO: the agent's own `computer: {kind, provider?}` setting once definitions carry it (desktop, phone). */
364
- function computerOf(kept, env, family = "computer") {
422
+ function computerOf(kept, env, family = "computer", own) {
365
423
  if (kept === ON_COMPUTER)
366
424
  return { kind: "browser" };
367
425
  const browser = kept === undefined ? undefined : recheckPlane({ browser: kept }, env).browser;
368
426
  if (browser === undefined)
369
- return { off: family === "browser" ? "this run's agent has no browser tool" : "this run's agent has no computer" };
427
+ return { off: family === "browser" ? "this run's agent has no browser tool" : own === "sandbox" ? SANDBOX_NO_SCREEN : "this run's agent has no computer" };
370
428
  return isUnavailable(browser) ? { off: whyUnavailable(browser) } : { kind: "browser" };
371
429
  }
430
+ const SANDBOX_NO_SCREEN = "A sandbox has no screen: what the agent runs in it is on the timeline.";
372
431
  /** The run's kept browser vendor, over the store, as computerOf reads it: the vendor its launch plane resolved at start
373
432
  * (the same source the runner's claim reads), normalized to the vendor name (keptVendor) so recheckPlane re-resolves it as
374
433
  * 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 +479,18 @@ export function offersEnvOf(env) {
420
479
  /** What of `env` a write can change that the harnesses' offers are made from: each secret but the tool keys' fields (a
421
480
  * saved key is one of those; the rest of the environment is the server's start's). Held to tell whether a write needs
422
481
  * the offers probed again, never shown. */
423
- const offersInputs = (env) => SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]);
482
+ const offersInputs = (env) => [...SECRET_NAMES.filter((name) => !TOOL_FIELDS.includes(name)).map((name) => env[name]), planOf(env)?.state, planOf(env)?.models.join(" ")];
483
+ /** A sign-in step's answer; its refusal (a stale or bad pasted address, no sign-in waiting, OpenAI's no) a 400 in words. */
484
+ async function planStep(step) {
485
+ try {
486
+ return await step();
487
+ }
488
+ catch (error) {
489
+ if (error instanceof PlanSignInRefused)
490
+ throw new ApiError("bad_request", error.message);
491
+ throw error;
492
+ }
493
+ }
424
494
  async function needsOf(env) {
425
495
  const chosen = await chooseModel(env, undefined);
426
496
  if ("why" in chosen)
@@ -559,6 +629,9 @@ function capabilitiesWith(env, maxRuns, harnesses, learning, { needs, priced },
559
629
  idempotency_ttl_s: IDEMPOTENCY_TTL_S,
560
630
  input_wait_s: null,
561
631
  max_cost_usd: null,
632
+ // The most requests on free models a run makes (AGENTRUN_FREE_MODEL_REQUESTS, else 60): each costs $0, so the
633
+ // dollar cap cannot stop them, and this does (the kernel cap's free.ts). ChatGPT-plan requests don't count.
634
+ free_model_requests: freeModelRequestsOf(env),
562
635
  },
563
636
  };
564
637
  }
@@ -615,6 +688,8 @@ export async function startServe(options) {
615
688
  const maxRuns = maxRunsOf(process.env, options.maxRuns);
616
689
  const learning = learningOf(process.env, options.learning);
617
690
  const learningBudget = learningBudgetOf(process.env, options.learningBudget);
691
+ // A limit on a run's requests on free models that is no whole number above 0 stops the start, naming its variable.
692
+ freeModelRequestsOf(process.env);
618
693
  const minFreeMib = process.env.AGENTRUN_MIN_FREE_MB ? Number(process.env.AGENTRUN_MIN_FREE_MB) : MIN_FREE_MIB;
619
694
  if (!(Number.isFinite(minFreeMib) && minFreeMib >= 0))
620
695
  throw new Error("AGENTRUN_MIN_FREE_MB is a number of MiB, 0 or more");
@@ -707,11 +782,15 @@ async function startHolding(options, data, checked, stops) {
707
782
  warn: (message) => void process.stderr.write(`agentrun-serve: ${message}\n`),
708
783
  ...(options.onStoreLost ? { onOwnerLost: options.onStoreLost } : {}),
709
784
  }), (error) => onSqlite && error instanceof StoreOwned, replacedUntil, waitingForReplaced);
710
- stops.push(() => store.close());
785
+ let stopObservationRetention = async () => undefined;
786
+ stops.push(async () => { await stopObservationRetention(); await store.close(); });
711
787
  // The packages served: the bundled ones, read and checked before the start, and those imported here, which the store
712
788
  // keeps and are checked again as they load (template-import.ts). One that no longer checks is left out, said in the log.
713
789
  const registry = new TemplateRegistry(templates);
714
790
  await loadImported({ registry, store }, (id, why) => log?.(logLine("template_import_skipped", { template: id, why })));
791
+ stopObservationRetention = await maintainObservations(new Observations(store), {
792
+ onError: () => { process.stderr.write("agentrun-serve: observation retention failed; retrying on the next sweep\n"); },
793
+ });
715
794
  // The person's own computers paired with this server (computer-attach.ts): their live sockets are this process's hub,
716
795
  // which the runner beside the server shares (Serve.attachHub), so one process holds them. A second server on this
717
796
  // store is refused above (its owner lock).
@@ -798,7 +877,12 @@ async function startHolding(options, data, checked, stops) {
798
877
  // settings, caps; a save or delete of a key, env and caps, and the offers only when what they are made from changed,
799
878
  // which no tool key is. So a write answers at once, and capabilities, save checks and run checks after it see it, with
800
879
  // 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));
880
+ // The ChatGPT sign-in, sealed in the store: on every reading of env (chatgpt-plan.ts withPlan), so a plan model runs
881
+ // where it is signed in. A sign-in, a sign-out or an expiry it sees makes the reading again, as a key's save does.
882
+ const plan = new ChatGPTPlan({ store, sealKey: seal.key, log: (fields) => (log ? log(logLine("chatgpt", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("chatgpt", fields)}\n`)), changed: () => keysChanged() });
883
+ await plan.load();
884
+ stops.push(async () => plan.close());
885
+ let env = withPlan(own(withSecrets(base, "all", storedKeys)), plan);
802
886
  let offers;
803
887
  let caps;
804
888
  // Whether a revision that names no model runs (needsOf): made from env alone, so remade with it, before the caps.
@@ -830,7 +914,7 @@ async function startHolding(options, data, checked, stops) {
830
914
  const keysChanged = async () => {
831
915
  // A run's learning, view, list and timeline row are cut of the keys saved now by the run view at read time (it reads
832
916
  // serverSecrets live, store-view), so a key change needs no cache invalidation here.
833
- env = own(withSecrets(base, "all", storedKeys));
917
+ env = withPlan(own(withSecrets(base, "all", storedKeys)), plan);
834
918
  const mine = ++needsAsked;
835
919
  const next = await needsOf(env);
836
920
  if (mine === needsAsked)
@@ -841,6 +925,12 @@ async function startHolding(options, data, checked, stops) {
841
925
  else
842
926
  await probe("key");
843
927
  };
928
+ /** The sign-in as the store holds it now: a runner may have renewed it, or found it expired. A change reads env again. */
929
+ const planNow = async () => {
930
+ const was = plan.state;
931
+ if ((await plan.load()).state !== was)
932
+ await keysChanged();
933
+ };
844
934
  // The boxes a place may name, read once from the computers runs execute on (place-offers.ts): AGENTRUN_BOXES lists
845
935
  // them, docker alone when it is not set; docker by its probe, daytona and modal by their providers' keys, read as a
846
936
  // run's claim reads them. Under --faux, `fauxDocker` stands in for Docker's answer, and nothing asks Docker.
@@ -1023,6 +1113,16 @@ async function startHolding(options, data, checked, stops) {
1023
1113
  };
1024
1114
  ({ secrets: secretStores, settings: triggerSettings } = await openServerSecretsOverStore(store, data, env, adapters, (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`))));
1025
1115
  secretStores.add("server", () => [token]);
1116
+ // The email account's password (email/account.ts), and each one saved since this server started: cut from everything
1117
+ // it shows, so a tool's error or a model's text that ever echoed it shows it nowhere.
1118
+ const emailPasswords = new Set();
1119
+ const heldEmailPassword = async () => {
1120
+ const password = (await openAccount(store, sealKey).catch(() => undefined))?.password;
1121
+ if (password)
1122
+ emailPasswords.add(password);
1123
+ };
1124
+ await heldEmailPassword();
1125
+ secretStores.add("email", () => [...emailPasswords]);
1026
1126
  // Each agent's saved sign-ins, over the one store (module A, sign-ins-store): the vendor's calls on the server's keys
1027
1127
  // (under faux, the vendor's fake alone), under this server's seal key. The store holds whether a sign-in is still held
1028
1128
  // (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 +1166,16 @@ async function startHolding(options, data, checked, stops) {
1066
1166
  const lock = options.harnessLocks?.[entry.id];
1067
1167
  // npm past its SIGTERM's grace (it waits on a tarball once it writes): killed, and the line says so.
1068
1168
  const onKilled = () => log?.(logLine("harness_install_killed", { harness: entry.id, said: `npm did not stop within ${NPM_STOP_GRACE_MS / 1000} s of SIGTERM; killed` }));
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) => {
1169
+ return [entry.id, new HarnessInstall(entry, installDirOf(data, entry.id), pins, options.harnessInstall ?? ((entry, dir, pins, signal) => npmInstall(entry, dir, pins, { signal, onKilled, ...(lock ? { lock } : {}) })), (ms) => {
1070
1170
  log?.(logLine("harness_installed", { harness: entry.id, ms, dir: installDirOf(data, entry.id) }));
1071
1171
  void probe(`${entry.id}_installed`).catch(() => undefined);
1072
1172
  })];
1073
1173
  }));
1174
+ // Each harness found installed as this server starts has what earlier installs left beside it swept (HarnessInstall
1175
+ // needed): the point sure to come after an install that could not remove one (a crashed server's npm still writing in
1176
+ // it), since no install runs again until the pin changes. Not waited for; the close waits for it (install.stop).
1177
+ for (const install of Object.values(installs))
1178
+ void install.needed().catch(() => undefined);
1074
1179
  // A capped start prices each OpenRouter Decisions model a workflow pins (runnable.ts) from OpenRouter's public catalog,
1075
1180
  // read once for this server (and again after a read that failed), through the faux one under --faux.
1076
1181
  let pricing;
@@ -1089,7 +1194,7 @@ async function startHolding(options, data, checked, stops) {
1089
1194
  // no box relay here — a runner (its own process, sharing only this store) claims and runs every run. The leaves a start
1090
1195
  // needs that live in this request layer are gathered once as StartDeps; the run's model is resolved once, now (the runner
1091
1196
  // reads launch.model alone).
1092
- const modelOf = (_entry, revision) => runModelRef(env, revision);
1197
+ const modelOf = (_entry, revision) => nativeOf(revision.body) ? Promise.resolve(undefined) : runModelRef(env, revision);
1093
1198
  const startDeps = {
1094
1199
  runBodyIssues,
1095
1200
  boundRepos: async (agentId) => bindingOf(await store.triggers.list(agentId), agentId),
@@ -1153,12 +1258,13 @@ async function startHolding(options, data, checked, stops) {
1153
1258
  },
1154
1259
  shown: () => secretsShown(serverSecrets(), { local: true }),
1155
1260
  };
1156
- /** What a learning batch's loop reads of a run, from its view. */
1261
+ /** What a learning batch's loop reads of a run, from its view. Its `cost_usd` is the exact cost: a batch's figures say
1262
+ * no "at most", so a view cost marked `upper_bound` reads null there, as the run's stored cost does (RunRow.costUsd). */
1157
1263
  const batchRunView = async (runId) => {
1158
1264
  const v = (await viewOverStore(store, runId, viewDepsFor(ownOriginOf())));
1159
1265
  if (!v)
1160
1266
  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 };
1267
+ return { status: String(v.status), ended_at: v.ended_at ?? null, answer: typeof v.result?.final_answer === "string" ? v.result.final_answer : null, cost_usd: typeof v.cost?.usd === "number" && v.cost.upper_bound !== true ? v.cost.usd : null, learning_state: typeof v.learning?.state === "string" ? v.learning.state : null, error: typeof v.error?.message === "string" ? v.error.message : null };
1162
1268
  };
1163
1269
  // Learn from a CSV (learning-batch.ts): a batch's loop runs in this process over the run write half and the run view; its
1164
1270
  // 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 +1354,7 @@ async function startHolding(options, data, checked, stops) {
1248
1354
  // shows and each browser sign-in pointer the run was handed; its decision rows among them, its error rows in the
1249
1355
  // error's words. A run whose hand can't be read back here is withheld: none of its rows. A run's Timeline is read
1250
1356
  // 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),
1357
+ timelineRows: (forStore, runId, context, calls) => servedTimelineRows({ serverSecrets, signIns, keyEnv: () => own(withSecrets(process.env, "all", storedKeys)), statuses }, forStore, runId, context, calls),
1252
1358
  runView: (forStore, runId) => viewOverStore(forStore, runId, viewDepsFor(ownOriginOf())),
1253
1359
  });
1254
1360
  const triggerDeps = {
@@ -1385,7 +1491,9 @@ async function startHolding(options, data, checked, stops) {
1385
1491
  clock: options.triggerClock,
1386
1492
  ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1387
1493
  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),
1494
+ unavailable: async (kind) => (kind === "github" && !githubConnection() ? new ApiError("github_not_connected", "This server has no GitHub App: Connect GitHub in Settings, then make the trigger (or turn it on).") : kind === "email" && !(await openAccount(store, sealKey)) ? noAccount() : undefined),
1495
+ // The email trigger's account, its password opened as it polls (email/account.ts): never kept in the engine.
1496
+ credentials: async (kind) => (kind === "email" ? openAccount(store, sealKey) : undefined),
1389
1497
  say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1390
1498
  // The trigger target policy (what a trigger may start or message, and in what words it is refused) is the one store's
1391
1499
  // (trigger-targets.ts, over the run write half and the run view): targetIssues, start, message, statusOf, runOf. The
@@ -1393,6 +1501,17 @@ async function startHolding(options, data, checked, stops) {
1393
1501
  ...targets,
1394
1502
  settings: (adapterId) => triggerSettings.get(adapterId),
1395
1503
  notify: (failed, key) => webhooks.emitTrigger(failed, key),
1504
+ // A Composio trigger's instance, and the project's subscription, are made and kept on Composio with its server's key.
1505
+ upstream: (kind) => (kind === "composio" ? composioTriggers : undefined),
1506
+ });
1507
+ const composioTriggers = new ComposioTriggers({
1508
+ control: options.composioControl ?? {},
1509
+ ...(options.publicUrl ? { publicUrl: options.publicUrl.replace(/\/+$/, "") } : {}),
1510
+ sealed: triggerSettings.get("composio"),
1511
+ credential: (name, refusal) => mcpServers.composioOf(name, refusal),
1512
+ holders: () => triggers.ofKind("composio"),
1513
+ signal: stopping.signal,
1514
+ say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)),
1396
1515
  });
1397
1516
  // A repair of the GitHub installations (below) stops before the triggers close, in a start that fails as in close.
1398
1517
  stops.push(() => githubConnect.close());
@@ -1509,7 +1628,7 @@ async function startHolding(options, data, checked, stops) {
1509
1628
  throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
1510
1629
  return Buffer.concat(chunks);
1511
1630
  }
1512
- async function bodyOf(req) {
1631
+ async function bodyOf(req, max = MAX_BODY) {
1513
1632
  // Read once: the secret-write check reads a registered operation's body before its route does (secret-writes.ts).
1514
1633
  const read = bodies.get(req);
1515
1634
  if (read !== undefined)
@@ -1517,7 +1636,7 @@ async function startHolding(options, data, checked, stops) {
1517
1636
  const type = String(req.headers["content-type"] ?? "");
1518
1637
  if (!type.startsWith("application/json"))
1519
1638
  throw new ApiError("unsupported_media_type", "the body must be application/json");
1520
- const bytes = await bytesOf(req);
1639
+ const bytes = await bytesOf(req, max);
1521
1640
  let value;
1522
1641
  try {
1523
1642
  value = JSON.parse(bytes.toString("utf8") || "null");
@@ -1537,24 +1656,19 @@ async function startHolding(options, data, checked, stops) {
1537
1656
  const revision = (entry ?? (await needAgent(id))).revision;
1538
1657
  if (revision?.kind !== "agentic")
1539
1658
  return { tools: [], gated: {}, deniedBy: {} };
1540
- const [{ learnedDraftTools, mcpGrantsListed }, { permissionFrom }, { learnedAskFits }] = await Promise.all([import("./tools.js"), import("./tool-gate.js"), import("./learned-workflow.js")]);
1659
+ const [{ learnedDraftTools }, { permissionFrom }] = await Promise.all([import("./tools.js"), import("./tool-gate.js")]);
1541
1660
  const server = settings.get();
1542
1661
  // The revision row's body is the agentic body JSON (store-backed RevisionRow types it as unknown).
1543
1662
  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
1663
  const gate = (name) => permissionFrom(name, server, (body.toolSettings ?? {}), body.approvals === "never" ? "never" : "ask");
1548
1664
  // `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 };
1665
+ const { tools, gated, deniedBy } = learnedDraftTools(body.tools ?? [], (name) => gate(name).permission, undefined, (name) => gate(name).from, { mcp: true, approvers: await readApprovers(store.settings) });
1552
1666
  // A draft's decision nodes (LS-07), as a run's learning end checks them: on this server's decision providers (its
1553
1667
  // keys, saved ones among them: env), each held to the gate by its bare id; deny alone refuses one.
1554
1668
  const [{ decisionProvidersIn }, { DECISION_PROVIDER_KEYS }] = await Promise.all([import("./decisions.js"), import("./tool-plane.js")]);
1555
1669
  const providers = await decisionProvidersIn(env);
1556
1670
  if (!providers)
1557
- return { tools, gated, deniedBy, ask };
1671
+ return { tools, gated, deniedBy };
1558
1672
  const decided = {};
1559
1673
  const decisionDeniedBy = {};
1560
1674
  for (const provider of DECISION_PROVIDER_KEYS) {
@@ -1565,7 +1679,7 @@ async function startHolding(options, data, checked, stops) {
1565
1679
  if (permission === "deny")
1566
1680
  decisionDeniedBy[provider] = from;
1567
1681
  }
1568
- return { tools, gated, deniedBy, ask, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1682
+ return { tools, gated, deniedBy, decisions: { providers: providers.providers, default: providers.default, gated: decided, deniedBy: decisionDeniedBy } };
1569
1683
  }
1570
1684
  async function needAgent(id) {
1571
1685
  const entry = ID.test(id) ? await agents.get(id) : null;
@@ -1573,13 +1687,24 @@ async function startHolding(options, data, checked, stops) {
1573
1687
  throw new ApiError("not_found", `no agent ${id}`);
1574
1688
  return entry;
1575
1689
  }
1690
+ /** The agent `id` (needAgent), refused when it is archived (409 agent_not_runnable): every route that starts its runs,
1691
+ * a person's start (createRun) and a replay's (startLearnedWorkflowReplay), asks this before it reserves or writes anything. */
1692
+ async function needRunnableAgent(id) {
1693
+ const entry = await needAgent(id);
1694
+ if (entry.agent.archivedAt)
1695
+ throw new ApiError("agent_not_runnable", `The agent ${id} is archived: unarchive it to run it.`, { details: { archived_at: new Date(entry.agent.archivedAt).toISOString() } });
1696
+ return entry;
1697
+ }
1576
1698
  /** An agent view's extra fields (agents-store agentView): its saved sign-ins, its learning count, and its run counts.
1577
1699
  * The run counts read the store's runs (store-reads/runs.ts listRuns): `count` is every run the agent has, `live` those
1578
1700
  * still running (runReadState 'running': queued, running or parked), the same numbers the file-backed view showed. */
1579
1701
  const agentExtra = async (entry) => {
1580
1702
  const learning = await learningOfAgent(entry);
1703
+ const native = nativeOf(entry.revision?.body);
1704
+ const nativeStatus = native?.remote ? await new RemoteConnectors(store).status(native) : undefined;
1581
1705
  const runs = await listRunsOverStore(store, { agent: entry.agent.id }, ctx);
1582
1706
  return {
1707
+ ...(nativeStatus ? { nativeStatus } : {}),
1583
1708
  signIns: await signIns.view(entry.agent.id),
1584
1709
  ...(learning ? { learning } : {}),
1585
1710
  runs: { count: runs.length, live: runs.filter((run) => run.state === "running").length },
@@ -1663,6 +1788,28 @@ async function startHolding(options, data, checked, stops) {
1663
1788
  * starts with the checks a save makes (runnable.ts): one a save refused, or one a setting of this host fixes that it
1664
1789
  * does not have yet. `capped`: the run has a spend cap, which a web tool's resolution reads (tool-plane.ts). */
1665
1790
  async function runnable(revision, place, { capped = false } = {}) {
1791
+ if (sdkOf(revision.body))
1792
+ throw new ApiError("agent_not_runnable", "This agent runs in its backend SDK. Call its SDK wrapper to start a task; AgentRun does not launch its tools or credentials.");
1793
+ const native = nativeOf(revision.body);
1794
+ if (native) {
1795
+ const overrides = nativeModelOverrides(revision.body);
1796
+ if (overrides.length)
1797
+ throw new ApiError("agent_not_runnable", NATIVE_MODEL_SETTINGS_UNSUPPORTED, { fields: overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })) });
1798
+ const execution = nativeExecutionOverrides(revision.body);
1799
+ if (execution.length)
1800
+ throw new ApiError("agent_not_runnable", NATIVE_EXECUTION_SETTINGS_UNSUPPORTED, { fields: execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })) });
1801
+ if ((revision.body.maxToolCalls ?? 0) > 0)
1802
+ throw new ApiError("agent_not_runnable", NATIVE_TOOL_BUDGET_UNSUPPORTED, { fields: [{ field: "definition.max_tool_calls", reason: "not_an_option", message: NATIVE_TOOL_BUDGET_UNSUPPORTED }] });
1803
+ if (!native.remote && (options.apiOnly || options.publicUrl || !isLoopback(host)))
1804
+ throw new ApiError("agent_not_runnable", "Native connections run only on an AgentRun server bound to loopback on the source machine, without a public URL.");
1805
+ if (capped)
1806
+ throw new ApiError("agent_not_runnable", "Native runs retain their own limits; AgentRun cannot enforce a dollar cap on this connection. Remove max_cost_usd and use native limits.");
1807
+ if (native.remote)
1808
+ await new RemoteConnectors(store).assertReady(native);
1809
+ else
1810
+ await launchNative(native);
1811
+ return;
1812
+ }
1666
1813
  const shape = { ...shapeOf(revision), place, ...(revision.body.place ? {} : { unnamed: true }) };
1667
1814
  // An agentic revision's MCP tools are checked as its save pinned them (its pin, never the server's listing now), for
1668
1815
  // a server still saved here; a granted tool its pin does not hold is said first, with how to pin it.
@@ -1688,7 +1835,8 @@ async function startHolding(options, data, checked, stops) {
1688
1835
  return meta ? { ...tool, grantable: false, reason: meta.reason } : tool;
1689
1836
  });
1690
1837
  };
1691
- const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, decisionPrice });
1838
+ const monid = revision.monidPin ?? undefined;
1839
+ const blockers = await blockersOf(env, shape, settings.get(), { capped, boxes: boxOffers, computerReady, shellOf, offers, mcp: revision.kind === "agentic" ? pinnedTools : mcpTools, monid, decisionPrice });
1692
1840
  if (!blockers.length)
1693
1841
  return;
1694
1842
  const message = blockers.map((b) => b.message).join(" ");
@@ -1782,12 +1930,23 @@ async function startHolding(options, data, checked, stops) {
1782
1930
  return pin ? { ...revision, mcpPin: pin } : revision;
1783
1931
  }
1784
1932
  /** 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). */
1933
+ * its pins (mcpListingOf, monidPinOf), each carrying from `previous` what its grants did not change. A revision that
1934
+ * names no place is checked where it would run (fallbackPlace). */
1787
1935
  async function saveable(revision, previous) {
1788
1936
  // The store's NewRevision keeps the revision's fields under `body` (AgenticBody|WorkflowBody); build the flat shape the
1789
1937
  // host checks (runnable.ts RevisionShape) from it, as shapeOf does for a run's Revision.
1790
1938
  const body = revision.body;
1939
+ if (nativeOf(body)) {
1940
+ const overrides = nativeModelOverrides(body);
1941
+ if (overrides.length)
1942
+ throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
1943
+ const execution = nativeExecutionOverrides(body);
1944
+ if (execution.length)
1945
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
1946
+ return { warnings: [], stamp: {} };
1947
+ }
1948
+ if (sdkOf(body))
1949
+ return { warnings: [], stamp: {} };
1791
1950
  // An agent on a harness that installs on first use starts its install, if it is not in yet: its first run waits for less.
1792
1951
  const install = revision.kind === "agentic" ? installs[harnessOfBody(body)] : undefined;
1793
1952
  if (install) {
@@ -1795,51 +1954,44 @@ async function startHolding(options, data, checked, stops) {
1795
1954
  }
1796
1955
  const named = (revision.kind === "agentic" ? { kind: "agentic", ...body } : workflowShape(body));
1797
1956
  const shape = named.place ? named : { ...named, place: fallbackPlace(named.kind, named.tools ?? []), unnamed: true };
1798
- const listing = await mcpListingOf(revision, previous);
1957
+ const listing = await mcpListingOf(revision, previous?.mcpPin);
1799
1958
  const mcp = listing.tools;
1800
- const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp });
1959
+ const { monid, warnings: usage = [] } = (await monidPinOf(revision, previous)) ?? {};
1960
+ const blockers = await blockersOf(env, shape, settings.get(), { boxes: boxOffers, computerReady, shellOf, offers, mcp, monid });
1801
1961
  // An agent's default cap caps each run started without one of its own, and a web tool resolves by the cap: what a cap
1802
1962
  // alone keeps from running under the definition's own picks, whatever this host's settings, would keep every such run
1803
1963
  // from running, so the save is refused, not each run (claude-agent's or codex's own search, picked, under a cap).
1804
1964
  if ((body.maxCostUsd ?? 0) > 0) {
1805
1965
  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 });
1966
+ const plain = new Set((await blockersOf(env, shape, {}, { boxes: boxOffers, computerReady, shellOf, offers, mcp, monid })).map(key));
1967
+ const capped = await blockersOf(env, shape, {}, { capped: true, capUsd: body.maxCostUsd, boxes: boxOffers, computerReady, shellOf, offers, mcp, monid, decisionPrice });
1808
1968
  // 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.
1969
+ // agent saves and updates, and only a run under the cap is refused (409). So is a cap below what the model needs for
1970
+ // one more step and an answer (`short`): the agent saves, and its runs wrap up at their first tool call. A tool's
1971
+ // pick a cap rules out refuses it.
1810
1972
  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 })));
1973
+ blockers.push(...added.filter((b) => b.unpriced || b.short));
1974
+ blockers.push(...added.filter((b) => !b.unpriced && !b.short).map((b) => ({ ...b, reason: "not_an_option", fix: "Pick another provider for this tool in definition.tool_settings, or clear the agent's default cap (max_cost_usd: 0).", host: false })));
1813
1975
  }
1814
1976
  const never = blockers.filter((b) => !b.host);
1815
1977
  if (never.length)
1816
1978
  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
1979
  const mcpPin = listing.pin();
1842
- return { warnings: [...blockers.map(issueOf), ...leftOut], stamp: mcpPin ? { mcpPin } : {} };
1980
+ return { warnings: [...blockers.map(issueOf), ...usage], stamp: { ...(mcpPin ? { mcpPin } : {}), ...(monid ? { monidPin: monid } : {}) } };
1981
+ }
1982
+ /** An agentic `revision`'s monid pin (monid.ts pinMonid) and a warning per endpoint priced by usage; a grant that
1983
+ * cannot be pinned refuses the save (422). Undefined when it grants none. */
1984
+ async function monidPinOf(revision, previous) {
1985
+ if (revision.kind !== "agentic")
1986
+ return undefined;
1987
+ const tools = revision.body.tools ?? [];
1988
+ const send = await checkFetch("monid");
1989
+ const before = previous?.kind === "agentic" ? { grants: previous.body.tools ?? [], pin: previous.monidPin } : undefined;
1990
+ // The key as the server reads it (env: what it was started with, its handed secrets and its saved keys).
1991
+ const pinned = await pinMonid(tools, { key: env[MONID_KEY_ENV]?.trim(), fetch: send ?? (async () => { throw new Error("no fake of monid's API under faux"); }), signal: stopping.signal, ...(before ? { previous: before } : {}) });
1992
+ if (pinned && "refused" in pinned)
1993
+ throw invalid(pinned.refused.map(({ tool, message }) => ({ field: tools.includes(tool) ? `definition.tools[${tools.indexOf(tool)}]` : "definition.tools", reason: "not_an_option", message })));
1994
+ return pinned && { monid: pinned.pin, warnings: pinned.warnings.map(({ tool, message }) => ({ field: `definition.tools[${tools.indexOf(tool)}]`, reason: PRICED_BY_USAGE, message })) };
1843
1995
  }
1844
1996
  /** POST /agents' body made into its agent, as that route makes one, with what this host still lacks for it. A new agent
1845
1997
  * that names no place is given this server's box (place.ts newAgentPlace), stamped on its revision; one that names a
@@ -1856,6 +2008,28 @@ async function startHolding(options, data, checked, stops) {
1856
2008
  }, "place" in fresh ? { place: fresh.place, tools: NEW_AGENT_TOOLS } : undefined, template);
1857
2009
  return { entry, warnings };
1858
2010
  }
2011
+ /** A replay's ports for agent `entry` (runner/promotion.ts askReplay, replayView): its learning folder where this server
2012
+ * reads it, cut of the host's secrets as the learning reads cut them, and a replay run's launch made as a run's start
2013
+ * makes one now (prepareLaunch: the agent's current revision, model, plane and learning start). */
2014
+ const replayAskOf = (entry) => ({
2015
+ store, agentId: entry.agent.id, context: ctx, log: (line) => void log?.(line),
2016
+ folder: () => learningFolderOf(data, entry.agent.id), shown: () => learningShown(entry.agent.id),
2017
+ launchOf: async (input) => {
2018
+ const { launch, revision } = await prepareLaunch(startDeps, entry, { input });
2019
+ return { launch, revisionId: revision.id };
2020
+ },
2021
+ });
2022
+ /** `act`, its ReplayRefused answered as the API's: 404 not_found, or 409 replay_conflict, in its words. */
2023
+ const replayAsked = async (act) => {
2024
+ try {
2025
+ return await act();
2026
+ }
2027
+ catch (error) {
2028
+ if (error instanceof ReplayRefused)
2029
+ throw new ApiError(error.kind === "missing" ? "not_found" : "replay_conflict", error.message);
2030
+ throw error;
2031
+ }
2032
+ };
1859
2033
  /** Agent `source`'s learned workflow `raw` made into a workflow agent of its own, as POST /agents makes one
1860
2034
  * (createAgentOf: the definition's checks, the workflow's validation and what this host refuses of it). Only an active
1861
2035
  * one, checked again as a restore checks it (learning-routes.ts promotable). Its revision is a workflow revision of the
@@ -1882,7 +2056,6 @@ async function startHolding(options, data, checked, stops) {
1882
2056
  ...(policy.toolSettings ? { tool_settings: policy.toolSettings } : {}),
1883
2057
  ...(policy.approvals === "never" ? { approvals: "never" } : {}),
1884
2058
  ...(policy.maxCostUsd !== undefined ? { max_cost_usd: policy.maxCostUsd } : {}),
1885
- ...(policy.capMode !== undefined ? { cap_mode: policy.capMode } : {}),
1886
2059
  });
1887
2060
  const note = `Made from the learned workflow ${learned.name} of agent ${id}.`;
1888
2061
  // Another promotion (or a create) may take the id between the read and the write: the next one is tried.
@@ -1904,15 +2077,17 @@ async function startHolding(options, data, checked, stops) {
1904
2077
  }
1905
2078
  /** A template package applied: its parameters and the owner's grants checked (422), then the secrets and required MCP
1906
2079
  * 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
2080
+ * agent made as POST /agents makes one, granted the MCP tools the owner ticked (grants) alone, with no permission written
2081
+ * (each call follows this server's tool settings: a write asks unless the owner allowed it there or approvals never; a deny the owner set on this server stays,
2082
+ * with a warning): a tool left unticked is not the agent's, under any approvals, its body held to POST /agents' limit (413), on the first harness of its list this server runs and the model packageModel
1909
2083
  * picks, then each trigger on it as POST /triggers makes one. A trigger refused undoes the apply: the triggers made
1910
2084
  * before it are deleted and the agent is archived (an agent store keeps every agent), and the refusal is the answer, a 422's fields under `triggers.<i>`; a
1911
2085
  * github trigger GitHub is not connected for is skipped instead, with a warning there, and one made is said there. A webhook
1912
2086
  * trigger's secret is not in the answer (the Idempotency-Key record would keep it): POST /triggers/{id}/secret makes one. */
1913
2087
  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));
2088
+ const { parameters, grants: asked, servers: picks, model: override, choice, approvals } = applyBodyOf(template, body);
2089
+ // A model choice's own keys are needed as the package's are: missing, the apply is refused and nothing is made.
2090
+ const missing = [...new Set([...template.secrets, ...(choice?.secrets ?? [])])].filter((name) => !secret(name, storedKeys));
1916
2091
  // Each MCP need on the saved server whose source and toolkit match (the owner's pick when several do, never a silent
1917
2092
  // one: several and no pick is a 422); the package's
1918
2093
  // tool names, mcp:<toolkit>/<tool>, read as that server's from here on (templates.ts onServers).
@@ -1938,8 +2113,19 @@ async function startHolding(options, data, checked, stops) {
1938
2113
  const computerWarnings = pick?.note ? [{ field: "computer", reason: pick.entry === "none" ? NOT_SET_UP : "not_an_option", message: pick.note }] : [];
1939
2114
  // An MCP server the package can do without is skipped, and said: its tools are not granted.
1940
2115
  const skipped = unsaved.map((need) => ({ field: `mcp.${need.toolkit}`, reason: NOT_SET_UP, message: `No saved MCP server is ${need.source} ${need.toolkit}, so the agent was made without its tools (${need.tools.join(", ")}).`, fix: mcpSetUp(need) }));
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);
2116
+ // A model choice the owner picked is its model on its harness, or a refusal naming the model: never the tier's model
2117
+ // in its place. So is a package's `prefer` (packageModel's `refused`), outside a gateway.
2118
+ const unrunnable = choice && (await choiceUnrunnable(env, choice, offers.find((offer) => offer.id === choice.harness)));
2119
+ if (choice && unrunnable) {
2120
+ const message = `The ${pkg.name} template's choice ${choice.label} runs ${choice.model} on ${choice.harness}, which this server can't run: ${unrunnable.replace(/\.$/, "")}. Nothing was created.`;
2121
+ throw new ApiError("agent_not_runnable", message, { fields: [{ field: "overrides.choice", reason: NOT_SET_UP, message, fix: "Apply with the default or another choice, or, where the model only wants a key, add it in Settings → Model keys." }] });
2122
+ }
2123
+ const harness = choice ? choice.harness : pkg.harness && (pkg.harness.find((id) => offers.some((offer) => offer.id === id && offer.available)) ?? pkg.harness[0]);
2124
+ const picked = choice ? { model: choice.model } : override ? { model: override } : await packageModel(env, pkg.model, harness ?? DEFAULT_HARNESS);
2125
+ if ("refused" in picked && picked.refused) {
2126
+ const message = `The ${pkg.name} template prefers ${pkg.model?.prefer}, which this server can't run on ${harness ?? DEFAULT_HARNESS}: ${picked.refused.why}. Nothing was created.`;
2127
+ throw new ApiError("agent_not_runnable", message, { fields: [{ field: "model", reason: NOT_SET_UP, message, fix: picked.refused.fix }] });
2128
+ }
1943
2129
  const model = picked.model;
1944
2130
  // Which model the agent got, where it is not the package's: a note, never a lack. The agent runs; only the package's
1945
2131
  // choice was not an option here (not_set_up_here would read as a run refused until the host has something).
@@ -1950,14 +2136,15 @@ async function startHolding(options, data, checked, stops) {
1950
2136
  // A grant never lifts a deny the owner set on this server: that tool keeps it, and the answer says so.
1951
2137
  const server = settings.get();
1952
2138
  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.` }));
2139
+ const kept = denied.map((tool) => ({ field: `grants.${tool}`, reason: "not_allowed", message: `${tool} is denied on this server (Settings → Tools), so the agent's runs are refused it until the owner changes that setting.` }));
1954
2140
  // The agent's approvals: the apply's override, else the package's own (a template whose job runs on triggers says
1955
2141
  // never), else ask. Deny and pins hold either way.
1956
2142
  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);
2143
+ const made = compiled(pkg, parameters, { ...(harness ? { harness } : {}), ...(model ? { model } : {}), ...(tiers.modelTiers ? { modelTiers: tiers.modelTiers } : {}), mcp: saved, defaultTools, grants, ...(chosenApprovals ? { approvals: chosenApprovals } : {}), ...(pick ? { computer: pick } : {}) }, templateDeps);
1958
2144
  // 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);
2145
+ // from a parameter that does not read, or a date that has passed, refuses the apply (422 under triggers.<i>). "Passed"
2146
+ // by the triggers' own clock, the one POST /triggers checks by and they fire by (a template eval case's `now`).
2147
+ const refusedTriggers = madeTriggerIssues(made.triggers, options.triggerClock?.now() ?? Date.now(), pkg.inputSchema);
1961
2148
  if (refusedTriggers.length)
1962
2149
  throw invalid(refusedTriggers);
1963
2150
  // POST /agents' and POST /triggers' own body limit: parameters filled in more than once can grow a package past it.
@@ -2105,9 +2292,7 @@ async function startHolding(options, data, checked, stops) {
2105
2292
  return { body: rest, sealer };
2106
2293
  }
2107
2294
  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() } });
2295
+ const entry = await needRunnableAgent(agentId);
2111
2296
  const { body, sealer } = handedMcpAuth(await bodyOf(req));
2112
2297
  return idempotent(req, `/agents/${agentId}/runs`, body, async (origin) => {
2113
2298
  // A run the store started under this key, though no answer was kept (its server went down first): that run, as it is now.
@@ -2131,6 +2316,8 @@ async function startHolding(options, data, checked, stops) {
2131
2316
  * (runs-over-store startInline). The answer is POST /agents/{agent_id}/runs' own: 202 and the run. */
2132
2317
  async function createInlineRun(req) {
2133
2318
  const { body, sealer } = handedMcpAuth(await bodyOf(req));
2319
+ if (isObject(body.definition) && body.definition.native !== undefined)
2320
+ throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine; an inline definition cannot create one.");
2134
2321
  const { external, definition, skills, note, revision: pinned, ...run } = body;
2135
2322
  const given = { definition, ...(skills !== undefined ? { skills } : {}), ...(note !== undefined ? { note } : {}) };
2136
2323
  const issues = [
@@ -2154,10 +2341,7 @@ async function startHolding(options, data, checked, stops) {
2154
2341
  const mapped = await store.agents.byExternal(externalKey(ref));
2155
2342
  const stored = mapped ? await store.agents.externalRevision(mapped.id, String(ref.version)) : undefined;
2156
2343
  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 };
2344
+ const revision = stored ? made : { ...made, ...(await saveable(made, current)).stamp };
2161
2345
  const inline = {
2162
2346
  external: { source: ref.source, kind: ref.kind, id: ref.id, version: String(ref.version) },
2163
2347
  name: checked.definition.name,
@@ -2229,7 +2413,7 @@ async function startHolding(options, data, checked, stops) {
2229
2413
  }
2230
2414
  /** A run create's body as POST /agents/{id}/runs checks it before it reads the agent: each field issue. */
2231
2415
  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"]);
2416
+ const issues = unknownFields(body, ["input", "revision", "file_ids", "effort", "max_cost_usd", "quote_id", "learning", "archil_disk", "repo", "workflow_first", "hold", "hold_minutes"]);
2233
2417
  issues.push(...holdIssues(body));
2234
2418
  if (body.repo !== undefined && !(typeof body.repo === "string" && REPO_NAME.test(body.repo)))
2235
2419
  issues.push({ field: "repo", reason: "wrong_type", message: "repo is a GitHub repository as owner/name, one the agent is bound to" });
@@ -2249,8 +2433,6 @@ async function startHolding(options, data, checked, stops) {
2249
2433
  issues.push({ field: "effort", reason: "not_an_option", message: `effort is one of ${EFFORTS.join(", ")}` });
2250
2434
  if (body.max_cost_usd !== undefined && !(typeof body.max_cost_usd === "number" && body.max_cost_usd > 0 && Number.isFinite(body.max_cost_usd)))
2251
2435
  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
2436
  if (body.file_ids !== undefined && !Array.isArray(body.file_ids))
2255
2437
  issues.push({ field: "file_ids", reason: "wrong_type", message: "file_ids is a list of file ids" });
2256
2438
  if (body.workflow_first !== undefined && typeof body.workflow_first !== "boolean")
@@ -2296,11 +2478,16 @@ async function startHolding(options, data, checked, stops) {
2296
2478
  if (asked !== null && !(/^\d+$/.test(asked) && Number(asked) >= 1 && Number(asked) <= PAGE_ROWS))
2297
2479
  throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_ROWS}`);
2298
2480
  const limit = asked === null ? PAGE_ROWS : Number(asked);
2481
+ // `calls=whole`: each call's arguments and its output's head too (tool_input, tool_result_text), for a grader.
2482
+ const shape = url.searchParams.get("calls");
2483
+ if (shape !== null && shape !== "whole")
2484
+ throw new ApiError("bad_request", "calls is whole, or absent");
2485
+ const calls = shape === "whole";
2299
2486
  // The run's page from the store (runTimelines): run_id/status/state/reset/rows/drop/next_after/unchanged/has_more/final/
2300
2487
  // cost, byte-identical to the old live page. TODO(learning-row freshness): a learning row approved or retired since the
2301
2488
  // journal wrote it reads its journal state here (store-view owns the fresh learning view); folded in with learning-1.
2302
2489
  if (!String(req.headers.accept ?? "").includes("text/event-stream")) {
2303
- const page = await timelines.page(store, runId, after, waitMs, limit);
2490
+ const page = await timelines.page(store, runId, after, waitMs, limit, calls);
2304
2491
  return send(res, 200, { ...page, poll_after_ms: page.final || page.has_more ? 0 : 1000 });
2305
2492
  }
2306
2493
  const last = req.headers["last-event-id"];
@@ -2324,7 +2511,7 @@ async function startHolding(options, data, checked, stops) {
2324
2511
  });
2325
2512
  try {
2326
2513
  for (let first = true; open; first = false) {
2327
- const page = await timelines.page(store, runId, cursor, 0, limit);
2514
+ const page = await timelines.page(store, runId, cursor, 0, limit, calls);
2328
2515
  if (!open)
2329
2516
  break;
2330
2517
  if (first || !page.unchanged || page.final)
@@ -2702,8 +2889,10 @@ async function startHolding(options, data, checked, stops) {
2702
2889
  // Archil on or off, or saving a key, changes them. So does a shell on the runner (bash on Archil's serverless exec
2703
2890
  // in Mode 2): where there is one, the document is made again with it (cheap), its tools available with no box.
2704
2891
  const runnerShell = shellTools(await shellOf({ kind: "none" }));
2892
+ await planNow();
2705
2893
  const answer = forCaller(runnerShell.size ? compose(runnerShell) : caps, byOwnerSession(req));
2706
- return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()) } });
2894
+ // features.triggers.public_url: whether Composio (or any sender) has a public address to reach, never the address.
2895
+ return send(res, 200, { ...answer, features: { ...answer.features, computers: await computerCapabilities(computersOf()), triggers: { ...answer.features.triggers, public_url: Boolean(options.publicUrl) } } });
2707
2896
  }
2708
2897
  if (found.name === "getOpenapi")
2709
2898
  return send(res, 200, servedOpenapi(openapi, req.socket.localPort));
@@ -2715,7 +2904,7 @@ async function startHolding(options, data, checked, stops) {
2715
2904
  // read (push-handler.ts).
2716
2905
  if (found.name === "receiveHook") {
2717
2906
  // 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]);
2907
+ const answer = await receivePush({ adapters, hooked: (id) => triggers.hookSource(id), ...(options.hookBodyMs !== undefined ? { bodyMs: options.hookBodyMs } : {}), ignored: (id, eventId) => triggers.ignored(id, eventId), listening: (kind) => triggers.listening(kind), notice: async (adapterId, event, body) => (adapterId === "github" && event === "installation" ? githubConnect.installationEvent(body, (detail) => triggers.turnOff("github", detail)) : undefined), receive: (id, eventId, payload, attrs) => triggers.receive(id, eventId, payload, attrs), scoped: (kind, scope) => triggers.scoped(kind, scope), setting: (adapterId, scope, field) => triggerSettings.get(adapterId)?.get(scope, field), refused: authFailed, say: (fields) => (log ? log(logLine("trigger", fields)) : void process.stderr.write(`agentrun-serve: ${logLine("trigger", fields)}\n`)) }, req, ...((([, segment, sub]) => [segment, sub])(/^\/hooks\/([^/]+)(?:\/([^/]+))?$/.exec(path))));
2719
2908
  return send(res, answer.status, answer.body, answer.headers ?? {});
2720
2909
  }
2721
2910
  // A paired computer's driver trading its pairing code for its token: the code is its credential (computer-attach.ts),
@@ -2784,6 +2973,12 @@ async function startHolding(options, data, checked, stops) {
2784
2973
  authFailed(`/v2${path}`, "promote_without_session");
2785
2974
  throw new ApiError("forbidden", owner ? "Making a learned workflow an agent takes the owner's password sign-in in the console, never a token." : "Making a learned workflow an agent takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
2786
2975
  }
2976
+ // A replay its owner starts runs the agent's graded inputs again at its cost, and may promote a revision that then
2977
+ // serves first: the same session as making one an agent.
2978
+ if (found.name === "startLearnedWorkflowReplay" && !byOwnerSession(req) && req.headers.authorization !== undefined) {
2979
+ authFailed(`/v2${path}`, "replay_without_session");
2980
+ throw new ApiError("forbidden", owner ? "Replaying a learned workflow's revision takes the owner's password sign-in in the console, never a token." : "Replaying a learned workflow's revision takes the owner's password sign-in, and this server has no accounts (AGENTRUN_ACCOUNTS=0).");
2981
+ }
2787
2982
  // A run's live computer view is a full-control credential for its computer: the owner's signed-in page alone, as
2788
2983
  // approving a note is (never a token a run, an MCP client or a script may hold).
2789
2984
  if ((found.name === "getRunBrowser" || found.name === "handBackRunBrowser" || found.name === "getRunComputer") && !byOwnerSession(req) && req.headers.authorization !== undefined) {
@@ -2824,17 +3019,130 @@ async function startHolding(options, data, checked, stops) {
2824
3019
  }
2825
3020
  secretSeen = checked.seen;
2826
3021
  }
3022
+ // Connector credentials have no authority over the ordinary API. Enrollment is a one-use owner grant;
3023
+ // subsequent calls are restricted to one connector and its explicitly imported target allowlist.
3024
+ if (found.name === "registerRemoteConnector") {
3025
+ const credential = String(req.headers.authorization ?? "").replace(/^Bearer /, "");
3026
+ return send(res, 200, await new RemoteConnectors(store).register(credential, await bodyOf(req)));
3027
+ }
3028
+ if (found.name === "revokeRemoteConnector" && String(req.headers.authorization ?? "").startsWith("Bearer ar_connector_")) {
3029
+ const connectorId = decodeURIComponent(found.pattern.exec(path)[1]);
3030
+ const broker = new RemoteConnectors(store);
3031
+ await broker.authenticate(connectorId, String(req.headers.authorization).slice(7));
3032
+ return send(res, 200, await broker.revoke(connectorId));
3033
+ }
3034
+ if (["importRemoteTarget", "importRemoteHistory", "pollRemoteConnector", "remoteCommandEvents", "completeRemoteCommand"].includes(found.name)) {
3035
+ const parts = found.pattern.exec(path);
3036
+ const connectorId = decodeURIComponent(parts[1]);
3037
+ const broker = new RemoteConnectors(store);
3038
+ await broker.authenticate(connectorId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
3039
+ // History pages and command completions have separate bounded contracts; other JSON keeps MAX_BODY.
3040
+ const limit = found.name === "importRemoteHistory" ? REMOTE_HISTORY_BODY_BYTES
3041
+ : found.name === "completeRemoteCommand" ? REMOTE_COMPLETION_BODY_BYTES : MAX_BODY;
3042
+ const body = await bodyOf(req, limit);
3043
+ if (found.name === "importRemoteTarget")
3044
+ return send(res, 200, await broker.importTarget(connectorId, body));
3045
+ if (found.name === "importRemoteHistory")
3046
+ return send(res, 200, await broker.importHistory(connectorId, decodeURIComponent(parts[2]), body, [token, String(req.headers.authorization ?? "").replace(/^Bearer /, "")]));
3047
+ if (found.name === "pollRemoteConnector")
3048
+ return send(res, 200, await broker.poll(connectorId, body));
3049
+ const commandId = decodeURIComponent(parts[2]);
3050
+ return send(res, 200, found.name === "remoteCommandEvents" ? await broker.events(connectorId, commandId, body) : await broker.complete(connectorId, commandId, body));
3051
+ }
3052
+ if (["getSdkRun", "sdkRunEvents", "completeSdkRun"].includes(found.name)) {
3053
+ const runId = decodeURIComponent(found.pattern.exec(path)[1]);
3054
+ const sdk = new SdkRuns(store, data, token, serverSecrets);
3055
+ await sdk.authenticate(runId, String(req.headers.authorization ?? "").replace(/^Bearer /, ""));
3056
+ if (found.name === "sdkRunEvents")
3057
+ return send(res, 200, await sdk.events(runId, await bodyOf(req)));
3058
+ if (found.name === "completeSdkRun")
3059
+ return send(res, 200, await sdk.complete(runId, await bodyOf(req)));
3060
+ return send(res, 200, { ...await sdk.status(runId), learning: await servedRunLearning({ serverSecrets, signIns, statuses }, store, runId) });
3061
+ }
2827
3062
  if (!timingSafeEqual(digest(String(req.headers.authorization ?? "")), expected)) {
2828
3063
  authFailed(`/v2${path}`, req.headers.authorization === undefined ? "no_credential" : "wrong_token");
2829
3064
  throw new ApiError("unauthenticated", "this route needs Authorization: Bearer <the token in the data directory>", {}, { "www-authenticate": "Bearer" });
2830
3065
  }
2831
3066
  if (found.capability)
2832
3067
  throw unsupported(found.capability, UNSUPPORTED[found.capability]);
3068
+ if (["discoverNative", "connectNative"].includes(found.name) && (options.apiOnly || options.publicUrl || !isLoopback(host)))
3069
+ throw new ApiError("forbidden", "Native connections require AgentRun on the source machine, bound to loopback without a public URL. A hosted browser cannot discover your laptop.");
2833
3070
  const [, first, second] = found.pattern.exec(path);
2834
3071
  const id = first ? decodeURIComponent(first) : "";
2835
3072
  switch (found.name) {
3073
+ case "startSdkRun": {
3074
+ if (!req.headers["idempotency-key"])
3075
+ throw new ApiError("bad_request", "An SDK run requires Idempotency-Key so a retried start never duplicates execution.");
3076
+ const body = await bodyOf(req), entry = await needAgent(id);
3077
+ let gradeModel = gradeModelOf(env, options.gradeModel);
3078
+ if (!gradeModel && sdkOf(entry.revision?.body) && learnsOf(entry.revision.body.learning) && learning !== "off") {
3079
+ try {
3080
+ const chosen = await runModelRef(env, (await pinnedOf(entry, {})).revision);
3081
+ if (chosen)
3082
+ gradeModel = `${chosen.provider}/${chosen.modelId}`;
3083
+ }
3084
+ catch { }
3085
+ }
3086
+ const sdk = new SdkRuns(store, data, token, serverSecrets);
3087
+ const answer = await idempotent(req, path, body, async (origin) => ({ status: 201, body: await sdk.start(entry, body, { ...startDeps, ...(gradeModel ? { gradeModel } : {}) }, origin, async (model) => {
3088
+ try {
3089
+ const route = await gradeRouteFor({ model, agentId: id }, env, sdkModelRoute);
3090
+ await route.provider.credential();
3091
+ }
3092
+ catch {
3093
+ throw new ApiError("agent_not_runnable", "Self-improving SDK runs need a working server model key and grading model. Configure Model keys or turn self-improving off.");
3094
+ }
3095
+ }, linkOrigin(req)) }));
3096
+ // Re-read the pinned receipt even on an in-memory replay: credentials saved since
3097
+ // the first response must still be withheld without reselecting a different seed.
3098
+ const receipt = await sdk.receipt(answer.body.run_id, linkOrigin(req));
3099
+ return send(res, answer.status, receipt, answer.headers);
3100
+ }
3101
+ case "getObservations": {
3102
+ const days = Number(url.searchParams.get("days") ?? 30);
3103
+ if (!Number.isInteger(days) || days < 1 || days > 31)
3104
+ throw new ApiError("input_invalid", "Choose an observation window from 1 to 31 days.");
3105
+ return send(res, 200, await new Observations(store).snapshot(days, url.searchParams.get("session_id") ?? undefined));
3106
+ }
3107
+ case "listRemoteConnectors": return send(res, 200, await new RemoteConnectors(store).list());
3108
+ case "enrollRemoteConnector": return send(res, 200, await new RemoteConnectors(store).enroll(await bodyOf(req)));
3109
+ case "revokeRemoteConnector": return send(res, 200, await new RemoteConnectors(store).revoke(id));
3110
+ case "discoverNative": {
3111
+ const body = await bodyOf(req);
3112
+ if (typeof body.project !== "string" || (body.runtime !== undefined && !isNativeRuntime(body.runtime)))
3113
+ throw new ApiError("input_invalid", "Choose the project directory on this source machine and a supported CLI runtime.");
3114
+ return send(res, 200, await discoverNative({ project: body.project, ...(body.runtime ? { runtime: body.runtime } : {}) }));
3115
+ }
3116
+ case "connectNative": {
3117
+ const entry = await connectNative(store, await bodyOf(req));
3118
+ return send(res, 200, { agent: agentView(entry, linkOrigin(req), await agentExtra(entry)), native: nativeOf(entry.revision?.body) });
3119
+ }
3120
+ case "getNative": {
3121
+ const entry = await needAgent(id);
3122
+ const native = nativeOf(entry.revision?.body);
3123
+ return send(res, 200, { native: native?.remote ? await new RemoteConnectors(store).status(native) : native ?? null });
3124
+ }
3125
+ case "verifyNative": {
3126
+ const before = await needAgent(id);
3127
+ if (!nativeOf(before.revision?.body)?.remote && (options.apiOnly || options.publicUrl || !isLoopback(host)))
3128
+ throw new ApiError("forbidden", "Local native verification must run on the source machine.");
3129
+ const entry = nativeOf(before.revision?.body)?.remote ? await verifyRemote(store, before) : await verifyConnection(store, before);
3130
+ return send(res, 200, { native: nativeOf(entry.revision?.body) });
3131
+ }
3132
+ case "disconnectNative": {
3133
+ const entry = await needAgent(id);
3134
+ const native = nativeOf(entry.revision?.body);
3135
+ if (!native)
3136
+ throw new ApiError("not_found", "This agent has no native connection.");
3137
+ const changed = await updateNative(store, entry, { ...native, connected: false });
3138
+ if (native.remote)
3139
+ await new RemoteConnectors(store).disconnectTarget(native);
3140
+ return send(res, 200, { native: nativeOf(changed.revision?.body) });
3141
+ }
2836
3142
  case "createAgent": {
2837
3143
  const body = await bodyOf(req);
3144
+ if (isObject(body.definition) && body.definition.native !== undefined)
3145
+ throw new ApiError("input_invalid", "Native references are registered only through /native/connect on the source machine.");
2838
3146
  const answer = await idempotent(req, "/agents", body, async () => {
2839
3147
  const { entry, warnings } = await createAgentOf(body);
2840
3148
  return { status: 201, body: { ...agentView(entry, linkOrigin(req), await agentExtra(entry)), warnings }, headers: { location: `/v2/agents/${entry.agent.id}`, etag: etagOf(entry) } };
@@ -2879,6 +3187,16 @@ async function startHolding(options, data, checked, stops) {
2879
3187
  // contract's is the definition itself, and takes the contract's preconditions: If-Match, and a version past the
2880
3188
  // current one.
2881
3189
  const contract = !("definition" in body);
3190
+ const nativeEdit = contract ? body.native : isObject(body.definition) ? body.definition.native : undefined;
3191
+ if (nativeEdit !== undefined && stable(nativeEdit) !== stable(nativeOf(entry.revision?.body)))
3192
+ throw new ApiError("input_invalid", "Native references are changed only through the native connection endpoints. Normal edits retain the existing reference.");
3193
+ // Check explicit native selectors before canonicalization (the ordinary default harness, pi, is not stored).
3194
+ const definition = contract ? body : body.definition;
3195
+ if (nativeOf(entry.revision?.body) && isObject(definition)) {
3196
+ const execution = nativeExecutionOverrides({ ...definition, native: nativeOf(entry.revision?.body) });
3197
+ if (execution.length)
3198
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
3199
+ }
2882
3200
  if (contract) {
2883
3201
  if (match === undefined)
2884
3202
  throw new ApiError("precondition_failed", "If-Match is required: the agent's ETag, as GET /agents/{agent_id} returned it.");
@@ -2889,9 +3207,8 @@ async function startHolding(options, data, checked, stops) {
2889
3207
  // the same revision exactly one lands.
2890
3208
  let warnings = [];
2891
3209
  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);
3210
+ // The pins of the revision this try builds on (commitAgent's read, a retry's newer one) carry what it kept.
3211
+ const saved = await saveable(revision, on);
2895
3212
  warnings = saved.warnings;
2896
3213
  return saved.stamp;
2897
3214
  };
@@ -2917,8 +3234,19 @@ async function startHolding(options, data, checked, stops) {
2917
3234
  const revision = body.revision;
2918
3235
  if (typeof revision !== "string" || !ID.test(revision))
2919
3236
  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)))
3237
+ const candidate = await agents.revision(id, revision);
3238
+ if (!candidate)
2921
3239
  throw invalid([{ field: "revision", reason: "not_an_option", message: `${revision} is not a revision of the agent ${id}` }]);
3240
+ if (stable(nativeOf(candidate.revision.body)) !== stable(nativeOf(entry.revision?.body)))
3241
+ throw new ApiError("input_invalid", "This revision changes the native connection. Reconnect or verify through the native connection controls; ordinary revision restore cannot change its source or connection state.");
3242
+ if (nativeOf(candidate.revision.body)) {
3243
+ const overrides = nativeModelOverrides(candidate.revision.body);
3244
+ if (overrides.length)
3245
+ throw invalid(overrides.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_MODEL_SETTINGS_UNSUPPORTED })));
3246
+ const execution = nativeExecutionOverrides(candidate.revision.body);
3247
+ if (execution.length)
3248
+ throw invalid(execution.map(field => ({ field: `definition.${field}`, reason: "not_allowed", message: NATIVE_EXECUTION_SETTINGS_UNSUPPORTED })));
3249
+ }
2922
3250
  const moved = await agents.setCurrent(entry, revision);
2923
3251
  reconcileComputer(id);
2924
3252
  return send(res, 200, agentView(moved, linkOrigin(req), await agentExtra(moved)), { etag: etagOf(moved) });
@@ -3084,11 +3412,14 @@ async function startHolding(options, data, checked, stops) {
3084
3412
  const grade = {
3085
3413
  run: row.id, correct: body.correct, ...(body.expected !== undefined ? { expected: body.expected } : {}), source: body.source ?? "feedback", at: new Date().toISOString(), path,
3086
3414
  ...(typeof m.workflow === "string" ? { workflow: m.workflow } : {}), ...(typeof m.workflow_digest === "string" ? { digest: m.workflow_digest } : {}),
3415
+ ...(typeof m.workflow_promotion === "number" ? { promotion: m.workflow_promotion } : {}),
3087
3416
  };
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 });
3417
+ // Kept with what it asks of the run's learning (runner/feedback-round.ts): nothing, a revision ask, or a look-back.
3418
+ const kept = gradeView(await keepGrade(store, row.agentId, grade, typeof body.label === "string" ? body.label : undefined));
3419
+ // Its workflow's name cut as GET /runs/{id}/learning cuts it (learningShown); withheld whole when that cut can't be
3420
+ // read (the grade is kept by then: never a shorter cut, never a refusal of a grade it kept).
3421
+ const shown = await learningShown(row.agentId).catch(() => undefined);
3422
+ return send(res, 200, { ...kept, workflow: kept.workflow === null ? null : shown ? shown.name(kept.workflow) : REDACTED });
3092
3423
  }
3093
3424
  case "archiveRun":
3094
3425
  case "unarchiveRun": {
@@ -3110,7 +3441,11 @@ async function startHolding(options, data, checked, stops) {
3110
3441
  const kept = await keptBrowserOf(store, run.id);
3111
3442
  // A desktop or a phone (the run's revision's computer) whose screen is not open now is still the run's computer:
3112
3443
  // none with its kind, never off as if the agent had none (#2170).
3113
- const viewed = family === "computer" ? await runViewedKind(store, run.id) : undefined;
3444
+ const own = family === "computer" ? await runComputerKind(store, run.id) : undefined;
3445
+ const viewed = own === "desktop" || own === "phone" ? own : undefined;
3446
+ // A parked run's desktop or phone is no screen being opened: its claim let it go, or kept it for the resume
3447
+ // (computer-kept.ts; the run's timeline says until when), and once its time passed, the timeout's words.
3448
+ const parked = family === "computer" && !run.terminal && (await store.runs.get(run.id))?.state === "parked";
3114
3449
  const view = await computerView({
3115
3450
  viewer: async () => {
3116
3451
  if (family === "browser") {
@@ -3119,8 +3454,9 @@ async function startHolding(options, data, checked, stops) {
3119
3454
  }
3120
3455
  return computerViewerLink(store, sealKey, run.id, answers);
3121
3456
  },
3122
- computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family)),
3123
- session: (kind) => sessionIn(kind, entries, run.terminal),
3457
+ computer: () => (viewed ? { kind: viewed } : computerOf(kept, env, family, own)),
3458
+ session: (kind) => sessionIn(kind, entries, run.terminal || (parked && kind !== "browser")),
3459
+ lapsed: async (kind) => (parked ? lapsedOf(kind, await readKept(store.settings, run.id).catch(() => undefined), Date.now()) : undefined),
3124
3460
  hold: () => hold,
3125
3461
  // A going run's browser let go while it waited for its person: the Screen tab says so, with when. One settings
3126
3462
  // row (browser-wait-ended.ts), never the run's journal: this is read on every Screen poll.
@@ -3370,6 +3706,35 @@ async function startHolding(options, data, checked, stops) {
3370
3706
  await toolKeys.remove(id);
3371
3707
  await keysChanged();
3372
3708
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
3709
+ // Never through `idempotent`: its record keeps the body, and the body holds the password.
3710
+ case "getEmailAccount":
3711
+ case "saveEmailAccount":
3712
+ case "deleteEmailAccount":
3713
+ case "testEmailAccount": {
3714
+ const body = found.name === "saveEmailAccount" || found.name === "testEmailAccount" ? await bodyOf(req) : undefined;
3715
+ if (found.name === "saveEmailAccount" && stopping.signal.aborted)
3716
+ throw new ApiError("unavailable", "The server is shutting down: the account was not saved.");
3717
+ const answer = await emailRoute({ store, sealKey }, found.name, body);
3718
+ if (found.name === "saveEmailAccount")
3719
+ await heldEmailPassword();
3720
+ if (answer === undefined)
3721
+ return void res.writeHead(204, { "cache-control": "no-store" }).end();
3722
+ return send(res, 200, answer, { "cache-control": "no-store" });
3723
+ }
3724
+ // The ChatGPT sign-in (chatgpt-plan.ts): a step it refuses is 400 in its words; its token is in no answer.
3725
+ case "getChatGPTSignIn":
3726
+ await planNow();
3727
+ return send(res, 200, plan.view());
3728
+ case "startChatGPTSignIn":
3729
+ return send(res, 200, await planStep(() => plan.startSignIn()));
3730
+ case "finishChatGPTSignIn": {
3731
+ const body = (await bodyOf(req));
3732
+ return send(res, 200, await planStep(() => plan.finishSignIn(body?.redirect_url)));
3733
+ }
3734
+ case "signOutChatGPT": {
3735
+ const { revoked } = await plan.signOut();
3736
+ return send(res, 200, revoked ? { revoked } : { revoked, message: SIGN_OUT_UNCONFIRMED });
3737
+ }
3373
3738
  // Never through `idempotent`: its record keeps the body, and a body may hold a credential.
3374
3739
  case "listMcpServers":
3375
3740
  return send(res, 200, await mcpServers.list());
@@ -3393,6 +3758,14 @@ async function startHolding(options, data, checked, stops) {
3393
3758
  await refreshMcpMeta();
3394
3759
  return send(res, 200, answer, { "cache-control": "no-store" });
3395
3760
  }
3761
+ case "listComposioEvents":
3762
+ return send(res, 200, await composioTriggers.events(id), { "cache-control": "no-store" });
3763
+ case "listComposioTriggers":
3764
+ return send(res, 200, await composioTriggers.triggersOf(id), { "cache-control": "no-store" });
3765
+ case "rotateComposioSecret":
3766
+ return send(res, 200, await composioTriggers.rotate(id), { "cache-control": "no-store" });
3767
+ case "deleteComposioSubscription":
3768
+ return send(res, 200, await composioTriggers.forget(id), { "cache-control": "no-store" });
3396
3769
  case "refreshMcpServer": {
3397
3770
  const refreshed = await mcpServers.refresh(id, stopping.signal);
3398
3771
  await refreshMcpMeta();
@@ -3441,8 +3814,9 @@ async function startHolding(options, data, checked, stops) {
3441
3814
  // Our row goes first, by the checked removal (a 412 sends Composio nothing), and answers what it removed: a Composio
3442
3815
  // preset server's MCP server on Composio is deleted next, as the row removed named it and with its saved key.
3443
3816
  // 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);
3817
+ // remove there by hand. One that Composio triggers still use is kept: refused, naming them, checked and deleted in
3818
+ // its Composio project's turn, so a trigger still being made on it is counted (composio-triggers.ts deleting).
3819
+ const { composio: made } = await composioTriggers.deleting(id, () => mcpServers.remove(id, secretSeen));
3446
3820
  await refreshMcpMeta();
3447
3821
  const forgotten = !made ? undefined : "unusable" in made ? composioNote(id) : await composioForget(options.composioControl ?? {}, made.key, made.id, id, stopping.signal);
3448
3822
  if (forgotten && !forgotten.removed)
@@ -3591,6 +3965,29 @@ async function startHolding(options, data, checked, stops) {
3591
3965
  });
3592
3966
  return send(res, answer.status, answer.body, answer.headers);
3593
3967
  }
3968
+ case "startLearnedWorkflowReplay": {
3969
+ const body = await bodyOf(req);
3970
+ // An archived agent starts no run: refused before the replay is reserved, as a person's start is.
3971
+ const entry = await needRunnableAgent(id);
3972
+ const extra = unknownFields(body, ["inputs"]);
3973
+ if (extra.length)
3974
+ throw invalid(extra);
3975
+ const inputs = body.inputs === undefined ? "held" : body.inputs;
3976
+ if (inputs !== "held" && !(typeof inputs === "number" && Number.isInteger(inputs) && inputs >= 1 && inputs <= GRADES_KEPT)) {
3977
+ throw new ApiError("bad_request", `inputs is "held" (the graded inputs the revision was last decided on, the default) or a whole number from 1 to ${GRADES_KEPT}: that many of the agent's newest graded inputs.`);
3978
+ }
3979
+ const [, , name, digest] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
3980
+ const started = await replayAsked(() => askReplay(replayAskOf(entry), name, digest, inputs));
3981
+ return send(res, 202, started, { location: `/v2/agents/${encodeURIComponent(id)}/learning/workflows/${encodeURIComponent(name)}/revisions/${encodeURIComponent(digest)}/replays/${started.replay}` });
3982
+ }
3983
+ case "getLearnedWorkflowReplay": {
3984
+ const entry = await needAgent(id);
3985
+ const [, , name, digest, replayId] = found.pattern.exec(path).map((part) => decodeURIComponent(part));
3986
+ const view = await replayAsked(() => replayView(replayAskOf(entry), name, digest, replayId));
3987
+ // Its words cut as the promotions list cuts a record's (promotionsShown).
3988
+ const shown = await learningShown(id);
3989
+ return send(res, 200, { ...view, workflow: shown.name(view.workflow), ...(view.reason !== undefined ? { reason: shown.text(view.reason) } : {}) });
3990
+ }
3594
3991
  case "getRunLearning": {
3595
3992
  const run = await needRun(id);
3596
3993
  // The run's learning view over the store (learning-1's runLearningOverStore): its end, the notes it was given and its seed
@@ -3680,23 +4077,24 @@ async function startHolding(options, data, checked, stops) {
3680
4077
  }
3681
4078
  case "rotateTriggerSecret":
3682
4079
  // 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
- })());
4080
+ // It takes no body: the new secret is made here, never given. Any body is refused before it rotates, `{}` too: a
4081
+ // length other than 0, or one sent chunked, is a body whatever it holds.
4082
+ if (req.headers["transfer-encoding"] !== undefined || Number(req.headers["content-length"] ?? 0) !== 0) {
4083
+ throw invalid([{ field: "body", reason: "not_allowed", message: "Rotating a trigger's secret takes no body: send none, and the new secret is made here." }]);
4084
+ }
4085
+ return send(res, 200, triggerRotated(id, (await triggers.rotate(id)).secret, new Date().toISOString()));
3692
4086
  case "getTrigger":
3693
4087
  return send(res, 200, withSecretOf(await triggers.get(id)));
3694
4088
  case "updateTrigger":
3695
4089
  // Its secret's metadata as a read answers it, so a page showing the changed trigger keeps saying it is set.
3696
4090
  return send(res, 200, withSecretOf(await triggers.update(id, await bodyOf(req))));
3697
- case "deleteTrigger":
3698
- await triggers.remove(id);
4091
+ case "deleteTrigger": {
4092
+ // Deleted here whatever its sender says; what could not be removed there is answered (Composio's instance).
4093
+ const said = await triggers.remove(id);
4094
+ if (said)
4095
+ return send(res, 200, { deleted: true, ...said });
3699
4096
  return void res.writeHead(204, { "cache-control": "no-store" }).end();
4097
+ }
3700
4098
  case "fireTrigger": {
3701
4099
  const key = req.headers["idempotency-key"];
3702
4100
  if (typeof key !== "string" || key.length < 1 || key.length > 255)
@@ -3795,8 +4193,12 @@ async function startHolding(options, data, checked, stops) {
3795
4193
  return void mcp(req, res).catch(fail);
3796
4194
  if (raw === "/llms.txt")
3797
4195
  return void answerLlms(req, res).catch(fail);
4196
+ if (raw === "/skills/agentrun-serve/SKILL.md")
4197
+ return void answerSkill(req, res).catch(fail);
3798
4198
  if (answerPage(req, res, raw, { token, authFailed, console: options.console, takesBytes, ...(owner ? { owner } : {}), ...(consoleSessions ? { sessions: consoleSessions } : {}), ...(options.publicUrl ? { publicUrl: options.publicUrl } : {}) }))
3799
4199
  return;
4200
+ if (isObservationRoute(raw))
4201
+ return void observationHttp(req, res, url, new Observations(store), token).catch(fail);
3800
4202
  if (!raw.startsWith("/v2/"))
3801
4203
  return fail(new ApiError("not_found", `no route ${raw}; the API is under /v2`));
3802
4204
  // A run's id needs no decoding: one that is not an id as sent (a stray or malformed escape) is no run's, and is never
@@ -3920,7 +4322,10 @@ async function startHolding(options, data, checked, stops) {
3920
4322
  // change would be the next seam.
3921
4323
  const RUN_CHANGES_POLL_MS = 250;
3922
4324
  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() } : {}) });
4325
+ /** A row its stop ended (stopEnd), which may stand at the person's stop (store.ts stoppedByPerson: an agentic run, its
4326
+ * status input_required and idle, a message continues it) and not have ended: its view says which. */
4327
+ const stopRow = (row) => row.state === "stopped" && row.outcome === "stopped" && row.importedFrom === null;
4328
+ const endOf = (row) => ({ id: row.id, state: final(row) ? row.state : "running", ...(final(row) && row.endedAt !== null ? { endedAt: new Date(row.endedAt).toISOString() } : {}), ...(stopRow(row) ? { stop: true } : {}) });
3924
4329
  /** The run as the store holds it now, with its notice (the run list's own view of it); null when there is no such run. */
3925
4330
  const endNotice = async (id) => {
3926
4331
  const row = await store.runs.get(id);
@@ -3946,9 +4351,9 @@ async function startHolding(options, data, checked, stops) {
3946
4351
  /** When each held wait (a run waiting on its person with its claim held) was last read again. */
3947
4352
  const heldReadAt = new Map();
3948
4353
  const HELD_WAIT_REREAD_MS = 1_000;
3949
- const waitKinds = new Set(["question", "approval", "budget", "browser"]);
4354
+ const waitKinds = new Set(["question", "approval", "budget", "browser", "computer", "stopped"]);
3950
4355
  /** The wait of a run its runner left parked (or let go of), or holds in its claim, told once per ask: its marker the
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
4356
+ * ask's own (webhooks.ts waitMarkerOf), its kind the pending card's (none when the run waits on no card). False when it
3952
4357
  * is not done (a read that failed, or its notice not saved): it is read again. */
3953
4358
  const tellWait = async (row) => {
3954
4359
  const seen = `${row.state}\n${row.epoch}\n${row.runner ?? ""}\n${row.summary ?? ""}`;
@@ -3958,14 +4363,17 @@ async function startHolding(options, data, checked, stops) {
3958
4363
  if (view?.status !== "input_required")
3959
4364
  return (readWaits.set(row.id, seen), true);
3960
4365
  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);
4366
+ const card = view.pending?.kind;
4367
+ // One marker per ask, so the held read and the let-go read of one ask agree, whatever row shows last. A stop's is when
4368
+ // its stop ended the row: rows its stopped turn still streams in (a late result, a charge) never move it.
4369
+ const marker = card === "stopped" && row.endedAt !== null ? `stopped:${new Date(row.endedAt).toISOString()}` : waitMarkerOf(rows, view.pending, view.state === "waiting", LEARNING_LABEL);
3963
4370
  if (!marker)
3964
4371
  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 };
4372
+ // Its kind is the read's own `pending.kind` (a stop's is stoppedTurn's), so the notice and GET never disagree; a wait
4373
+ // whose card is withheld is a question. A run idle on nothing named (its harness ended its turn on its own) names no kind.
4374
+ const kind = typeof card === "string" && waitKinds.has(card) ? card : view.state === "waiting" ? "question" : undefined;
4375
+ const wait = kind === undefined ? undefined : { kind };
4376
+ const notice = { run_id: row.id, agent_id: row.agentId, status: "input_required", title: typeof view.title === "string" ? view.title : "", ...(wait ? { pending: wait } : {}) };
3969
4377
  if (!(await toldAll(row.id, waitSubscribers.map((tell) => () => tell(notice, wait, marker)))))
3970
4378
  return false;
3971
4379
  readWaits.set(row.id, seen);
@@ -4017,6 +4425,17 @@ async function startHolding(options, data, checked, stops) {
4017
4425
  const now = await endNotice(id).catch((error) => (sayUnread(id, error.message), undefined));
4018
4426
  if (now === undefined)
4019
4427
  return false;
4428
+ // A person's stop of an agentic run ends its row but not the run: it reads input_required (pending kind stopped), so
4429
+ // it is told as that wait, run.needs_input, never as an end.
4430
+ if (now?.notice.status === "input_required") {
4431
+ const row = await rowNow(id);
4432
+ if (row === UNREAD)
4433
+ return (sayUnread(id, "its row could not be read"), false);
4434
+ const told = row === undefined || (await tellWait(row).catch((error) => (sayUnread(id, error.message), false)));
4435
+ if (told)
4436
+ unreadSaid.delete(id);
4437
+ return told;
4438
+ }
4020
4439
  readWaits.delete(id);
4021
4440
  heldReadAt.delete(id);
4022
4441
  if (!now?.endedAt || toldEnds.get(id) === now.endedAt)
@@ -4055,7 +4474,7 @@ async function startHolding(options, data, checked, stops) {
4055
4474
  const row = await rowNow(id);
4056
4475
  if (row === UNREAD)
4057
4476
  return (sayUnread(id, "its row could not be read"), false);
4058
- if (row === undefined || !letGo(row))
4477
+ if (row === undefined || !(letGo(row) || stopRow(row)))
4059
4478
  return true;
4060
4479
  const told = await tellWait(row).catch((error) => (sayUnread(id, error.message), false));
4061
4480
  if (told)
@@ -4140,8 +4559,9 @@ async function startHolding(options, data, checked, stops) {
4140
4559
  const unsaved = await webhooks.catchUp(rows.filter((row) => !row.importedFrom).map(endOf), (id) => endNotice(id).catch((error) => (endsLeft.add(id), Promise.reject(error))));
4141
4560
  for (const id of unsaved)
4142
4561
  endsLeft.add(id);
4562
+ // A run that stands at a person's stop waits too (tellWait reads its view: one its stop ended reads no wait).
4143
4563
  for (const row of rows)
4144
- if (!closing && letGo(row) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
4564
+ if (!closing && (letGo(row) || stopRow(row)) && !(await tellWait(row).catch((error) => (sayUnread(row.id, error.message), false))))
4145
4565
  waitsLeft.add(row.id);
4146
4566
  };
4147
4567
  followChanges();
@@ -4155,6 +4575,9 @@ async function startHolding(options, data, checked, stops) {
4155
4575
  // the store closes last.
4156
4576
  closing = true;
4157
4577
  stopping.abort();
4578
+ // Cancel a pending ChatGPT callback without signing out or changing the saved credential.
4579
+ plan.close();
4580
+ const observationStopped = stopObservationRetention();
4158
4581
  // A harness install under way stops with the server: npm gets SIGTERM, then SIGKILL, and nothing half installed stays.
4159
4582
  const installStopped = Promise.all(Object.values(installs).map((install) => install.stop()));
4160
4583
  // Aborted now, so nothing it writes races the next server on the same refresh token; drained before the store closes.
@@ -4172,6 +4595,7 @@ async function startHolding(options, data, checked, stops) {
4172
4595
  await Promise.all([...workers.values()].map((w) => w.exit));
4173
4596
  await importing;
4174
4597
  await installStopped;
4598
+ await observationStopped;
4175
4599
  // The ends' follower stops before the webhooks it feeds and the store it reads.
4176
4600
  clearTimeout(endsTimer);
4177
4601
  await endsRead;