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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (350) hide show
  1. package/CHANGELOG.md +148 -5
  2. package/README.md +385 -305
  3. package/dist/acp-package.d.ts +28 -0
  4. package/dist/acp-package.js +23 -0
  5. package/dist/adapter-facts.d.ts +8 -1
  6. package/dist/adapter-facts.js +9 -1
  7. package/dist/adapters.d.ts +5 -0
  8. package/dist/adapters.js +36 -3
  9. package/dist/agent-delete.d.ts +50 -0
  10. package/dist/agent-delete.js +125 -0
  11. package/dist/agents-store.d.ts +9 -3
  12. package/dist/agents-store.js +22 -8
  13. package/dist/agents.d.ts +5 -1
  14. package/dist/agents.js +8 -4
  15. package/dist/api-only.d.ts +8 -3
  16. package/dist/api-only.js +10 -4
  17. package/dist/archil-routes.d.ts +5 -1
  18. package/dist/archil-routes.js +57 -2
  19. package/dist/browser-wait-ended.d.ts +2 -0
  20. package/dist/browser-wait-ended.js +2 -0
  21. package/dist/calendar/ics-faux.d.ts +3 -1
  22. package/dist/calendar/ics-faux.js +12 -2
  23. package/dist/calendar/tools.js +5 -2
  24. package/dist/chatgpt-plan.js +3 -1
  25. package/dist/claude-login.d.ts +135 -0
  26. package/dist/claude-login.js +244 -0
  27. package/dist/cli.js +62 -19
  28. package/dist/composio-preset.js +69 -7
  29. package/dist/composio-triggers.d.ts +14 -0
  30. package/dist/composio-triggers.js +79 -15
  31. package/dist/computer-attach.d.ts +40 -5
  32. package/dist/computer-attach.js +130 -15
  33. package/dist/computer-keys.d.ts +3 -0
  34. package/dist/computer-keys.js +7 -1
  35. package/dist/computer-live.js +3 -2
  36. package/dist/computers.d.ts +21 -10
  37. package/dist/computers.js +39 -28
  38. package/dist/console/assets/index-C2MYaUBa.css +1 -0
  39. package/dist/console/assets/index-CZZeCReB.js +701 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/decisions.d.ts +1 -1
  42. package/dist/dial-relay.d.ts +29 -0
  43. package/dist/dial-relay.js +94 -0
  44. package/dist/email/tools.js +10 -5
  45. package/dist/env-proxy.d.ts +2 -0
  46. package/dist/env-proxy.js +35 -0
  47. package/dist/errors.d.ts +3 -1
  48. package/dist/errors.js +7 -4
  49. package/dist/faux-computers.d.ts +8 -2
  50. package/dist/faux-computers.js +83 -6
  51. package/dist/harness-archive.d.ts +67 -0
  52. package/dist/harness-archive.js +177 -0
  53. package/dist/harness-goose.d.ts +34 -0
  54. package/dist/harness-goose.js +87 -0
  55. package/dist/harness-install.d.ts +21 -0
  56. package/dist/harness-install.js +24 -11
  57. package/dist/harness-opencode/adapter.js +1 -1
  58. package/dist/harness-table.d.ts +9 -1
  59. package/dist/harness-table.js +20 -3
  60. package/dist/harness.d.ts +1 -2
  61. package/dist/harness.js +3 -4
  62. package/dist/host.js +2 -1
  63. package/dist/import.d.ts +10 -0
  64. package/dist/import.js +28 -8
  65. package/dist/key-check.js +3 -0
  66. package/dist/learn/audit.d.ts +6 -6
  67. package/dist/learn/audit.js +3 -7
  68. package/dist/learn/check.d.ts +23 -89
  69. package/dist/learn/check.js +57 -335
  70. package/dist/learn/commit.d.ts +63 -90
  71. package/dist/learn/commit.js +124 -316
  72. package/dist/learn/compile.d.ts +53 -50
  73. package/dist/learn/compile.js +89 -104
  74. package/dist/learn/corrections.d.ts +13 -0
  75. package/dist/learn/corrections.js +23 -0
  76. package/dist/learn/delete.d.ts +5 -5
  77. package/dist/learn/delete.js +8 -10
  78. package/dist/learn/folder.d.ts +35 -47
  79. package/dist/learn/folder.js +118 -134
  80. package/dist/learn/index.d.ts +3 -5
  81. package/dist/learn/index.js +6 -9
  82. package/dist/learn/learning.sh +45 -15
  83. package/dist/learn/promote.d.ts +23 -5
  84. package/dist/learn/promote.js +40 -2
  85. package/dist/learn/{skills.d.ts → workflow-draft.d.ts} +30 -38
  86. package/dist/learn/{skills.js → workflow-draft.js} +48 -58
  87. package/dist/learn/workflow-nodes.js +1 -1
  88. package/dist/learned-workflow.js +2 -2
  89. package/dist/learning-cost.d.ts +38 -24
  90. package/dist/learning-cost.js +41 -24
  91. package/dist/learning-routes.d.ts +91 -170
  92. package/dist/learning-routes.js +183 -421
  93. package/dist/learning-run.d.ts +19 -40
  94. package/dist/learning-run.js +23 -93
  95. package/dist/learning-setting.d.ts +21 -10
  96. package/dist/learning-setting.js +47 -11
  97. package/dist/learning-words.d.ts +28 -74
  98. package/dist/learning-words.js +64 -162
  99. package/dist/learning.d.ts +61 -392
  100. package/dist/learning.js +101 -651
  101. package/dist/live-reach.d.ts +25 -2
  102. package/dist/live-reach.js +46 -4
  103. package/dist/llms.txt +1 -1
  104. package/dist/local-models.d.ts +3 -11
  105. package/dist/local-models.js +5 -6
  106. package/dist/mcp-servers-store.d.ts +4 -4
  107. package/dist/model-form.js +6 -5
  108. package/dist/model.d.ts +4 -0
  109. package/dist/model.js +26 -9
  110. package/dist/native/binding.js +1 -1
  111. package/dist/native/connection.js +1 -1
  112. package/dist/native/discovery.js +1 -1
  113. package/dist/native/instructions.d.ts +3 -0
  114. package/dist/native/instructions.js +5 -3
  115. package/dist/native/remote-worker-bridge.js +9 -43
  116. package/dist/native/remote.d.ts +8 -15
  117. package/dist/native/remote.js +3 -3
  118. package/dist/native/schema.js +1 -1
  119. package/dist/native/types.d.ts +2 -2
  120. package/dist/openapi.js +273 -319
  121. package/dist/paid-calls.d.ts +8 -0
  122. package/dist/paid-calls.js +20 -0
  123. package/dist/particle-provider.d.ts +11 -0
  124. package/dist/particle-provider.js +135 -0
  125. package/dist/port-models.d.ts +12 -4
  126. package/dist/port-models.js +28 -11
  127. package/dist/print.d.ts +27 -0
  128. package/dist/print.js +21 -0
  129. package/dist/provider.d.ts +7 -0
  130. package/dist/provider.js +15 -1
  131. package/dist/reflect-range.js +2 -3
  132. package/dist/run-launch.d.ts +14 -28
  133. package/dist/run-launch.js +9 -12
  134. package/dist/run-learning-served.d.ts +15 -89
  135. package/dist/run-listing.d.ts +34 -0
  136. package/dist/run-listing.js +128 -0
  137. package/dist/run-model-key.js +1 -1
  138. package/dist/run-timeline-served.js +5 -3
  139. package/dist/run-trace.d.ts +97 -0
  140. package/dist/run-trace.js +253 -0
  141. package/dist/run-view.d.ts +15 -0
  142. package/dist/run-view.js +9 -0
  143. package/dist/runnable.js +2 -1
  144. package/dist/runner/adapter-loop.d.ts +8 -6
  145. package/dist/runner/adapter-loop.js +16 -12
  146. package/dist/runner/adapter-run-spec.d.ts +16 -4
  147. package/dist/runner/adapter-run-spec.js +64 -58
  148. package/dist/runner/adapters/index.js +22 -0
  149. package/dist/runner/adapters/pi.d.ts +4 -12
  150. package/dist/runner/adapters/pi.js +2 -2
  151. package/dist/runner/audit.d.ts +1 -1
  152. package/dist/runner/audit.js +30 -13
  153. package/dist/runner/beside.d.ts +6 -2
  154. package/dist/runner/beside.js +38 -9
  155. package/dist/runner/claim-secrets.d.ts +18 -2
  156. package/dist/runner/claim-secrets.js +42 -18
  157. package/dist/runner/cli-run-spec.js +55 -51
  158. package/dist/runner/conformance/harness.d.ts +6 -0
  159. package/dist/runner/conformance/harness.js +35 -13
  160. package/dist/runner/conformance/subject.d.ts +6 -0
  161. package/dist/runner/dispatch.d.ts +2 -2
  162. package/dist/runner/end-of-run.d.ts +6 -14
  163. package/dist/runner/end-of-run.js +8 -33
  164. package/dist/runner/feedback-round.d.ts +2 -2
  165. package/dist/runner/feedback-round.js +7 -7
  166. package/dist/runner/github-app.js +3 -1
  167. package/dist/runner/harness-loops.d.ts +0 -8
  168. package/dist/runner/harness-loops.js +11 -59
  169. package/dist/runner/held.d.ts +170 -0
  170. package/dist/runner/held.js +57 -0
  171. package/dist/runner/journal-kinds.d.ts +2 -3
  172. package/dist/runner/journal-kinds.js +2 -3
  173. package/dist/runner/learned-first.d.ts +40 -0
  174. package/dist/runner/learned-first.js +32 -0
  175. package/dist/runner/learning-end.d.ts +77 -69
  176. package/dist/runner/learning-end.js +250 -303
  177. package/dist/runner/learning-seed.d.ts +15 -33
  178. package/dist/runner/learning-seed.js +24 -45
  179. package/dist/runner/loop-contract.d.ts +2 -3
  180. package/dist/runner/main.d.ts +17 -9
  181. package/dist/runner/main.js +82 -20
  182. package/dist/runner/mcp-run.d.ts +11 -0
  183. package/dist/runner/mcp-run.js +67 -0
  184. package/dist/runner/memory-claim.d.ts +10 -5
  185. package/dist/runner/memory-claim.js +12 -6
  186. package/dist/runner/model-route.d.ts +7 -4
  187. package/dist/runner/model-route.js +22 -10
  188. package/dist/runner/native-loop.d.ts +0 -7
  189. package/dist/runner/native-loop.js +9 -101
  190. package/dist/runner/promotion.d.ts +12 -8
  191. package/dist/runner/promotion.js +37 -28
  192. package/dist/runner/reflect-hook.d.ts +64 -95
  193. package/dist/runner/reflect-hook.js +112 -225
  194. package/dist/runner/run-channel.d.ts +43 -0
  195. package/dist/runner/run-channel.js +467 -0
  196. package/dist/runner/run-child-host.d.ts +169 -0
  197. package/dist/runner/run-child-host.js +1230 -0
  198. package/dist/runner/run-child.d.ts +1 -0
  199. package/dist/runner/run-child.js +254 -0
  200. package/dist/runner/run-errors.d.ts +2 -0
  201. package/dist/runner/run-errors.js +20 -0
  202. package/dist/runner/runner.js +1 -5
  203. package/dist/runner/sdk-ask.d.ts +78 -0
  204. package/dist/runner/sdk-ask.js +158 -0
  205. package/dist/runner/sdk-loop.d.ts +2 -4
  206. package/dist/runner/sdk-loop.js +29 -49
  207. package/dist/runner/store-secrets.d.ts +5 -3
  208. package/dist/runner/store-secrets.js +5 -1
  209. package/dist/runner/workflow-first.d.ts +5 -0
  210. package/dist/runner/workflow-first.js +4 -0
  211. package/dist/runner/workflow-spec.js +7 -2
  212. package/dist/runs-over-store.d.ts +16 -28
  213. package/dist/runs-over-store.js +31 -38
  214. package/dist/sdk/runs.d.ts +6 -11
  215. package/dist/sdk/runs.js +20 -41
  216. package/dist/sdk/schema.js +3 -4
  217. package/dist/seal-key.d.ts +5 -0
  218. package/dist/seal-key.js +7 -0
  219. package/dist/secrets.d.ts +3 -0
  220. package/dist/secrets.js +16 -3
  221. package/dist/server.d.ts +55 -33
  222. package/dist/server.js +689 -322
  223. package/dist/sign-ins-store.d.ts +8 -0
  224. package/dist/sign-ins-store.js +36 -1
  225. package/dist/skills.js +1 -1
  226. package/dist/store/index.d.ts +2 -2
  227. package/dist/store/index.js +1 -1
  228. package/dist/store/journal/storage.js +3 -0
  229. package/dist/store/postgres/migrations/0017_run_listing.sql +83 -0
  230. package/dist/store/postgres/migrations/0018_trigger_template.sql +6 -0
  231. package/dist/store/postgres/migrations/0019_runner_relays.sql +28 -0
  232. package/dist/store/schema.d.ts +53 -4
  233. package/dist/store/schema.js +137 -6
  234. package/dist/store/sqlite/connection.d.ts +2 -0
  235. package/dist/store/sqlite/connection.js +3 -1
  236. package/dist/store/sqlite/run-patch.d.ts +0 -17
  237. package/dist/store/sqlite/run-patch.js +4 -33
  238. package/dist/store/sqlite/store.js +246 -63
  239. package/dist/store/sqlite/worker.js +25 -0
  240. package/dist/store/store.d.ts +193 -36
  241. package/dist/store/store.js +25 -3
  242. package/dist/store-reads/learning.d.ts +102 -204
  243. package/dist/store-reads/learning.js +159 -321
  244. package/dist/store-reads/loop.d.ts +0 -1
  245. package/dist/store-reads/loop.js +1 -1
  246. package/dist/store-view.d.ts +29 -1
  247. package/dist/store-view.js +97 -31
  248. package/dist/template-eval.d.ts +3 -6
  249. package/dist/template-eval.js +22 -36
  250. package/dist/templates.d.ts +8 -4
  251. package/dist/templates.js +44 -6
  252. package/dist/timeline/index.d.ts +1 -1
  253. package/dist/timeline/index.js +1 -1
  254. package/dist/timeline/timeline.d.ts +5 -1
  255. package/dist/timeline/timeline.js +16 -0
  256. package/dist/tool-gate.d.ts +0 -7
  257. package/dist/tool-gate.js +1 -15
  258. package/dist/tool-keys-store.d.ts +1 -1
  259. package/dist/tool-keys.d.ts +6 -4
  260. package/dist/tool-keys.js +12 -6
  261. package/dist/tools.d.ts +2 -2
  262. package/dist/tools.js +11 -4
  263. package/dist/triggers.d.ts +65 -6
  264. package/dist/triggers.js +125 -19
  265. package/dist/validate.js +1 -1
  266. package/dist/webhooks.d.ts +7 -2
  267. package/dist/webhooks.js +12 -5
  268. package/dist/workspace/agent-computer.d.ts +2 -0
  269. package/dist/workspace/agent-computer.js +2 -0
  270. package/dist/workspace/archil-claim.d.ts +7 -0
  271. package/dist/workspace/archil-claim.js +29 -0
  272. package/dist/workspace/archil.d.ts +9 -1
  273. package/dist/workspace/archil.js +165 -3
  274. package/dist/workspace/attach.d.ts +3 -1
  275. package/dist/workspace/attach.js +2 -0
  276. package/dist/workspace/attached-computers.d.ts +16 -5
  277. package/dist/workspace/attached-computers.js +25 -9
  278. package/dist/workspace/computer-deps.js +1 -1
  279. package/dist/workspace/computer-for-claim.d.ts +7 -3
  280. package/dist/workspace/computer-for-claim.js +119 -22
  281. package/dist/workspace/computer-hold.js +2 -1
  282. package/dist/workspace/computer-kept.d.ts +11 -1
  283. package/dist/workspace/computer-kept.js +24 -3
  284. package/dist/workspace/resolve-computer.d.ts +33 -19
  285. package/dist/workspace/resolve-computer.js +172 -64
  286. package/dist/workspace/revision-skills.d.ts +1 -2
  287. package/dist/workspace/revision-skills.js +3 -4
  288. package/dist/workspace/run-workspace.d.ts +1 -1
  289. package/dist/workspace/run-workspace.js +5 -0
  290. package/dist/workspace/synced-folder.d.ts +85 -0
  291. package/dist/workspace/synced-folder.js +230 -0
  292. package/dist/workspace/workspace.d.ts +4 -0
  293. package/launcher/agentrun-serve +1 -1
  294. package/package.json +10 -10
  295. package/templates/README.md +8 -8
  296. package/templates/inbound-lead/agent.md +5 -4
  297. package/templates/inbound-lead/evals/learned-correction/case.yaml +3 -3
  298. package/templates/inbound-lead/evals/learned-correction/fixtures/corrections.md +1 -0
  299. package/templates/inbound-lead/evals/learned-correction/graders/applies-correction.md +22 -0
  300. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +1 -1
  301. package/templates/inbound-lead/evals/learned-correction/prompt.md +1 -1
  302. package/templates/inbound-lead/lead.schema.json +6 -5
  303. package/templates/inbound-lead/rules/RUBRIC.md +4 -4
  304. package/templates/inbound-lead/skills/lead/SKILL.md +4 -4
  305. package/templates/kyb/agent.md +2 -1
  306. package/templates/market-monitor/evals/learned-preference/case.yaml +4 -4
  307. package/templates/market-monitor/evals/learned-preference/fixtures/corrections.md +1 -0
  308. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +3 -3
  309. package/templates/market-monitor/evals/learned-preference/prompt.md +1 -1
  310. package/templates/release-notes/evals/learned-style/case.yaml +4 -4
  311. package/templates/release-notes/evals/learned-style/fixtures/corrections.md +1 -0
  312. package/templates/release-notes/evals/learned-style/graders/same-changes.md +2 -2
  313. package/templates/release-notes/evals/learned-style/prompt.md +1 -1
  314. package/dist/console/assets/index-BUktRvS-.css +0 -1
  315. package/dist/console/assets/index-nB9kTfIN.js +0 -711
  316. package/dist/learn/grade.d.ts +0 -138
  317. package/dist/learn/grade.js +0 -682
  318. package/dist/learn/notes.d.ts +0 -81
  319. package/dist/learn/notes.js +0 -178
  320. package/dist/learn/reflect.d.ts +0 -77
  321. package/dist/learn/reflect.js +0 -228
  322. package/dist/learn/relevance.d.ts +0 -24
  323. package/dist/learn/relevance.js +0 -91
  324. package/dist/learn/seed-check.d.ts +0 -74
  325. package/dist/learn/seed-check.js +0 -103
  326. package/dist/learning-batch.d.ts +0 -291
  327. package/dist/learning-batch.js +0 -600
  328. package/dist/learning-evals.d.ts +0 -35
  329. package/dist/learning-evals.js +0 -99
  330. package/dist/native/context.d.ts +0 -6
  331. package/dist/native/context.js +0 -22
  332. package/dist/propose.d.ts +0 -52
  333. package/dist/propose.js +0 -224
  334. package/dist/runner/learning-ask.d.ts +0 -47
  335. package/dist/runner/learning-ask.js +0 -128
  336. package/dist/runner/learning-dispatch.d.ts +0 -45
  337. package/dist/runner/learning-dispatch.js +0 -99
  338. package/dist/runner/learning-factory.d.ts +0 -16
  339. package/dist/runner/learning-factory.js +0 -50
  340. package/dist/runner/learning-loop.d.ts +0 -273
  341. package/dist/runner/learning-loop.js +0 -521
  342. package/dist/usage.d.ts +0 -11
  343. package/dist/usage.js +0 -11
  344. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +0 -1
  345. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +0 -14
  346. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +0 -21
  347. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +0 -1
  348. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +0 -8
  349. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +0 -1
  350. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +0 -13
