@parcha/agentrun-serve 0.1.0-beta.43 → 0.1.0-beta.45

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 (388) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/README.md +580 -320
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +92 -22
  28. package/dist/composio-preset.d.ts +4 -3
  29. package/dist/composio-preset.js +81 -11
  30. package/dist/composio-triggers.d.ts +34 -2
  31. package/dist/composio-triggers.js +261 -31
  32. package/dist/computer-attach.d.ts +40 -5
  33. package/dist/computer-attach.js +130 -15
  34. package/dist/computer-keys.d.ts +3 -0
  35. package/dist/computer-keys.js +7 -1
  36. package/dist/computer-live.js +3 -2
  37. package/dist/computer-lost.d.ts +11 -0
  38. package/dist/computer-lost.js +19 -0
  39. package/dist/computer-record.d.ts +10 -2
  40. package/dist/computer-record.js +50 -18
  41. package/dist/computer-setting.d.ts +1 -0
  42. package/dist/computer-setting.js +2 -2
  43. package/dist/computers.d.ts +21 -10
  44. package/dist/computers.js +39 -28
  45. package/dist/console/assets/index-3O2Yl6hZ.js +701 -0
  46. package/dist/console/assets/index-DaFsZuzQ.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decisions.d.ts +1 -1
  49. package/dist/dial-relay.d.ts +29 -0
  50. package/dist/dial-relay.js +94 -0
  51. package/dist/email/tools.js +10 -5
  52. package/dist/env-proxy.d.ts +2 -0
  53. package/dist/env-proxy.js +35 -0
  54. package/dist/errors.d.ts +4 -1
  55. package/dist/errors.js +10 -4
  56. package/dist/faux-computers.d.ts +8 -2
  57. package/dist/faux-computers.js +83 -6
  58. package/dist/harness-archive.d.ts +67 -0
  59. package/dist/harness-archive.js +177 -0
  60. package/dist/harness-goose.d.ts +34 -0
  61. package/dist/harness-goose.js +87 -0
  62. package/dist/harness-install.d.ts +21 -0
  63. package/dist/harness-install.js +24 -11
  64. package/dist/harness-opencode/adapter.js +1 -1
  65. package/dist/harness-table.d.ts +59 -3
  66. package/dist/harness-table.js +119 -14
  67. package/dist/harness.d.ts +17 -1
  68. package/dist/harness.js +22 -11
  69. package/dist/host.d.ts +12 -10
  70. package/dist/host.js +19 -16
  71. package/dist/import-worker.d.ts +3 -0
  72. package/dist/import-worker.js +7 -5
  73. package/dist/import.d.ts +22 -1
  74. package/dist/import.js +141 -28
  75. package/dist/key-check.js +3 -0
  76. package/dist/learn/audit.d.ts +6 -6
  77. package/dist/learn/audit.js +3 -7
  78. package/dist/learn/check.d.ts +26 -89
  79. package/dist/learn/check.js +58 -336
  80. package/dist/learn/commit.d.ts +63 -90
  81. package/dist/learn/commit.js +124 -316
  82. package/dist/learn/compile.d.ts +53 -50
  83. package/dist/learn/compile.js +88 -103
  84. package/dist/learn/corrections.d.ts +13 -0
  85. package/dist/learn/corrections.js +23 -0
  86. package/dist/learn/delete.d.ts +17 -0
  87. package/dist/learn/delete.js +42 -0
  88. package/dist/learn/folder.d.ts +35 -47
  89. package/dist/learn/folder.js +118 -134
  90. package/dist/learn/index.d.ts +3 -5
  91. package/dist/learn/index.js +6 -9
  92. package/dist/learn/learning.sh +45 -15
  93. package/dist/learn/promote.d.ts +20 -2
  94. package/dist/learn/promote.js +17 -4
  95. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +34 -38
  96. package/dist/learn/{skills.js → workflow-draft.js} +65 -59
  97. package/dist/learn/workflow-nodes.d.ts +22 -1
  98. package/dist/learn/workflow-nodes.js +29 -10
  99. package/dist/learned-workflow.js +2 -2
  100. package/dist/learning-cost.d.ts +127 -13
  101. package/dist/learning-cost.js +142 -10
  102. package/dist/learning-routes.d.ts +99 -170
  103. package/dist/learning-routes.js +199 -420
  104. package/dist/learning-run.d.ts +19 -40
  105. package/dist/learning-run.js +23 -93
  106. package/dist/learning-setting.d.ts +4 -4
  107. package/dist/learning-setting.js +6 -6
  108. package/dist/learning-words.d.ts +28 -74
  109. package/dist/learning-words.js +64 -162
  110. package/dist/learning.d.ts +62 -393
  111. package/dist/learning.js +101 -651
  112. package/dist/listen-first.d.ts +30 -0
  113. package/dist/listen-first.js +115 -0
  114. package/dist/live-reach.d.ts +25 -2
  115. package/dist/live-reach.js +46 -4
  116. package/dist/llms.txt +2 -1
  117. package/dist/local-models.d.ts +3 -11
  118. package/dist/local-models.js +5 -6
  119. package/dist/mcp-servers-store.d.ts +16 -16
  120. package/dist/model-form.js +6 -5
  121. package/dist/model.d.ts +12 -4
  122. package/dist/model.js +41 -16
  123. package/dist/native/binding.js +1 -1
  124. package/dist/native/connection.js +1 -1
  125. package/dist/native/discovery.js +1 -1
  126. package/dist/native/instructions.d.ts +3 -0
  127. package/dist/native/instructions.js +5 -3
  128. package/dist/native/remote-worker-bridge.js +9 -43
  129. package/dist/native/remote.d.ts +8 -15
  130. package/dist/native/remote.js +3 -3
  131. package/dist/native/schema.js +1 -1
  132. package/dist/native/types.d.ts +2 -2
  133. package/dist/openapi.js +375 -347
  134. package/dist/owner.d.ts +8 -0
  135. package/dist/owner.js +11 -0
  136. package/dist/paid-calls.d.ts +14 -0
  137. package/dist/paid-calls.js +31 -1
  138. package/dist/particle-provider.d.ts +11 -0
  139. package/dist/particle-provider.js +135 -0
  140. package/dist/place.d.ts +8 -3
  141. package/dist/place.js +13 -9
  142. package/dist/port-models.d.ts +12 -4
  143. package/dist/port-models.js +28 -11
  144. package/dist/print.d.ts +27 -0
  145. package/dist/print.js +21 -0
  146. package/dist/provider.d.ts +7 -0
  147. package/dist/provider.js +30 -2
  148. package/dist/reflect-range.js +2 -3
  149. package/dist/run-launch.d.ts +14 -28
  150. package/dist/run-launch.js +9 -12
  151. package/dist/run-learning-served.d.ts +16 -90
  152. package/dist/run-listing.d.ts +34 -0
  153. package/dist/run-listing.js +128 -0
  154. package/dist/run-model-key.d.ts +64 -0
  155. package/dist/run-model-key.js +147 -0
  156. package/dist/run-timeline-served.js +5 -3
  157. package/dist/run-trace.d.ts +97 -0
  158. package/dist/run-trace.js +253 -0
  159. package/dist/run-view.d.ts +15 -0
  160. package/dist/run-view.js +9 -0
  161. package/dist/runnable.js +2 -1
  162. package/dist/runner/adapter-loop.d.ts +14 -6
  163. package/dist/runner/adapter-loop.js +25 -14
  164. package/dist/runner/adapter-run-spec.d.ts +22 -7
  165. package/dist/runner/adapter-run-spec.js +130 -77
  166. package/dist/runner/adapters/index.d.ts +4 -2
  167. package/dist/runner/adapters/index.js +35 -4
  168. package/dist/runner/adapters/pi.d.ts +4 -12
  169. package/dist/runner/adapters/pi.js +2 -2
  170. package/dist/runner/audit.d.ts +5 -1
  171. package/dist/runner/audit.js +31 -12
  172. package/dist/runner/beside.d.ts +7 -2
  173. package/dist/runner/beside.js +41 -9
  174. package/dist/runner/claim-secrets.d.ts +66 -1
  175. package/dist/runner/claim-secrets.js +136 -3
  176. package/dist/runner/cli-run-spec.d.ts +2 -1
  177. package/dist/runner/cli-run-spec.js +82 -59
  178. package/dist/runner/commands.d.ts +3 -6
  179. package/dist/runner/conformance/harness.d.ts +6 -0
  180. package/dist/runner/conformance/harness.js +16 -5
  181. package/dist/runner/dispatch.d.ts +2 -2
  182. package/dist/runner/end-of-run.d.ts +6 -14
  183. package/dist/runner/end-of-run.js +8 -33
  184. package/dist/runner/feedback-round.d.ts +5 -4
  185. package/dist/runner/feedback-round.js +14 -10
  186. package/dist/runner/github-app.js +3 -1
  187. package/dist/runner/harness-loops.d.ts +0 -8
  188. package/dist/runner/harness-loops.js +30 -56
  189. package/dist/runner/held.d.ts +170 -0
  190. package/dist/runner/held.js +57 -0
  191. package/dist/runner/journal-kinds.d.ts +7 -3
  192. package/dist/runner/journal-kinds.js +2 -3
  193. package/dist/runner/learned-first.d.ts +40 -0
  194. package/dist/runner/learned-first.js +32 -0
  195. package/dist/runner/learning-end.d.ts +77 -66
  196. package/dist/runner/learning-end.js +250 -299
  197. package/dist/runner/learning-seed.d.ts +15 -33
  198. package/dist/runner/learning-seed.js +24 -45
  199. package/dist/runner/loop-contract.d.ts +8 -3
  200. package/dist/runner/loop-contract.js +4 -0
  201. package/dist/runner/loop.js +6 -2
  202. package/dist/runner/main.d.ts +18 -9
  203. package/dist/runner/main.js +82 -22
  204. package/dist/runner/mcp-run.d.ts +11 -0
  205. package/dist/runner/mcp-run.js +67 -0
  206. package/dist/runner/memory-claim.d.ts +14 -6
  207. package/dist/runner/memory-claim.js +18 -9
  208. package/dist/runner/model-route.d.ts +7 -4
  209. package/dist/runner/model-route.js +22 -10
  210. package/dist/runner/native-loop.d.ts +0 -7
  211. package/dist/runner/native-loop.js +9 -101
  212. package/dist/runner/promotion.d.ts +13 -6
  213. package/dist/runner/promotion.js +63 -17
  214. package/dist/runner/reflect-hook.d.ts +64 -91
  215. package/dist/runner/reflect-hook.js +112 -206
  216. package/dist/runner/run-channel.d.ts +43 -0
  217. package/dist/runner/run-channel.js +467 -0
  218. package/dist/runner/run-child-host.d.ts +169 -0
  219. package/dist/runner/run-child-host.js +1222 -0
  220. package/dist/runner/run-child.d.ts +1 -0
  221. package/dist/runner/run-child.js +254 -0
  222. package/dist/runner/run-errors.d.ts +2 -0
  223. package/dist/runner/run-errors.js +20 -0
  224. package/dist/runner/runner.js +58 -9
  225. package/dist/runner/sdk-ask.d.ts +78 -0
  226. package/dist/runner/sdk-ask.js +158 -0
  227. package/dist/runner/sdk-loop.d.ts +2 -4
  228. package/dist/runner/sdk-loop.js +29 -49
  229. package/dist/runner/store-secrets.d.ts +5 -3
  230. package/dist/runner/store-secrets.js +14 -6
  231. package/dist/runner/workflow-first.d.ts +5 -0
  232. package/dist/runner/workflow-first.js +4 -0
  233. package/dist/runner/workflow-spec.js +17 -4
  234. package/dist/runs-over-store.d.ts +21 -32
  235. package/dist/runs-over-store.js +44 -41
  236. package/dist/sdk/runs.d.ts +6 -11
  237. package/dist/sdk/runs.js +20 -41
  238. package/dist/sdk/schema.js +3 -4
  239. package/dist/sdk/workflows.d.ts +1 -1
  240. package/dist/seal-key.d.ts +5 -0
  241. package/dist/seal-key.js +7 -0
  242. package/dist/secrets.d.ts +3 -0
  243. package/dist/secrets.js +16 -3
  244. package/dist/server.d.ts +119 -83
  245. package/dist/server.js +1121 -419
  246. package/dist/sign-ins-store.d.ts +8 -0
  247. package/dist/sign-ins-store.js +36 -1
  248. package/dist/skills.js +1 -1
  249. package/dist/store/index.d.ts +3 -3
  250. package/dist/store/index.js +2 -2
  251. package/dist/store/journal/storage.js +3 -0
  252. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  253. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  254. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  255. package/dist/store/schema.d.ts +53 -4
  256. package/dist/store/schema.js +137 -6
  257. package/dist/store/seal.d.ts +20 -2
  258. package/dist/store/seal.js +24 -8
  259. package/dist/store/sqlite/connection.d.ts +2 -0
  260. package/dist/store/sqlite/connection.js +3 -1
  261. package/dist/store/sqlite/run-launch.d.ts +4 -1
  262. package/dist/store/sqlite/run-launch.js +12 -0
  263. package/dist/store/sqlite/run-patch.d.ts +0 -17
  264. package/dist/store/sqlite/run-patch.js +4 -33
  265. package/dist/store/sqlite/store.d.ts +3 -2
  266. package/dist/store/sqlite/store.js +360 -75
  267. package/dist/store/sqlite/worker.js +25 -0
  268. package/dist/store/store.d.ts +231 -39
  269. package/dist/store/store.js +25 -3
  270. package/dist/store-reads/analytics.js +11 -1
  271. package/dist/store-reads/learning.d.ts +131 -194
  272. package/dist/store-reads/learning.js +292 -301
  273. package/dist/store-reads/loop.d.ts +0 -1
  274. package/dist/store-reads/loop.js +1 -1
  275. package/dist/store-reads/stats.js +13 -3
  276. package/dist/store-view.d.ts +34 -2
  277. package/dist/store-view.js +108 -41
  278. package/dist/telemetry.d.ts +59 -0
  279. package/dist/telemetry.js +153 -0
  280. package/dist/template-eval.d.ts +3 -6
  281. package/dist/template-eval.js +22 -36
  282. package/dist/templates.d.ts +2 -1
  283. package/dist/templates.js +6 -3
  284. package/dist/timeline/index.d.ts +1 -1
  285. package/dist/timeline/index.js +1 -1
  286. package/dist/timeline/timeline.d.ts +5 -1
  287. package/dist/timeline/timeline.js +16 -0
  288. package/dist/tool-gate.d.ts +0 -7
  289. package/dist/tool-gate.js +1 -15
  290. package/dist/tool-keys-store.d.ts +1 -1
  291. package/dist/tool-keys.d.ts +6 -4
  292. package/dist/tool-keys.js +12 -6
  293. package/dist/tool-plane.d.ts +12 -12
  294. package/dist/tools.d.ts +13 -13
  295. package/dist/tools.js +29 -9
  296. package/dist/trigger-adapter.d.ts +3 -0
  297. package/dist/trigger-adapters.d.ts +4 -0
  298. package/dist/trigger-adapters.js +13 -0
  299. package/dist/trigger-composio.d.ts +58 -1
  300. package/dist/trigger-composio.js +160 -6
  301. package/dist/triggers.d.ts +64 -5
  302. package/dist/triggers.js +141 -17
  303. package/dist/validate.d.ts +11 -7
  304. package/dist/validate.js +9 -8
  305. package/dist/webhooks.d.ts +4 -1
  306. package/dist/webhooks.js +11 -4
  307. package/dist/workspace/agent-computer.d.ts +2 -0
  308. package/dist/workspace/agent-computer.js +2 -0
  309. package/dist/workspace/archil-claim.d.ts +7 -0
  310. package/dist/workspace/archil-claim.js +29 -0
  311. package/dist/workspace/archil.d.ts +9 -1
  312. package/dist/workspace/archil.js +165 -3
  313. package/dist/workspace/attach.d.ts +3 -1
  314. package/dist/workspace/attach.js +2 -0
  315. package/dist/workspace/attached-computers.d.ts +16 -5
  316. package/dist/workspace/attached-computers.js +25 -9
  317. package/dist/workspace/computer-deps.js +1 -1
  318. package/dist/workspace/computer-for-claim.d.ts +22 -8
  319. package/dist/workspace/computer-for-claim.js +339 -46
  320. package/dist/workspace/computer-hold.js +2 -1
  321. package/dist/workspace/computer-kept.d.ts +11 -1
  322. package/dist/workspace/computer-kept.js +24 -3
  323. package/dist/workspace/resolve-computer.d.ts +41 -21
  324. package/dist/workspace/resolve-computer.js +172 -64
  325. package/dist/workspace/revision-skills.d.ts +1 -2
  326. package/dist/workspace/revision-skills.js +3 -4
  327. package/dist/workspace/run-workspace.d.ts +1 -1
  328. package/dist/workspace/run-workspace.js +5 -0
  329. package/dist/workspace/synced-folder.d.ts +85 -0
  330. package/dist/workspace/synced-folder.js +230 -0
  331. package/dist/workspace/workspace.d.ts +4 -0
  332. package/launcher/agentrun-serve +1 -1
  333. package/package.json +10 -9
  334. package/templates/README.md +7 -7
  335. package/templates/inbound-lead/agent.md +3 -3
  336. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  337. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  338. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  339. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  340. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  341. package/templates/inbound-lead/lead.schema.json +6 -5
  342. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  343. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  344. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  345. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  346. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  347. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  348. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  349. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  350. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  351. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  352. package/dist/console/assets/index-BrcDSBD8.css +0 -1
  353. package/dist/console/assets/index-Bz6IWncl.js +0 -711
  354. package/dist/learn/grade.d.ts +0 -138
  355. package/dist/learn/grade.js +0 -682
  356. package/dist/learn/notes.d.ts +0 -81
  357. package/dist/learn/notes.js +0 -178
  358. package/dist/learn/reflect.d.ts +0 -77
  359. package/dist/learn/reflect.js +0 -228
  360. package/dist/learn/relevance.d.ts +0 -24
  361. package/dist/learn/relevance.js +0 -91
  362. package/dist/learn/seed-check.d.ts +0 -74
  363. package/dist/learn/seed-check.js +0 -103
  364. package/dist/learning-batch.d.ts +0 -291
  365. package/dist/learning-batch.js +0 -600
  366. package/dist/learning-evals.d.ts +0 -33
  367. package/dist/learning-evals.js +0 -98
  368. package/dist/native/context.d.ts +0 -6
  369. package/dist/native/context.js +0 -22
  370. package/dist/propose.d.ts +0 -52
  371. package/dist/propose.js +0 -224
  372. package/dist/runner/learning-ask.d.ts +0 -47
  373. package/dist/runner/learning-ask.js +0 -128
  374. package/dist/runner/learning-dispatch.d.ts +0 -45
  375. package/dist/runner/learning-dispatch.js +0 -99
  376. package/dist/runner/learning-factory.d.ts +0 -16
  377. package/dist/runner/learning-factory.js +0 -50
  378. package/dist/runner/learning-loop.d.ts +0 -273
  379. package/dist/runner/learning-loop.js +0 -521
  380. package/dist/usage.d.ts +0 -11
  381. package/dist/usage.js +0 -11
  382. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  383. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  384. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  385. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  386. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  387. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  388. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