@@ -85,6 +85,14 @@ export declare const GIVEN_BACK = "given back";
85
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
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
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;
88
96
  /** The run's one ledger the current call books on (Ledger.paid), when it has one: the runner's. */
89
97
  export declare const paidLedger: () => PaidBooking | undefined;
90
98
  /** Stops the run the current call books in, in `words`: handed to its pause (Ledger.pause) as a cap refusal no raise
@@ -104,6 +104,26 @@ let paidSeq = 0;
104
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
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
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
+ };
107
127
  /** The run's one ledger the current call books on (Ledger.paid), when it has one: the runner's. */
108
128
  export const paidLedger = () => ledgers.getStore()?.paid;
109
129
  /** Stops the run the current call books in, in `words`: handed to its pause (Ledger.pause) as a cap refusal no raise
@@ -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
+ }
@@ -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,15 @@ 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
+ }
62
72
  /** Whether `base` (a gatewayBase answer) is on the origin of serve's own gateway (AGENT_MODEL_BASE_URL): there a run's own
63
73
  * model key (run-model-key.ts) is sent, so the endpoint needs no standing key of the server's. */
64
74
  function onServeGateway(env, base) {
@@ -106,7 +116,7 @@ function openRouterKey(env, who, named) {
106
116
  }
107
117
  /** Serve's gateway (AGENT_MODEL_BASE_URL) on either wire: its base, its key (AGENT_MODEL_API_KEY, or none) as a bearer
108
118
  * token, the model id as model.ts chose it, priced as runModels prices it. */
109
- 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 });
110
120
  export function providerFor(wire, env, model, who) {
111
121
  const named = `${model.provider}/${model.modelId}`;
112
122
  if (wire === "anthropic-messages") {
@@ -121,6 +131,10 @@ export function providerFor(wire, env, model, who) {
121
131
  if (model.provider !== "anthropic")
122
132
  throw new HarnessUnavailable(`${who} runs Anthropic models; the run's model is ${named}.`);
123
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 };
124
138
  if (openRouterOnly(wire, env))
125
139
  return { origin: OPENROUTER_BASE, credential: openRouterKey(env, who, named), auth: "bearer", modelId: own, priceModel: { provider: "openrouter", modelId: `anthropic/${openRouterName(own)}` } };
126
140
  // The endpoint first: one it refuses is the reason, and no key would fix it (no `keys`). An endpoint the host names
@@ -1,6 +1,5 @@
1
1
  import { LEARNING_LABEL } from "./learning.js";
2
2
  import { said } from "./learning-words.js";
3
- import { askedForDryRun } from "./learn/reflect.js";
4
3
  import { askedForCompile } from "./learn/compile.js";
5
4
  /** The run asked its end-of-run turn and has not ended since. */
6
5
  export const reflecting = (run) => run.meta.reflect !== undefined && run.meta.reflect.until === undefined;
@@ -25,7 +24,7 @@ export function labelled(reflect, rows) {
25
24
  return rows.map((row) => (!reflects(reflect, row.id) ? row : {
26
25
  ...row, agent_label: LEARNING_LABEL,
27
26
  ...(row.kind === "final_answer" ? { kind: "text_block" } : {}),
28
- // The turn asked again for a draft whose dry run failed says so; every other message of the turn is its ask.
29
- ...(row.kind === "user_message" ? ((words) => ({ summary: words, text: words }))(askedForDryRun(row.text) ? said.askedDryRun : askedForCompile(row.text) === "again" ? said.askedCompileAgain : askedForCompile(row.text) ? said.askedCompile : said.asked) : {}),
27
+ // The compile turn's ask, or its ask again once the checks sent a draft back; any other message of the turn, its own.
28
+ ...(row.kind === "user_message" ? ((words) => ({ summary: words, text: words }))(askedForCompile(row.text) === "again" ? said.askedCompileAgain : askedForCompile(row.text) ? said.askedCompile : said.asked) : {}),
30
29
  }));
31
30
  }
@@ -7,9 +7,9 @@ import { type Json } from "./validate.js";
7
7
  import type { Place } from "./workspace/place.js";
8
8
  /** What a run is launched with: everything its runner needs to build the run's spec at its claim, nothing derived later.
9
9
  * The server writes it once at start; the runner reads it at each claim (its claim rebuilds the run from the store, this
10
- * body included). `harness` picks the loop's adapter (a built-in learning run names "learning"; absent, the revision's
11
- * harness is used); `input` is the start request's body for a person's or a trigger's run, or an object a built-in run
12
- * names (a learning run's `{ runId }`). `model`, `plane`, `approvers`, `documents` and `boxAllow` are the per-run choices
10
+ * body included). `harness` picks the loop's adapter (absent, the revision's harness is used); `input` is the start
11
+ * request's body for a person's or a trigger's run, or an object a built-in run names. `model`, `plane`, `approvers`,
12
+ * `documents` and `boxAllow` are the per-run choices
13
13
  * the old path recomputed; here they are pinned at start, and optional (a built-in run may name none). */
14
14
  export interface RunLaunch {
15
15
  readonly sdk?: {
@@ -27,7 +27,7 @@ export interface RunLaunch {
27
27
  * repository (run-repo.ts); a github trigger's run has none here, its event names it. */
28
28
  readonly repo?: string;
29
29
  readonly place: Place;
30
- /** The loop's adapter, when not the revision's: a built-in learning run names "learning". */
30
+ /** The loop's adapter, when not the revision's (an SDK run names "sdk"). */
31
31
  readonly harness?: string;
32
32
  /** The run's model, pinned at start. */
33
33
  readonly model?: {
@@ -51,33 +51,19 @@ export interface RunLaunch {
51
51
  * runner copies them into the run's work/inputs/ at its claim, as the old start copied them before the process ran. */
52
52
  readonly files?: readonly string[];
53
53
  /** The run's learning start, when its agent learns and the server's learning is on, decided once here so the runner reads
54
- * no learning folder or git: `given`, the notes its # Learned section names (each `{file, name}`, as /runs/{id}/learning
55
- * shows them); `seed`, the learning commit's sha (or null when the seed could not be read); and `section`, the exact
56
- * # Learned text to lay into the prompt for those notes (what the old layLearned laid), within the learning budget; and
57
- * `seedNotes`, the count of all notes in the seed before the budget picked `given` (present with a read seed; absent when
58
- * the seed could not be read); `notesLeftOut`, the files of the active notes the section names in no way, over the
59
- * learning budget, which its claim says in the run's log, absent when none; `skills`, the names of the learned skills the seed offers the run (each active one that
60
- * fits a run's skill budget at all; its claim lays them), absent when none; `workflows`, the names of the learned
61
- * workflows the seed offers its learned_workflow tool (chooseWorkflows), absent when none; `notesOnly`, a run of a
62
- * revision that says `learning: "notes"`: given its notes and skills but never a learned workflow, and asked for no
63
- * workflow draft at its end; `gradeModel`, the model the
64
- * server names to grade what the run proposes (learning.ts gradeModelOf: --grade-model, else AGENTRUN_SERVE_GRADE_MODEL,
65
- * else AGENT_MODEL_STRONG), absent when it names none and the agent's own grades it; and `seedFailed`, why it starts with
66
- * nothing learned when it does (SeedFailed); `use`, a run started with `learning: "use"` (learning.ts RUN_LEARNING_USE):
67
- * it starts from all of the above and keeps nothing, never asked its end-of-run turn. Absent when the run does not learn. */
54
+ * no learning folder or git: `seed`, the learning commit's sha (or null when the seed could not be read); `section`,
55
+ * the exact # Learned text to lay into the prompt (its owner's corrections, learning.ts learnedSection); `workflows`,
56
+ * the names of the learned workflows the seed offers the run (chooseWorkflows), absent when none; `noWorkflows`, a run
57
+ * never answered by a learned workflow and asked for no workflow draft at its end (a native run, an SDK run with no
58
+ * workflow binding); `model`, the model an SDK run's compile turn is asked on (its agent's own); `seedFailed`, why it
59
+ * starts with nothing learned when it does (SeedFailed); `use`, a run started with `learning: "use"` (learning.ts
60
+ * RUN_LEARNING_USE): it starts from all of the above and keeps nothing. Absent when the run does not learn. */
68
61
  readonly learning?: {
69
- readonly given: readonly {
70
- readonly file: string;
71
- readonly name: string;
72
- }[];
73
62
  readonly seed: string | null;
74
63
  readonly section: string;
75
- readonly seedNotes?: number;
76
- readonly notesLeftOut?: readonly string[];
77
- readonly skills?: readonly string[];
78
64
  readonly workflows?: readonly string[];
79
- readonly notesOnly?: true;
80
- readonly gradeModel?: string;
65
+ readonly noWorkflows?: true;
66
+ readonly model?: string;
81
67
  readonly seedFailed?: SeedFailed;
82
68
  readonly use?: true;
83
69
  };
@@ -129,7 +115,7 @@ export declare function launchBody(launch: RunLaunch): Json;
129
115
  /** A launch body read back into a `RunLaunch`, with the input-origin fail-safe applied through the body's own trigger, or
130
116
  * undefined when the body is not one (not an object, or it names no place: a damaged or hand-edited body). */
131
117
  export declare function readLaunchBody(stored: unknown): RunLaunch | undefined;
132
- /** The run's learning start (its given notes, its seed sha and its # Learned section), read from one place by learning's
118
+ /** The run's learning start (its seed sha, its # Learned section and its learned workflows), read from one place by learning's
133
119
  * routes and the runner; undefined when the run does not learn. */
134
120
  export declare const learningStartOf: (launch: RunLaunch) => RunLaunch["learning"];
135
121
  /** The same start read from a launch body's `learning` member alone (Store.runs.learningStarts), as readLaunchBody reads it. */
@@ -67,7 +67,7 @@ export function launchBody(launch) {
67
67
  ...(launch.boxAllow !== undefined ? { box_allow: launch.boxAllow } : {}),
68
68
  ...(launch.boxAllowSet ? { box_allow_set: true } : {}),
69
69
  ...(launch.files?.length ? { files: launch.files } : {}),
70
- ...(launch.learning ? { learning: { given: launch.learning.given.map((note) => ({ file: note.file, name: note.name })), seed: launch.learning.seed, section: launch.learning.section, ...(launch.learning.seedNotes !== undefined ? { seedNotes: launch.learning.seedNotes } : {}), ...(launch.learning.notesLeftOut?.length ? { notesLeftOut: [...launch.learning.notesLeftOut] } : {}), ...(launch.learning.skills?.length ? { skills: [...launch.learning.skills] } : {}), ...(launch.learning.notesOnly ? { notesOnly: true } : {}), ...(launch.learning.workflows?.length ? { workflows: [...launch.learning.workflows] } : {}), ...(launch.learning.gradeModel ? { gradeModel: launch.learning.gradeModel } : {}), ...(launch.learning.seedFailed ? { seedFailed: launch.learning.seedFailed } : {}), ...(launch.learning.use ? { use: true } : {}) } } : {}),
70
+ ...(launch.learning ? { learning: { seed: launch.learning.seed, section: launch.learning.section, ...(launch.learning.workflows?.length ? { workflows: [...launch.learning.workflows] } : {}), ...(launch.learning.noWorkflows ? { noWorkflows: true } : {}), ...(launch.learning.model ? { model: launch.learning.model } : {}), ...(launch.learning.seedFailed ? { seedFailed: launch.learning.seedFailed } : {}), ...(launch.learning.use ? { use: true } : {}) } } : {}),
71
71
  ...(launch.workflowFirst === false ? { workflow_first: false } : {}),
72
72
  ...(launch.replay ? { replay: { of: launch.replay.of, workflow: launch.replay.workflow, digest: launch.replay.digest } } : {}),
73
73
  ...(launch.audit ? { audit: { of: launch.audit.of, workflow: launch.audit.workflow, digest: launch.audit.digest } } : {}),
@@ -78,19 +78,16 @@ export function launchBody(launch) {
78
78
  ...(launch.hold ? { hold: { minutes: launch.hold.minutes } } : {}),
79
79
  };
80
80
  }
81
- /** The learning start a launch body names, as read back: its given notes (each {file, name}), its seed sha, its # Learned
82
- * section text, the learned skills and workflows it was offered, its grade model, why its seed failed and whether it only
83
- * uses them (`use`), or undefined
84
- * when the body names none (a run that does not learn). */
81
+ /** The learning start a launch body names, as read back: its seed sha, its # Learned section text, the learned workflows
82
+ * it was offered, its compile model, why its seed failed and whether it only uses them (`use`), or undefined when the
83
+ * body names none (a run that does not learn). */
85
84
  function readLearning(value) {
86
85
  if (!isObject(value))
87
86
  return undefined;
88
- const given = Array.isArray(value.given) ? value.given.flatMap((note) => (isObject(note) && typeof note.file === "string" && typeof note.name === "string" ? [{ file: note.file, name: note.name }] : [])) : [];
89
87
  const seed = typeof value.seed === "string" ? value.seed : null;
90
88
  const section = typeof value.section === "string" ? value.section : "";
91
- const names = (list) => (Array.isArray(list) ? list.filter((name) => typeof name === "string") : []);
92
- const [skills, workflows, notesLeftOut] = [names(value.skills), names(value.workflows), names(value.notesLeftOut)];
93
- return { given, seed, section, ...(typeof value.seedNotes === "number" ? { seedNotes: value.seedNotes } : {}), ...(notesLeftOut.length ? { notesLeftOut } : {}), ...(skills.length ? { skills } : {}), ...(workflows.length ? { workflows } : {}), ...(value.notesOnly === true ? { notesOnly: true } : {}), ...(typeof value.gradeModel === "string" && value.gradeModel !== "" ? { gradeModel: value.gradeModel } : {}), ...(typeof value.seedFailed === "string" && SEED_FAILURES.includes(value.seedFailed) ? { seedFailed: value.seedFailed } : {}), ...(value.use === true ? { use: true } : {}) };
89
+ const workflows = Array.isArray(value.workflows) ? value.workflows.filter((name) => typeof name === "string") : [];
90
+ return { seed, section, ...(workflows.length ? { workflows } : {}), ...(value.noWorkflows === true ? { noWorkflows: true } : {}), ...(typeof value.model === "string" && value.model !== "" ? { model: value.model } : {}), ...(typeof value.seedFailed === "string" && SEED_FAILURES.includes(value.seedFailed) ? { seedFailed: value.seedFailed } : {}), ...(value.use === true ? { use: true } : {}) };
94
91
  }
95
92
  /** A launch body read back into a `RunLaunch`, with the input-origin fail-safe applied through the body's own trigger, or
96
93
  * undefined when the body is not one (not an object, or it names no place: a damaged or hand-edited body). */
@@ -122,7 +119,7 @@ export function readLaunchBody(stored) {
122
119
  ...(boxAllow !== undefined ? { boxAllow } : {}),
123
120
  ...(stored.box_allow_set === true ? { boxAllowSet: true } : {}),
124
121
  ...(Array.isArray(stored.files) && stored.files.every((id) => typeof id === "string") ? { files: stored.files } : {}),
125
- ...(stored.learning !== undefined ? { learning: readLearning(stored.learning) ?? { given: [], seed: null, section: "" } } : {}),
122
+ ...(stored.learning !== undefined ? { learning: readLearning(stored.learning) ?? { seed: null, section: "" } } : {}),
126
123
  ...(stored.workflow_first === false ? { workflowFirst: false } : {}),
127
124
  ...(readReplay(stored.replay) ? { replay: readReplay(stored.replay) } : {}),
128
125
  ...(readReplay(stored.audit) ? { audit: readReplay(stored.audit) } : {}),
@@ -133,11 +130,11 @@ export function readLaunchBody(stored) {
133
130
  ...(isObject(stored.hold) && typeof stored.hold.minutes === "number" ? { hold: { minutes: stored.hold.minutes } } : {}),
134
131
  };
135
132
  }
136
- /** The run's learning start (its given notes, its seed sha and its # Learned section), read from one place by learning's
133
+ /** The run's learning start (its seed sha, its # Learned section and its learned workflows), read from one place by learning's
137
134
  * routes and the runner; undefined when the run does not learn. */
138
135
  export const learningStartOf = (launch) => launch.learning;
139
136
  /** The same start read from a launch body's `learning` member alone (Store.runs.learningStarts), as readLaunchBody reads it. */
140
- export const learningStartOfStored = (stored) => (stored === undefined ? undefined : readLearning(stored) ?? { given: [], seed: null, section: "" });
137
+ export const learningStartOfStored = (stored) => (stored === undefined ? undefined : readLearning(stored) ?? { seed: null, section: "" });
141
138
  const SEED_FAILURES = ["unreadable", "not_copied"];
142
139
  /** A learning start with no seed (no commit of main, runs-over-store.ts learningStartFor): the run learns nothing, is
143
140
  * never asked what to keep, and so is never told it learns. Why is its `seedFailed`, when its start records one. */