package/dist/owner.d.ts CHANGED
@@ -58,6 +58,14 @@ export declare class Owner {
58
58
  attach(baseUrl: string): void;
59
59
  /** The setup page's link: with its code when setup needs one, a new code printed (never answered) when none is good. */
60
60
  setupLink(): string;
61
+ /** A setup code to use, for whoever asks with no credential: the one that stands is kept (never voided here), and a
62
+ * new one is printed only when none is good (expired, or spent). Answers which, and when the code now good runs
63
+ * out; never the code. Null where there is none to give: an open setup, or a setup under way, whose spent code
64
+ * needs no successor. */
65
+ renewSetupCode(): {
66
+ printed: boolean;
67
+ until: number;
68
+ } | null;
61
69
  /** Whether `given` is the setup code. None given (`missing`) is no try: it never counts against the printed code. A
62
70
  * wrong one counts, and the fifth voids it and prints a new one at once (`new`), as an expired one does. */
63
71
  private spendCode;
package/dist/owner.js CHANGED
@@ -173,6 +173,17 @@ export class Owner {
173
173
  }
174
174
  return `${this.base}/setup#code=${this.setupCode.code}`;
175
175
  }
176
+ /** A setup code to use, for whoever asks with no credential: the one that stands is kept (never voided here), and a
177
+ * new one is printed only when none is good (expired, or spent). Answers which, and when the code now good runs
178
+ * out; never the code. Null where there is none to give: an open setup, or a setup under way, whose spent code
179
+ * needs no successor. */
180
+ renewSetupCode() {
181
+ if (this.openSetup || this.settingUp)
182
+ return null;
183
+ const before = this.setupCode;
184
+ this.setupLink();
185
+ return { printed: this.setupCode !== before, until: this.setupCode.until };
186
+ }
176
187
  /** Whether `given` is the setup code. None given (`missing`) is no try: it never counts against the printed code. A
177
188
  * wrong one counts, and the fifth voids it and prints a new one at once (`new`), as an expired one does. */
178
189
  spendCode(given) {
@@ -82,6 +82,17 @@ export declare const bookedIn: <T>(ledger: Ledger | undefined, work: () => Promi
82
82
  export declare function paidRequest(fee: Fee, send: () => Promise<Response>): Promise<Response>;
83
83
  /** paidStep's chargeOf for a step that charged nothing and is given back: its mark settled with no charge row. */
84
84
  export declare const GIVEN_BACK = "given back";
85
+ /** Whether the current work runs inside a call's ledger (bookedIn): a host tool call of the run's, or a workflow call
86
+ * node's tool. A lost sandbox is started again only for one (computer-for-claim.ts lostAware), never for the run's end. */
87
+ export declare const inToolCall: () => boolean;
88
+ /** The ledger of the tool call the current work runs in, as a run's process hands it to its runner with each call it
89
+ * makes over its channel (run-channel.ts context): its call's id, the run's one ledger and its pause. None outside one. */
90
+ export declare const carriedLedger: () => Ledger | undefined;
91
+ /** A runner's side of carriedLedger: `run` inside the ledger a run's process carried with its call (bookedIn), so a
92
+ * paid step the runner makes for it (an MCP tool's call, a computer's) books on the run's one ledger and a lost sandbox
93
+ * is started again only inside a tool call (inToolCall). What does not read as one runs outside any ledger, where a paid
94
+ * request is refused. */
95
+ export declare const withinCarried: (carried: unknown, run: () => unknown) => unknown;
85
96
  /** The run's one ledger the current call books on (Ledger.paid), when it has one: the runner's. */
86
97
  export declare const paidLedger: () => PaidBooking | undefined;
87
98
  /** Stops the run the current call books in, in `words`: handed to its pause (Ledger.pause) as a cap refusal no raise
@@ -89,6 +100,9 @@ export declare const paidLedger: () => PaidBooking | undefined;
89
100
  * run ends failed in them, past its cap too, as a cap refusal for good ends it. Its code is the cap's, so the refused
90
101
  * request reads as the cap's refusal (no model error row of its own). */
91
102
  export declare const stopRun: (words: string) => Promise<void>;
103
+ /** Stops the run whose pause is `pause` (its ledger's: the adapter loop's RunLedger.pause), in `words`, as stopRun does,
104
+ * from any caller: one outside a tool call (the owner's computer channel) too. */
105
+ export declare const stopRunWith: (pause: NonNullable<Ledger["pause"]>) => (words: string) => Promise<void>;
92
106
  /** One paid step on the run's one ledger `paid`, under call `call`: admitted at `holdUsd` (refused unsent: the cap's words,
93
107
  * or why its hold could not be kept), then `run`, then settled at `chargeOf` its outcome (null: at its hold; GIVEN_BACK:
94
108
  * given back, nothing charged, as a hold-only step's: a request its provider refused unrun leaves no charge row). One refused
@@ -101,6 +101,29 @@ export async function paidRequest(fee, send) {
101
101
  export const GIVEN_BACK = "given back";
102
102
  /** Each paid request of this process on the run's one ledger, numbered within its call (one call may make several). */
103
103
  let paidSeq = 0;
104
+ /** Whether the current work runs inside a call's ledger (bookedIn): a host tool call of the run's, or a workflow call
105
+ * node's tool. A lost sandbox is started again only for one (computer-for-claim.ts lostAware), never for the run's end. */
106
+ export const inToolCall = () => ledgers.getStore() !== undefined;
107
+ /** The ledger of the tool call the current work runs in, as a run's process hands it to its runner with each call it
108
+ * makes over its channel (run-channel.ts context): its call's id, the run's one ledger and its pause. None outside one. */
109
+ export const carriedLedger = () => {
110
+ const ledger = ledgers.getStore();
111
+ if (!ledger)
112
+ return undefined;
113
+ return { call: ledger.call, ...(ledger.paid ? { paid: { admit: (request) => ledger.paid.admit(request), settle: (id, usd, options) => ledger.paid.settle(id, usd, options) } } : {}), ...(ledger.pause ? { pause: ledger.pause } : {}) };
114
+ };
115
+ /** A runner's side of carriedLedger: `run` inside the ledger a run's process carried with its call (bookedIn), so a
116
+ * paid step the runner makes for it (an MCP tool's call, a computer's) books on the run's one ledger and a lost sandbox
117
+ * is started again only inside a tool call (inToolCall). What does not read as one runs outside any ledger, where a paid
118
+ * request is refused. */
119
+ export const withinCarried = (carried, run) => {
120
+ const given = carried;
121
+ if (!given || typeof given !== "object" || typeof given.call !== "string")
122
+ return run();
123
+ const paid = given.paid && typeof given.paid.admit === "function" && typeof given.paid.settle === "function" ? given.paid : undefined;
124
+ const pause = typeof given.pause === "function" ? given.pause : undefined;
125
+ return ledgers.run({ call: given.call, ...(paid ? { paid } : {}), ...(pause ? { pause } : {}) }, run);
126
+ };
104
127
  /** The run's one ledger the current call books on (Ledger.paid), when it has one: the runner's. */
105
128
  export const paidLedger = () => ledgers.getStore()?.paid;
106
129
  /** Stops the run the current call books in, in `words`: handed to its pause (Ledger.pause) as a cap refusal no raise
@@ -108,7 +131,14 @@ export const paidLedger = () => ledgers.getStore()?.paid;
108
131
  * run ends failed in them, past its cap too, as a cap refusal for good ends it. Its code is the cap's, so the refused
109
132
  * request reads as the cap's refusal (no model error row of its own). */
110
133
  export const stopRun = async (words) => {
111
- await ledgers.getStore()?.pause?.({ refuse: words, code: SPEND_CAP_REACHED, forGood: true });
134
+ const pause = ledgers.getStore()?.pause;
135
+ if (pause)
136
+ await stopRunWith(pause)(words);
137
+ };
138
+ /** Stops the run whose pause is `pause` (its ledger's: the adapter loop's RunLedger.pause), in `words`, as stopRun does,
139
+ * from any caller: one outside a tool call (the owner's computer channel) too. */
140
+ export const stopRunWith = (pause) => async (words) => {
141
+ await pause({ refuse: words, code: SPEND_CAP_REACHED, forGood: true });
112
142
  };
113
143
  /** One paid step on the run's one ledger `paid`, under call `call`: admitted at `holdUsd` (refused unsent: the cap's words,
114
144
  * or why its hold could not be kept), then `run`, then settled at `chargeOf` its outcome (null: at its hold; GIVEN_BACK:
@@ -0,0 +1,11 @@
1
+ /** Regular peak list prices, USD per million tokens (https://docs.particle.ai/models, 2026-11-15).
2
+ * Cached input is part of prompt_tokens; reasoning is already part of completion_tokens. Off-peak,
3
+ * Flex and account-specific pricing can change the bill. These rates estimate usage and reserve the cap,
4
+ * never claim to be a provider-reported charge. */
5
+ export declare const PARTICLE_1_PRICE: {
6
+ readonly input: 0.25;
7
+ readonly output: 1;
8
+ readonly cacheRead: 0.03;
9
+ readonly cacheWrite: 0;
10
+ };
11
+ export declare function particleProvider(): import("@earendil-works/pi-ai").Provider<"openai-completions">;
@@ -0,0 +1,135 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
3
+ import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
4
+ import { createProvider } from "@earendil-works/pi-ai/models";
5
+ /** Regular peak list prices, USD per million tokens (https://docs.particle.ai/models, 2026-11-15).
6
+ * Cached input is part of prompt_tokens; reasoning is already part of completion_tokens. Off-peak,
7
+ * Flex and account-specific pricing can change the bill. These rates estimate usage and reserve the cap,
8
+ * never claim to be a provider-reported charge. */
9
+ export const PARTICLE_1_PRICE = { input: 0.25, output: 1, cacheRead: 0.03, cacheWrite: 0 };
10
+ /** Direct Particle uses Chat Completions, not OpenRouter's reasoning envelope or text tools.
11
+ * HTTP Responses is unsupported (https://docs.particle.ai/responses); Pi translates its session
12
+ * requests through this provider. Limits are Particle's own model catalog, not OpenRouter's. */
13
+ const PARTICLE_1 = {
14
+ id: "particle-1",
15
+ name: "Particle-1",
16
+ provider: "particle",
17
+ api: "openai-completions",
18
+ baseUrl: "https://api.particle.ai/v1",
19
+ reasoning: true,
20
+ input: ["text", "image"],
21
+ contextWindow: 1_048_576,
22
+ maxTokens: 131_072,
23
+ cost: PARTICLE_1_PRICE,
24
+ thinkingLevelMap: { off: "none", minimal: "low", low: "low", medium: "high", high: "high", xhigh: "high", max: "max" },
25
+ compat: {
26
+ thinkingFormat: "openai",
27
+ supportsReasoningEffort: true,
28
+ supportsUsageInStreaming: true,
29
+ supportsDeveloperRole: false,
30
+ supportsStore: false,
31
+ supportsStrictMode: false,
32
+ maxTokensField: "max_completion_tokens",
33
+ promptCacheKeyMode: "enabled",
34
+ sendSessionAffinityHeaders: false,
35
+ },
36
+ };
37
+ /** A stable opaque key, bounded below Particle's 256 UTF-8 byte limit and pi-ai's 64-character
38
+ * limit. Hashing the whole ID avoids collisions from truncating long IDs with a shared prefix. */
39
+ const requestOptions = (options) => ({
40
+ ...options,
41
+ maxRetries: 0,
42
+ ...(options?.sessionId ? { sessionId: createHash("sha256").update(options.sessionId).digest("hex") } : {}),
43
+ });
44
+ /** With include_usage, a successful stream must carry the provider's token counts. A finish_reason
45
+ * alone proves neither usage nor a free request. Fail closed on absent/malformed accounting. */
46
+ function metered(send) {
47
+ return ((model, context, options) => {
48
+ let accounted = false;
49
+ let ended = false;
50
+ const fetcher = options?.fetch ?? globalThis.fetch;
51
+ const inner = send(model, context, {
52
+ ...requestOptions(options),
53
+ // The shared client accepts EOF after finish_reason. Particle explicitly requires [DONE]
54
+ // (docs.particle.ai/streaming); observe that delimiter without buffering the response.
55
+ fetch: async (input, init) => {
56
+ const response = await fetcher(input, init);
57
+ if (!response.ok || !response.body)
58
+ return response;
59
+ let tail = "";
60
+ const decoder = new TextDecoder();
61
+ return new Response(response.body.pipeThrough(new TransformStream({
62
+ transform(chunk, controller) {
63
+ const text = tail + decoder.decode(chunk, { stream: true });
64
+ ended ||= /(?:^|\r|\n)data:[ \t]*\[DONE\][ \t]*(?:\r|\n)/.test(text);
65
+ tail = text.slice(-128);
66
+ controller.enqueue(chunk);
67
+ },
68
+ })), { status: response.status, statusText: response.statusText, headers: response.headers });
69
+ },
70
+ onProviderStreamEvent: async (data, current) => {
71
+ const frame = data;
72
+ // Match both usage locations the shared client consumes; a later compatibility report must not
73
+ // overwrite already-validated accounting with unchecked counters.
74
+ const usage = frame?.usage || (Array.isArray(frame?.choices) ? frame.choices[0]?.usage : undefined);
75
+ if (usage) {
76
+ accounted = false;
77
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
78
+ // Validate every counter the shared client consumes, including its compatibility aliases.
79
+ // Particle documents no separately billed cache writes; treating them as free would underprice input.
80
+ const details = usage.prompt_tokens_details;
81
+ const cached = details?.cached_tokens ?? usage.prompt_cache_hit_tokens ?? usage.cached_tokens ?? 0;
82
+ const written = details?.cache_write_tokens ?? 0;
83
+ const reasoning = usage.completion_tokens_details?.reasoning_tokens ?? 0;
84
+ if (!count(usage.prompt_tokens) || !count(usage.completion_tokens) || !count(cached) || !count(reasoning) || written !== 0 || cached > usage.prompt_tokens || reasoning > usage.completion_tokens) {
85
+ throw new Error("Particle returned invalid token usage; cost is unknown.");
86
+ }
87
+ accounted = true;
88
+ }
89
+ await options?.onProviderStreamEvent?.(data, current);
90
+ },
91
+ });
92
+ const outer = createAssistantMessageEventStream();
93
+ void (async () => {
94
+ for await (const event of inner) {
95
+ if (event.type === "done" && (!accounted || !ended)) {
96
+ event.message.stopReason = "error";
97
+ event.message.errorMessage = !accounted ? "Particle stream ended without token usage; cost is unknown." : "Particle stream ended without [DONE]; the response is incomplete and cost is unknown.";
98
+ delete event.message.usage.cost.total;
99
+ outer.push({ type: "error", reason: "error", error: event.message });
100
+ }
101
+ else {
102
+ if (event.type === "error" && !accounted)
103
+ delete event.error.usage.cost.total;
104
+ outer.push(event);
105
+ }
106
+ }
107
+ outer.end();
108
+ })().catch((error) => {
109
+ const failed = { role: "assistant", api: model.api, provider: model.provider, model: model.id, content: [], stopReason: options?.signal?.aborted ? "aborted" : "error", timestamp: Date.now(), errorMessage: String(error), usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } };
110
+ delete failed.usage.cost.total;
111
+ outer.push({ type: "error", reason: failed.stopReason, error: failed });
112
+ outer.end();
113
+ });
114
+ return outer;
115
+ });
116
+ }
117
+ export function particleProvider() {
118
+ const api = openAICompletionsApi();
119
+ return createProvider({
120
+ id: "particle",
121
+ name: "Particle",
122
+ baseUrl: PARTICLE_1.baseUrl,
123
+ auth: { apiKey: { name: "PARTICLE_API_KEY", resolve: async ({ ctx }) => {
124
+ const key = await ctx.env("PARTICLE_API_KEY");
125
+ return key ? { auth: { apiKey: key }, source: "PARTICLE_API_KEY" } : undefined;
126
+ } } },
127
+ models: [PARTICLE_1],
128
+ // Do not transparently replay a paid request after a transport/5xx failure whose outcome is
129
+ // unknown. Even a safe pre-admission 429 is surfaced for the caller to retry deliberately.
130
+ api: {
131
+ stream: metered(api.stream),
132
+ streamSimple: metered(api.streamSimple),
133
+ },
134
+ });
135
+ }
package/dist/place.d.ts CHANGED
@@ -22,9 +22,14 @@ export declare function newAgentPlace(registry: readonly BoxOffer[]): {
22
22
  why: string;
23
23
  };
24
24
  /** The place a revision that names none resolves to, at its create and at each run alike: this server's default place
25
- * (newAgentPlace) for an agentic revision; the runner for a workflow, which is never given a box, and for one that names
26
- * a tool the box refuses (`refused`: the browser, runner-only for now). */
27
- export declare function defaultPlaceOf(kind: "agentic" | "workflow", tools: readonly unknown[], registry: readonly BoxOffer[], refused: (tool: string) => boolean): Place;
25
+ * (newAgentPlace) for an agentic revision with a tool that runs only in a box (`flags`, tools.ts: bash and the
26
+ * background tools); the runner for a workflow, which is never given a box, for one whose tools need no shell (none, or
27
+ * only read and write: a container would only hold up its start), and for one that names a tool the box refuses (the
28
+ * browser, runner-only for now). */
29
+ export declare function defaultPlaceOf(kind: "agentic" | "workflow", tools: readonly unknown[], registry: readonly BoxOffer[], flags: (tool: string) => {
30
+ readonly sandboxOnly?: true;
31
+ readonly runnerOnly?: true;
32
+ } | undefined): Place;
28
33
  /** The tools a new agent in the default box is given when its definition names none: a shell, and the background tools
29
34
  * that start, read, feed, signal and list commands that outlive one call (background.ts SHELL_TOOLS, which a test holds
30
35
  * this list to; written out here, since background.ts reads this module). A definition that names its tools, an empty
package/dist/place.js CHANGED
@@ -7,11 +7,12 @@
7
7
  // of that provider (computer-setting.ts computerOfPlace), which the run's claim starts: Docker, Daytona or Modal. A harness's own tools in the box, when they come, are an option of sandbox, never a third
8
8
  // mode.
9
9
  //
10
- // The box is a new agent's default machine: an agentic definition that names no place is saved, at its create, with the
11
- // Docker box as its place wherever this server has docker, and with bash when it names no tools
12
- // (newAgentPlace). A revision that names no place resolves the same way at each run (defaultPlaceOf): this server's
13
- // default_place, so where docker is there now it runs in the Docker box, and the runner where it is not. A workflow, and a
14
- // revision with a tool the box refuses, run on the runner.
10
+ // The box is a new agent's default machine for a shell: an agentic definition that names no place and no tools is saved,
11
+ // at its create, with the Docker box as its place wherever this server has docker, and with bash (newAgentPlace). One that
12
+ // names its tools gets the box only when one of them needs a shell; else it keeps no place and runs on the runner, with
13
+ // no container to wait for. A revision that names no place resolves the same way at each run (defaultPlaceOf): with a
14
+ // shell tool, this server's default_place, so where docker is there now it runs in the Docker box, and the runner where it
15
+ // is not. A workflow, a revision whose tools need no shell, and one with a tool the box refuses run on the runner.
15
16
  import { BOX_IDS, BOXES_ENV } from "./place-offers.js";
16
17
  import { sentence } from "./errors.js";
17
18
  export const PLACE_MODES = ["runner", "sandbox"];
@@ -39,10 +40,13 @@ export function newAgentPlace(registry) {
39
40
  return { reason: `new agents run on the runner, because the docker box is unavailable here: ${why}`, why };
40
41
  }
41
42
  /** The place a revision that names none resolves to, at its create and at each run alike: this server's default place
42
- * (newAgentPlace) for an agentic revision; the runner for a workflow, which is never given a box, and for one that names
43
- * a tool the box refuses (`refused`: the browser, runner-only for now). */
44
- export function defaultPlaceOf(kind, tools, registry, refused) {
45
- if (kind === "workflow" || tools.some((tool) => typeof tool === "string" && refused(tool)))
43
+ * (newAgentPlace) for an agentic revision with a tool that runs only in a box (`flags`, tools.ts: bash and the
44
+ * background tools); the runner for a workflow, which is never given a box, for one whose tools need no shell (none, or
45
+ * only read and write: a container would only hold up its start), and for one that names a tool the box refuses (the
46
+ * browser, runner-only for now). */
47
+ export function defaultPlaceOf(kind, tools, registry, flags) {
48
+ const named = tools.flatMap((tool) => (typeof tool === "string" ? [flags(tool)] : []));
49
+ if (kind === "workflow" || named.some((tool) => tool?.runnerOnly) || !named.some((tool) => tool?.sandboxOnly))
46
50
  return { mode: "runner" };
47
51
  const fresh = newAgentPlace(registry);
48
52
  return "place" in fresh ? fresh.place : { mode: "runner" };
@@ -17,12 +17,19 @@ export type ThinkingLevelMap = NonNullable<Model<Api>["thinkingLevelMap"]>;
17
17
  /** `developerRole`: on Responses, the instructions go as a developer message, not a system one (a ChatGPT plan's route,
18
18
  * which takes no system message). `adaptiveThinking`: on Messages, the session asks its thinking level as an adaptive
19
19
  * effort (pi-ai's `forceAdaptiveThinking`), never a token budget: the route's own translation reads that level back
20
- * (model-route.ts LEVELS_BY_NAME). */
20
+ * (model-route.ts LEVELS_BY_NAME). `translatedChatCompletions`: the Messages hop carries native Chat Completions
21
+ * reasoning and a conversation cache key; its thinking blocks may have no signature. */
21
22
  export type SessionLike = Partial<Pick<Model<Api>, "reasoning" | "cost" | "contextWindow" | "maxTokens" | "thinkingLevelMap">> & {
22
23
  readonly input?: readonly string[];
23
24
  readonly inputLimits?: unknown;
24
25
  readonly developerRole?: boolean;
25
26
  readonly adaptiveThinking?: boolean;
27
+ readonly translatedChatCompletions?: boolean;
28
+ };
29
+ /** Pi's side port with its route's catalog metadata. A plain harness port remains valid; the kernel needs only the
30
+ * proxy coordinates, while the host's model client also keeps its reasoning, limits and translation settings. */
31
+ export type SessionModelPort = SessionPort & {
32
+ readonly like?: SessionLike;
26
33
  };
27
34
  /** The one model of a session's route as pi-ai lists it, for the port's requests and for pi's own (runner adapters/pi.ts):
28
35
  * `model` in `api` at the proxy `url` (sessionBaseUrl), under `provider`, with `headers` (the session key as the proxy
@@ -41,7 +48,7 @@ export declare function sessionModel(api: SessionPort["api"], url: string, model
41
48
  * credential (named `keyName`). The proxy knows a request by `authorization: Bearer <key>`: on Messages that header is set
42
49
  * on the model, since pi-ai's Anthropic client sends its key as x-api-key, which the proxy does not forward; on Responses
43
50
  * pi-ai sends the key as that bearer token itself. The one client every runner caller of a session proxy builds: pi's
44
- * sessions, the learning grader, a workflow's model nodes. Each request's images are checked as they are attached
51
+ * sessions and a workflow's model nodes. Each request's images are checked as they are attached
45
52
  * (attach-images.ts): one a provider would refuse goes as a text saying why. */
46
53
  export declare function sessionProvider(api: SessionPort["api"], proxy: {
47
54
  readonly url: string;
@@ -61,8 +68,9 @@ export type PortModels = {
61
68
  };
62
69
  /** Models over `port` (the session's, read at each request: undefined until a drive has attached a proxy, and anew for
63
70
  * each drive), one model named by any provider and id: the session's own, listed under `provider`. `like`: the
64
- * catalog's entry for the model the run is priced by, whose reasoning, limits and price the port's model takes. */
65
- export declare function portModels(port: () => SessionPort | undefined, like?: Partial<Model<Api>>, provider?: string): Promise<PortModels>;
71
+ * catalog's entry for the model the run is priced by, whose reasoning, limits and price the port's model takes; absent,
72
+ * the current port's own metadata, when supplied by Pi. */
73
+ export declare function portModels(port: () => SessionModelPort | undefined, like?: SessionLike, provider?: string): Promise<PortModels>;
66
74
  /** Port models of several ports as one registry (learned-workflow.ts takes one): each listed under its own provider id
67
75
  * (PORT_PROVIDER for the session's, tierProvider(tier) for a tier's), a model's request sent through the port it came
68
76
  * from. */
@@ -32,7 +32,7 @@ export function sessionModel(api, url, model, options) {
32
32
  cost: like?.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
33
33
  contextWindow: like?.contextWindow ?? 200_000, maxTokens: like?.maxTokens ?? 32_000,
34
34
  ...(api === "openai-responses" ? { compat: { supportsDeveloperRole: like?.developerRole === true } } : {}),
35
- ...(api === "anthropic-messages" && like?.adaptiveThinking ? { compat: { forceAdaptiveThinking: true } } : {}),
35
+ ...(api === "anthropic-messages" && (like?.adaptiveThinking || like?.translatedChatCompletions) ? { compat: { forceAdaptiveThinking: true, ...(like.translatedChatCompletions ? { allowEmptySignature: true } : {}) } } : {}),
36
36
  };
37
37
  }
38
38
  /** pi-ai's provider for the one model of a session's proxy on its wire: pi-ai's client of `api` (Anthropic's Messages or
@@ -40,7 +40,7 @@ export function sessionModel(api, url, model, options) {
40
40
  * credential (named `keyName`). The proxy knows a request by `authorization: Bearer <key>`: on Messages that header is set
41
41
  * on the model, since pi-ai's Anthropic client sends its key as x-api-key, which the proxy does not forward; on Responses
42
42
  * pi-ai sends the key as that bearer token itself. The one client every runner caller of a session proxy builds: pi's
43
- * sessions, the learning grader, a workflow's model nodes. Each request's images are checked as they are attached
43
+ * sessions and a workflow's model nodes. Each request's images are checked as they are attached
44
44
  * (attach-images.ts): one a provider would refuse goes as a text saying why. */
45
45
  export function sessionProvider(api, proxy, model, options) {
46
46
  return createProvider({
@@ -48,18 +48,33 @@ export function sessionProvider(api, proxy, model, options) {
48
48
  baseUrl: sessionBaseUrl(api, proxy.url),
49
49
  auth: { apiKey: { name: options.keyName, resolve: async () => ({ auth: { apiKey: proxy.key }, source: "session" }) } },
50
50
  models: [sessionModel(api, proxy.url, model, { provider: options.provider, ...(api === "anthropic-messages" ? { headers: { authorization: `Bearer ${proxy.key}` } } : {}), ...(options.like ? { like: options.like } : {}), reasoning: options.reasoning })],
51
- api: attachingImages(api === "anthropic-messages" ? anthropicMessagesApi() : openAIResponsesApi()),
51
+ api: sessionApi(api, options.like),
52
52
  });
53
53
  }
54
+ /** A translated Chat Completions session carries its cache identity in Messages' existing metadata field: the proxy
55
+ * preserves it without forwarding extra headers. The translation uses it only for provider cache affinity. */
56
+ function sessionApi(api, like) {
57
+ const own = attachingImages(api === "anthropic-messages" ? anthropicMessagesApi() : openAIResponsesApi());
58
+ if (api !== "anthropic-messages" || !like?.translatedChatCompletions)
59
+ return own;
60
+ const withSession = (options) => ({
61
+ ...options,
62
+ // The upstream can have accepted a paid request before this hop fails. Never replay it implicitly.
63
+ maxRetries: 0,
64
+ ...(options?.cacheRetention === "none" ? { metadata: { ...options.metadata, user_id: "" } } : options?.sessionId ? { metadata: { ...options.metadata, user_id: options.sessionId } } : {}),
65
+ });
66
+ return {
67
+ ...own,
68
+ stream: (model, context, options) => own.stream(model, context, withSession(options)),
69
+ streamSimple: (model, context, options) => own.streamSimple(model, context, withSession(options)),
70
+ };
71
+ }
54
72
  /** Models over `port` (the session's, read at each request: undefined until a drive has attached a proxy, and anew for
55
73
  * each drive), one model named by any provider and id: the session's own, listed under `provider`. `like`: the
56
- * catalog's entry for the model the run is priced by, whose reasoning, limits and price the port's model takes. */
74
+ * catalog's entry for the model the run is priced by, whose reasoning, limits and price the port's model takes; absent,
75
+ * the current port's own metadata, when supplied by Pi. */
57
76
  export async function portModels(port, like, provider = PORT_PROVIDER) {
58
- const [{ createModels, createProvider }, { anthropicMessagesApi }, { openAIResponsesApi }] = await Promise.all([
59
- import("@earendil-works/pi-ai/models"),
60
- import("@earendil-works/pi-ai/api/anthropic-messages.lazy"),
61
- import("@earendil-works/pi-ai/api/openai-responses.lazy"),
62
- ]);
77
+ const { createModels } = await import("@earendil-works/pi-ai/models");
63
78
  // One registry per proxy and key: a later drive's proxy is a new address.
64
79
  let built;
65
80
  const current = () => {
@@ -70,16 +85,18 @@ export async function portModels(port, like, provider = PORT_PROVIDER) {
70
85
  if (built?.at === at)
71
86
  return built;
72
87
  const baseUrl = sessionBaseUrl(now.api, now.url);
88
+ // Read the current drive's metadata with its port. An explicit caller description still takes precedence.
89
+ const description = like ?? now.like;
73
90
  // The side key as the proxy reads a key (a bearer token), and no beta header pi-ai would add of its own: the session's
74
91
  // policy admits the betas its harness sends, and these requests need none.
75
92
  const headers = { authorization: `Bearer ${now.key}`, ...(now.api === "anthropic-messages" ? { "anthropic-beta": null } : {}) };
76
- const model = sessionModel(now.api, now.url, now.model, { provider, headers, ...(like ? { like } : {}), reasoning: true });
93
+ const model = sessionModel(now.api, now.url, now.model, { provider, headers, ...(description ? { like: description } : {}), reasoning: true });
77
94
  const models = createModels({});
78
95
  models.setProvider(createProvider({
79
96
  id: provider, baseUrl,
80
97
  auth: { apiKey: { name: "the session's side key", resolve: async () => ({ auth: { apiKey: now.key }, source: "session" }) } },
81
98
  models: [model],
82
- api: attachingImages(now.api === "anthropic-messages" ? anthropicMessagesApi() : openAIResponsesApi()),
99
+ api: sessionApi(now.api, description),
83
100
  }));
84
101
  built = { at, models, model: models.getModel(provider, now.model) };
85
102
  return built;
package/dist/print.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { HoldShort } from "@parcha/agentrun-kernel";
1
2
  /** Where the token came from: made at this start (printed this once), kept in DIR/.token, the environment's
2
3
  * (AGENTRUN_TOKEN), or the token list's alone (AGENTRUN_TOKENS). */
3
4
  export type TokenSource = "made" | "file" | "env" | "list";
@@ -23,6 +24,32 @@ export declare function banner(o: {
23
24
  }): string[];
24
25
  /** One log line. */
25
26
  export declare const logLine: (event: string, fields?: Record<string, string | number>) => string;
27
+ /** The warn line of a paid request whose answer billed more input than the bound its hold was priced on (the kernel's
28
+ * HoldShort), the cap's tripwire for a hold that was too small: `cap_hold_short` with the run, the request's session and
29
+ * turn, the harness, the model, the bound and what it billed in tokens, and in USD what was held and, when its answer was
30
+ * priced, what it billed and the shortfall (billed less held). Ids and figures only: no prompt, answer, header, key or
31
+ * token. */
32
+ export declare function holdShortLine(o: {
33
+ run: string;
34
+ session: string;
35
+ turn: number;
36
+ harness: string;
37
+ model: string;
38
+ boundTokens: number;
39
+ billedTokens: number;
40
+ heldUsd: number;
41
+ billedUsd?: number;
42
+ }): string;
43
+ /** Writes `event`'s holdShortLine, when it is a booking's request_end that carries a `holdShort` (the kernel's booking,
44
+ * modelPortFor, tells one for a request billed past its hold's bound), to stderr with the runner's other warnings;
45
+ * any other event writes nothing. The one place every caller of the booking prints it (the adapter loop, a workflow
46
+ * run's model nodes), under `run` and `harness` (the harness, or what the booking's requests are). */
47
+ export declare function warnHoldShort(run: string, harness: string, event: {
48
+ type: string;
49
+ key: string;
50
+ turn?: number;
51
+ holdShort?: HoldShort;
52
+ }, warn?: (line: string) => void): void;
26
53
  /** The log line of a runner's start or end event (runner.ts RunnerEvent): `run_started` (run, agent, kind) once a run's
27
54
  * first claim, `run_ended` (run, agent, status, cost_usd) once it is final: `cost_usd` the exact cost or "unknown", and
28
55
  * beside an unknown one `cost_usd_at_most` when the run's stored cost is the most it can have cost. Any other event has
package/dist/print.js CHANGED
@@ -27,6 +27,27 @@ const value = (v) => {
27
27
  };
28
28
  /** One log line. */
29
29
  export const logLine = (event, fields = {}) => [`at=${new Date().toISOString()}`, `event=${event}`, ...Object.entries(fields).map(([k, v]) => `${k}=${value(v)}`)].join(" ");
30
+ /** The warn line of a paid request whose answer billed more input than the bound its hold was priced on (the kernel's
31
+ * HoldShort), the cap's tripwire for a hold that was too small: `cap_hold_short` with the run, the request's session and
32
+ * turn, the harness, the model, the bound and what it billed in tokens, and in USD what was held and, when its answer was
33
+ * priced, what it billed and the shortfall (billed less held). Ids and figures only: no prompt, answer, header, key or
34
+ * token. */
35
+ export function holdShortLine(o) {
36
+ const usd = (figure) => Number(figure.toFixed(6));
37
+ return logLine("cap_hold_short", {
38
+ run: o.run, session: o.session, turn: o.turn, harness: o.harness, model: o.model, bound_tokens: o.boundTokens, billed_tokens: o.billedTokens, held_usd: usd(o.heldUsd),
39
+ ...(o.billedUsd === undefined ? {} : { billed_usd: usd(o.billedUsd), short_usd: usd(o.billedUsd - o.heldUsd) }),
40
+ });
41
+ }
42
+ /** Writes `event`'s holdShortLine, when it is a booking's request_end that carries a `holdShort` (the kernel's booking,
43
+ * modelPortFor, tells one for a request billed past its hold's bound), to stderr with the runner's other warnings;
44
+ * any other event writes nothing. The one place every caller of the booking prints it (the adapter loop, a workflow
45
+ * run's model nodes), under `run` and `harness` (the harness, or what the booking's requests are). */
46
+ export function warnHoldShort(run, harness, event, warn = (line) => console.warn(line)) {
47
+ if (event.type !== "request_end" || !event.holdShort || event.turn === undefined)
48
+ return;
49
+ warn(holdShortLine({ run, session: event.key, turn: event.turn, harness, ...event.holdShort }));
50
+ }
30
51
  /** The log line of a runner's start or end event (runner.ts RunnerEvent): `run_started` (run, agent, kind) once a run's
31
52
  * first claim, `run_ended` (run, agent, status, cost_usd) once it is final: `cost_usd` the exact cost or "unknown", and
32
53
  * beside an unknown one `cost_usd_at_most` when the run's stored cost is the most it can have cost. Any other event has
@@ -1,4 +1,5 @@
1
1
  import type { Wire } from "@parcha/agentrun-kernel";
2
+ import type { ClaudeAgentLogin } from "@parcha/agentrun-harness-claude";
2
3
  import { type ModelNeeds, type ModelRef } from "./model.js";
3
4
  import { WIRES } from "./wires.js";
4
5
  export { WIRES };
@@ -28,6 +29,9 @@ export declare const OPENAI_ORIGIN = "https://api.openai.com";
28
29
  * rule: pi's gateway models take `<this>/v1` (model.ts).
29
30
  */
30
31
  export declare function gatewayBase(setting: string, value: string): string;
32
+ /** The generic gateway must speak HTTP Responses (or Messages). Particle exposes Chat Completions
33
+ * and a WebSocket-only Responses subset, so a direct API base is not a compatible gateway. */
34
+ export declare function modelGatewayBase(value: string): string;
31
35
  /**
32
36
  * Whether `wire` reaches its vendor's models here only through OpenRouter: OPENROUTER_API_KEY is set and none of the
33
37
  * wire's own settings is. Those win, as on a host with no OpenRouter key: the endpoint the host names (ANTHROPIC_BASE_URL
@@ -53,6 +57,8 @@ export declare function anthropicModelId(model: ModelRef): string;
53
57
  * vendor, a key that is not set (its `keys` name the ones that would fix it), or an endpoint a key may not go to. */
54
58
  /** `billing: "plan"`: a ChatGPT plan's route (chatgpt-plan.ts), billed to the plan, never priced here; its credential is
55
59
  * the plan's token, asked at each request, and `refused` tells the plan OpenAI answered 401 to one it sent. */
60
+ /** `login`: claude-agent on Claude Code's login on this machine (claude-login.ts): billed to the person's plan, its CLI
61
+ * calling Anthropic itself; `origin` and `credential` are never read (no proxy, no key). */
56
62
  export type Provider = {
57
63
  origin: string;
58
64
  credential: () => string | Promise<string>;
@@ -61,6 +67,7 @@ export type Provider = {
61
67
  priceModel: ModelRef;
62
68
  billing?: "plan";
63
69
  refused?: (credential: string) => Promise<void>;
70
+ login?: ClaudeAgentLogin;
64
71
  };
65
72
  export declare function providerFor(wire: Wire, env: NodeJS.ProcessEnv, model: ModelRef, who: string): Provider;
66
73
  /** The catalog entry a run on `wire` of `model` is capped and priced by: providerFor's, or the model's own (normalized)
package/dist/provider.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CLAUDE_LOGIN_PROVIDER, onClaudeLogin, claudeLoginOf } from "./claude-login.js";
1
2
  import { chooseModel, FAUX_ENV, hostModel, MODEL_PROVIDER } from "./model.js";
2
3
  import { WIRES } from "./wires.js";
3
4
  import { modelFormWhy } from "./model-form.js";
@@ -59,6 +60,27 @@ export function gatewayBase(setting, value) {
59
60
  throw wrong(`is ${url.protocol.replace(/:$/, "")}, not https`);
60
61
  return `${url.origin}${url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "")}`;
61
62
  }
63
+ /** The generic gateway must speak HTTP Responses (or Messages). Particle exposes Chat Completions
64
+ * and a WebSocket-only Responses subset, so a direct API base is not a compatible gateway. */
65
+ export function modelGatewayBase(value) {
66
+ const base = gatewayBase("AGENT_MODEL_BASE_URL", value);
67
+ if (["api.particle.ai", "us.api.particle.ai"].includes(new URL(base).hostname)) {
68
+ throw new HarnessUnavailable("Particle uses Chat Completions here: remove AGENT_MODEL_BASE_URL, save PARTICLE_API_KEY and select particle/particle-1 with Pi. Particle does not support HTTP POST /v1/responses.");
69
+ }
70
+ return base;
71
+ }
72
+ /** Whether `base` (a gatewayBase answer) is on the origin of serve's own gateway (AGENT_MODEL_BASE_URL): there a run's own
73
+ * model key (run-model-key.ts) is sent, so the endpoint needs no standing key of the server's. */
74
+ function onServeGateway(env, base) {
75
+ if (!env.AGENT_MODEL_BASE_URL)
76
+ return false;
77
+ try {
78
+ return new URL(gatewayBase("AGENT_MODEL_BASE_URL", env.AGENT_MODEL_BASE_URL)).origin === new URL(base).origin;
79
+ }
80
+ catch {
81
+ return false;
82
+ }
83
+ }
62
84
  /**
63
85
  * Whether `wire` reaches its vendor's models here only through OpenRouter: OPENROUTER_API_KEY is set and none of the
64
86
  * wire's own settings is. Those win, as on a host with no OpenRouter key: the endpoint the host names (ANTHROPIC_BASE_URL
@@ -94,7 +116,7 @@ function openRouterKey(env, who, named) {
94
116
  }
95
117
  /** Serve's gateway (AGENT_MODEL_BASE_URL) on either wire: its base, its key (AGENT_MODEL_API_KEY, or none) as a bearer
96
118
  * token, the model id as model.ts chose it, priced as runModels prices it. */
97
- const gatewayProvider = (env, model) => ({ origin: gatewayBase("AGENT_MODEL_BASE_URL", env.AGENT_MODEL_BASE_URL), credential: () => env.AGENT_MODEL_API_KEY || "none", auth: "bearer", modelId: model.modelId, priceModel: model });
119
+ const gatewayProvider = (env, model) => ({ origin: modelGatewayBase(env.AGENT_MODEL_BASE_URL), credential: () => env.AGENT_MODEL_API_KEY || "none", auth: "bearer", modelId: model.modelId, priceModel: model });
98
120
  export function providerFor(wire, env, model, who) {
99
121
  const named = `${model.provider}/${model.modelId}`;
100
122
  if (wire === "anthropic-messages") {
@@ -109,12 +131,18 @@ export function providerFor(wire, env, model, who) {
109
131
  if (model.provider !== "anthropic")
110
132
  throw new HarnessUnavailable(`${who} runs Anthropic models; the run's model is ${named}.`);
111
133
  const own = anthropicModelId(model);
134
+ // Claude Code's login on this machine, turned on here: claude-agent's Anthropic model goes on it, whatever key is set.
135
+ const login = onClaudeLogin(env, who) ? claudeLoginOf(env) : undefined;
136
+ if (login)
137
+ return { origin: ANTHROPIC_ORIGIN, credential: () => "", auth: "x-api-key", modelId: own, priceModel: { provider: CLAUDE_LOGIN_PROVIDER, modelId: own }, billing: "plan", login };
112
138
  if (openRouterOnly(wire, env))
113
139
  return { origin: OPENROUTER_BASE, credential: openRouterKey(env, who, named), auth: "bearer", modelId: own, priceModel: { provider: "openrouter", modelId: `anthropic/${openRouterName(own)}` } };
114
140
  // The endpoint first: one it refuses is the reason, and no key would fix it (no `keys`). An endpoint the host names
115
141
  // takes Anthropic's key alone: OpenRouter's never goes there.
116
142
  const origin = env.ANTHROPIC_BASE_URL ? gatewayBase("ANTHROPIC_BASE_URL", env.ANTHROPIC_BASE_URL) : ANTHROPIC_ORIGIN;
117
- if (!env.ANTHROPIC_API_KEY)
143
+ // An endpoint on serve's own gateway's origin takes each run's own key where the server holds none (run-model-key.ts):
144
+ // the harness runs here with no standing key, and a run with no key to spend is refused at its start.
145
+ if (!env.ANTHROPIC_API_KEY && !onServeGateway(env, origin))
118
146
  throw env.ANTHROPIC_BASE_URL ? new HarnessUnavailable(`${who} needs ANTHROPIC_API_KEY.`, undefined, ["ANTHROPIC_API_KEY"]) : new HarnessUnavailable(`${who} needs ANTHROPIC_API_KEY or OPENROUTER_API_KEY.`, undefined, ["ANTHROPIC_API_KEY", "OPENROUTER_API_KEY"]);
119
147
  return { origin, credential: () => env.ANTHROPIC_API_KEY ?? "", auth: "x-api-key", modelId: own, priceModel: { provider: "anthropic", modelId: own } };
120
148
  }