@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.59

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 (404) hide show
  1. package/CHANGELOG.md +376 -0
  2. package/README.md +393 -118
  3. package/dist/acp-package.d.ts +5 -1
  4. package/dist/acp-package.js +19 -2
  5. package/dist/adapters.d.ts +23 -2
  6. package/dist/adapters.js +106 -33
  7. package/dist/agents-store.js +1 -1
  8. package/dist/answer-text.d.ts +3 -0
  9. package/dist/answer-text.js +22 -0
  10. package/dist/api-only.d.ts +2 -4
  11. package/dist/api-only.js +2 -4
  12. package/dist/attach-conformance.js +5 -4
  13. package/dist/box-paths.d.ts +7 -5
  14. package/dist/box-paths.js +12 -8
  15. package/dist/browser-computer.d.ts +3 -8
  16. package/dist/browser-computer.js +12 -35
  17. package/dist/browser-cost.js +94 -20
  18. package/dist/capacity.d.ts +1 -1
  19. package/dist/capacity.js +3 -3
  20. package/dist/chatgpt-plan.d.ts +5 -0
  21. package/dist/chatgpt-plan.js +25 -11
  22. package/dist/claude-login-token.d.ts +121 -0
  23. package/dist/claude-login-token.js +797 -0
  24. package/dist/claude-login.d.ts +119 -34
  25. package/dist/claude-login.js +551 -79
  26. package/dist/claude-sign-in.d.ts +3 -0
  27. package/dist/claude-sign-in.js +10 -1
  28. package/dist/cli.js +325 -328
  29. package/dist/composio-made.d.ts +1 -6
  30. package/dist/composio-made.js +1 -6
  31. package/dist/composio-owners.d.ts +26 -0
  32. package/dist/composio-owners.js +36 -0
  33. package/dist/composio-preset.d.ts +56 -23
  34. package/dist/composio-preset.js +173 -77
  35. package/dist/composio-triggers.d.ts +4 -4
  36. package/dist/composio-triggers.js +6 -7
  37. package/dist/compute-cost.js +11 -2
  38. package/dist/computer-attach.d.ts +40 -19
  39. package/dist/computer-attach.js +326 -62
  40. package/dist/computer-held-routes.d.ts +1 -1
  41. package/dist/computer-held-routes.js +9 -4
  42. package/dist/computer-keys.d.ts +11 -1
  43. package/dist/computer-keys.js +26 -1
  44. package/dist/computer-record.js +3 -1
  45. package/dist/computer-view.d.ts +5 -3
  46. package/dist/computer-view.js +10 -6
  47. package/dist/computer-viewer.js +36 -7
  48. package/dist/computers.d.ts +12 -11
  49. package/dist/computers.js +11 -8
  50. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  51. package/dist/console/assets/backend-BztxEAvb.js +166 -0
  52. package/dist/console/assets/index-LwNL4L9q.js +619 -0
  53. package/dist/console/assets/share-L84tlUDW.js +6 -0
  54. package/dist/console/assets/styles-CaRKlHke.js +291 -0
  55. package/dist/console/assets/styles-DQo8rzY-.css +1 -0
  56. package/dist/console/index.html +4 -3
  57. package/dist/console/share.html +17 -0
  58. package/dist/decisions.d.ts +17 -7
  59. package/dist/decisions.js +41 -15
  60. package/dist/dial-relay.d.ts +25 -4
  61. package/dist/dial-relay.js +139 -5
  62. package/dist/docker-daemon.js +4 -5
  63. package/dist/docker-host-addresses.js +29 -11
  64. package/dist/email/account.d.ts +6 -0
  65. package/dist/email/account.js +6 -0
  66. package/dist/email/authentication.d.ts +21 -0
  67. package/dist/email/authentication.js +106 -0
  68. package/dist/email/email-faux.d.ts +11 -2
  69. package/dist/email/email-faux.js +21 -5
  70. package/dist/email/mail.d.ts +25 -0
  71. package/dist/email/mail.js +58 -2
  72. package/dist/email/names.js +2 -2
  73. package/dist/email/tools.d.ts +9 -4
  74. package/dist/email/tools.js +95 -13
  75. package/dist/env-switch.d.ts +13 -5
  76. package/dist/env-switch.js +24 -6
  77. package/dist/errors.d.ts +1 -0
  78. package/dist/errors.js +2 -0
  79. package/dist/fal-price.d.ts +12 -4
  80. package/dist/fal-price.js +110 -26
  81. package/dist/faux-computers.js +1 -1
  82. package/dist/filed-answer.d.ts +2 -2
  83. package/dist/filed-answer.js +2 -2
  84. package/dist/graph-served.d.ts +10 -5
  85. package/dist/graph-served.js +40 -10
  86. package/dist/handed-values.js +1 -2
  87. package/dist/harness-check.d.ts +2 -1
  88. package/dist/harness-check.js +45 -12
  89. package/dist/harness-keys.js +9 -6
  90. package/dist/harness-opencode/facts.js +2 -0
  91. package/dist/harness-recipe-entry.d.ts +9 -3
  92. package/dist/harness-recipe-entry.js +18 -9
  93. package/dist/harness-recipe.d.ts +21 -0
  94. package/dist/harness-recipe.js +25 -3
  95. package/dist/harness-table.d.ts +8 -0
  96. package/dist/harness-table.js +17 -6
  97. package/dist/helper-env.d.ts +4 -1
  98. package/dist/helper-env.js +4 -1
  99. package/dist/host-check.d.ts +2 -3
  100. package/dist/host-check.js +13 -7
  101. package/dist/hosted-search.js +1 -1
  102. package/dist/import.d.ts +11 -8
  103. package/dist/import.js +437 -186
  104. package/dist/key-refusal.d.ts +9 -2
  105. package/dist/key-refusal.js +86 -32
  106. package/dist/learn/audit.d.ts +8 -5
  107. package/dist/learn/audit.js +15 -7
  108. package/dist/learn/compile.d.ts +5 -2
  109. package/dist/learn/compile.js +45 -21
  110. package/dist/learn/field-check.d.ts +111 -0
  111. package/dist/learn/field-check.js +174 -0
  112. package/dist/learn/ledger.d.ts +173 -0
  113. package/dist/learn/ledger.js +225 -0
  114. package/dist/learn/promote.d.ts +82 -39
  115. package/dist/learn/promote.js +61 -66
  116. package/dist/learn/secrets.d.ts +4 -0
  117. package/dist/learn/secrets.js +12 -0
  118. package/dist/learned-nodes.d.ts +8 -5
  119. package/dist/learned-nodes.js +8 -5
  120. package/dist/learned-workflow.d.ts +2 -1
  121. package/dist/learned-workflow.js +13 -10
  122. package/dist/learning-cost.d.ts +40 -21
  123. package/dist/learning-cost.js +30 -21
  124. package/dist/learning-setting.d.ts +6 -0
  125. package/dist/learning-setting.js +11 -1
  126. package/dist/listen-first.d.ts +5 -4
  127. package/dist/listen-first.js +4 -5
  128. package/dist/live-reach.d.ts +9 -0
  129. package/dist/live-reach.js +9 -0
  130. package/dist/mcp-api-only-origins.d.ts +23 -3
  131. package/dist/mcp-api-only-origins.js +57 -17
  132. package/dist/mcp-gateway.d.ts +16 -2
  133. package/dist/mcp-gateway.js +41 -3
  134. package/dist/mcp-oauth.d.ts +1 -1
  135. package/dist/mcp-oauth.js +3 -2
  136. package/dist/mcp-probe.d.ts +3 -0
  137. package/dist/mcp-probe.js +3 -0
  138. package/dist/mcp-secret-writes.d.ts +24 -2
  139. package/dist/mcp-secret-writes.js +30 -2
  140. package/dist/mcp-servers-store.d.ts +52 -14
  141. package/dist/mcp-servers-store.js +165 -61
  142. package/dist/mcp-sources.d.ts +1 -2
  143. package/dist/mcp-sources.js +1 -2
  144. package/dist/mcp-store.d.ts +5 -5
  145. package/dist/mcp-store.js +3 -3
  146. package/dist/mcp.js +1 -1
  147. package/dist/micro.d.ts +2 -0
  148. package/dist/micro.js +2 -0
  149. package/dist/model-gateway.d.ts +1 -1
  150. package/dist/model-gateway.js +20 -36
  151. package/dist/model.d.ts +5 -4
  152. package/dist/model.js +7 -6
  153. package/dist/monid.d.ts +14 -1
  154. package/dist/monid.js +103 -26
  155. package/dist/ollama-provider.d.ts +23 -9
  156. package/dist/ollama-provider.js +49 -20
  157. package/dist/openapi.js +234 -61
  158. package/dist/otel/genai.d.ts +83 -7
  159. package/dist/otel/genai.js +69 -9
  160. package/dist/otel/tracer.d.ts +42 -13
  161. package/dist/otel/tracer.js +241 -56
  162. package/dist/page.d.ts +7 -1
  163. package/dist/page.js +76 -22
  164. package/dist/paid-calls.d.ts +6 -4
  165. package/dist/paid-calls.js +15 -7
  166. package/dist/place-offers.d.ts +59 -34
  167. package/dist/place-offers.js +100 -58
  168. package/dist/place.d.ts +13 -14
  169. package/dist/place.js +56 -41
  170. package/dist/print.js +1 -1
  171. package/dist/provider.d.ts +5 -4
  172. package/dist/provider.js +26 -13
  173. package/dist/redact/match.d.ts +27 -9
  174. package/dist/redact/match.js +266 -57
  175. package/dist/run-census.d.ts +1 -1
  176. package/dist/run-census.js +4 -5
  177. package/dist/run-cut.js +4 -5
  178. package/dist/run-export-store.d.ts +15 -0
  179. package/dist/run-export-store.js +30 -0
  180. package/dist/run-export.d.ts +139 -0
  181. package/dist/run-export.js +379 -0
  182. package/dist/run-file-cut.d.ts +5 -0
  183. package/dist/run-file-cut.js +13 -0
  184. package/dist/run-launch.js +16 -3
  185. package/dist/run-learning-served.d.ts +2 -2
  186. package/dist/run-model-key.d.ts +15 -6
  187. package/dist/run-model-key.js +30 -31
  188. package/dist/run-reads-over-store.js +4 -4
  189. package/dist/run-secrets.js +3 -5
  190. package/dist/run-timeline-served.js +3 -1
  191. package/dist/run-view.d.ts +1 -2
  192. package/dist/run-view.js +2 -1
  193. package/dist/runnable.js +2 -2
  194. package/dist/runner/adapter-loop.d.ts +35 -18
  195. package/dist/runner/adapter-loop.js +97 -63
  196. package/dist/runner/adapter-run-spec.d.ts +34 -14
  197. package/dist/runner/adapter-run-spec.js +120 -75
  198. package/dist/runner/adapters/pi.js +4 -2
  199. package/dist/runner/audit.d.ts +8 -5
  200. package/dist/runner/audit.js +37 -17
  201. package/dist/runner/beside.d.ts +9 -2
  202. package/dist/runner/beside.js +29 -13
  203. package/dist/runner/claim-secrets.d.ts +27 -18
  204. package/dist/runner/claim-secrets.js +61 -47
  205. package/dist/runner/cli-run-spec.d.ts +18 -0
  206. package/dist/runner/cli-run-spec.js +93 -46
  207. package/dist/runner/compare-end.d.ts +2 -1
  208. package/dist/runner/compare-end.js +25 -10
  209. package/dist/runner/conformance/harness.js +2 -3
  210. package/dist/runner/conformance/subject.d.ts +4 -1
  211. package/dist/runner/harness-loops.js +3 -3
  212. package/dist/runner/held.d.ts +19 -4
  213. package/dist/runner/journal-kinds.d.ts +4 -1
  214. package/dist/runner/journal-kinds.js +22 -4
  215. package/dist/runner/learned-first.js +20 -4
  216. package/dist/runner/learning-end.d.ts +2 -8
  217. package/dist/runner/learning-end.js +11 -19
  218. package/dist/runner/live-ticker.js +7 -5
  219. package/dist/runner/loop-contract.d.ts +0 -2
  220. package/dist/runner/loop.d.ts +7 -0
  221. package/dist/runner/loop.js +1 -0
  222. package/dist/runner/main.d.ts +11 -6
  223. package/dist/runner/main.js +24 -18
  224. package/dist/runner/mcp-claim.js +24 -7
  225. package/dist/runner/mcp-run.d.ts +3 -6
  226. package/dist/runner/mcp-run.js +3 -4
  227. package/dist/runner/meta-tools.js +3 -2
  228. package/dist/runner/metrics.d.ts +7 -0
  229. package/dist/runner/metrics.js +19 -0
  230. package/dist/runner/model-route.d.ts +10 -7
  231. package/dist/runner/model-route.js +79 -15
  232. package/dist/runner/native-loop.js +10 -8
  233. package/dist/runner/presence.d.ts +11 -4
  234. package/dist/runner/presence.js +11 -6
  235. package/dist/runner/promotion.d.ts +25 -13
  236. package/dist/runner/promotion.js +125 -50
  237. package/dist/runner/redact.d.ts +3 -1
  238. package/dist/runner/redact.js +5 -3
  239. package/dist/runner/reflect-hook.js +1 -1
  240. package/dist/runner/responses-fetch.d.ts +36 -0
  241. package/dist/runner/responses-fetch.js +511 -0
  242. package/dist/runner/run-child-host.d.ts +38 -12
  243. package/dist/runner/run-child-host.js +231 -83
  244. package/dist/runner/run-child.js +11 -4
  245. package/dist/runner/runner-check.js +5 -1
  246. package/dist/runner/runner.d.ts +5 -3
  247. package/dist/runner/runner.js +14 -10
  248. package/dist/runner/save-slots.js +2 -1
  249. package/dist/runner/sdk-loop.js +8 -8
  250. package/dist/runner/spec-holds.d.ts +8 -1
  251. package/dist/runner/spec-holds.js +9 -4
  252. package/dist/runner/subagent.d.ts +11 -0
  253. package/dist/runner/subagent.js +17 -3
  254. package/dist/runner/workflow-calls.d.ts +9 -0
  255. package/dist/runner/workflow-calls.js +150 -0
  256. package/dist/runner/workflow-first.d.ts +138 -37
  257. package/dist/runner/workflow-first.js +230 -99
  258. package/dist/runner/workflow-spec.js +2 -2
  259. package/dist/runs-over-store.js +8 -7
  260. package/dist/save-once.d.ts +14 -0
  261. package/dist/save-once.js +31 -0
  262. package/dist/scrub-command.d.ts +34 -31
  263. package/dist/scrub-command.js +116 -147
  264. package/dist/sdk/runs.d.ts +6 -0
  265. package/dist/sdk/runs.js +89 -10
  266. package/dist/seal-key.js +4 -4
  267. package/dist/secret-cut.d.ts +3 -0
  268. package/dist/secret-cut.js +7 -1
  269. package/dist/secret-rules.d.ts +8 -1
  270. package/dist/secret-rules.js +482 -53
  271. package/dist/secrets.d.ts +51 -9
  272. package/dist/secrets.js +311 -21
  273. package/dist/server-keys.d.ts +4 -3
  274. package/dist/server-keys.js +4 -3
  275. package/dist/server-secrets-store.js +2 -4
  276. package/dist/server.d.ts +33 -10
  277. package/dist/server.js +454 -136
  278. package/dist/share-context.d.ts +22 -0
  279. package/dist/share-context.js +76 -0
  280. package/dist/shell-lex.d.ts +105 -0
  281. package/dist/shell-lex.js +646 -0
  282. package/dist/sign-ins-store.d.ts +5 -7
  283. package/dist/sign-ins-store.js +12 -16
  284. package/dist/sign-ins.d.ts +7 -11
  285. package/dist/sign-ins.js +40 -41
  286. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  287. package/dist/slots.d.ts +9 -0
  288. package/dist/slots.js +45 -0
  289. package/dist/start-switches.d.ts +6 -5
  290. package/dist/start-switches.js +8 -4
  291. package/dist/stats.d.ts +5 -1
  292. package/dist/stats.js +1 -1
  293. package/dist/store/agent-body.js +2 -2
  294. package/dist/store/dialect.d.ts +4 -0
  295. package/dist/store/dialect.js +1 -0
  296. package/dist/store/index.d.ts +2 -2
  297. package/dist/store/index.js +1 -1
  298. package/dist/store/mcp-record-keys.d.ts +10 -0
  299. package/dist/store/mcp-record-keys.js +13 -0
  300. package/dist/store/postgres/dialect.js +2 -0
  301. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  302. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  303. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  304. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  305. package/dist/store/postgres/store.js +4 -0
  306. package/dist/store/schema.d.ts +44 -4
  307. package/dist/store/schema.js +111 -11
  308. package/dist/store/seal.d.ts +4 -1
  309. package/dist/store/sqlite/run-launch.d.ts +3 -10
  310. package/dist/store/sqlite/run-launch.js +12 -23
  311. package/dist/store/sqlite/run-patch.d.ts +19 -2
  312. package/dist/store/sqlite/run-patch.js +67 -2
  313. package/dist/store/sqlite/store.d.ts +3 -0
  314. package/dist/store/sqlite/store.js +177 -32
  315. package/dist/store/store-schema.js +3 -4
  316. package/dist/store/store.d.ts +74 -25
  317. package/dist/store/store.js +14 -11
  318. package/dist/store-reads/analytics.d.ts +2 -1
  319. package/dist/store-reads/analytics.js +7 -5
  320. package/dist/store-reads/learning.d.ts +102 -136
  321. package/dist/store-reads/learning.js +251 -302
  322. package/dist/store-reads/stats.d.ts +2 -2
  323. package/dist/store-reads/stats.js +13 -7
  324. package/dist/store-view.js +10 -7
  325. package/dist/suggestions.d.ts +1 -1
  326. package/dist/suggestions.js +29 -13
  327. package/dist/template-eval.d.ts +91 -9
  328. package/dist/template-eval.js +448 -105
  329. package/dist/template-import.d.ts +0 -10
  330. package/dist/template-import.js +5 -10
  331. package/dist/timeline/labels.d.ts +1 -1
  332. package/dist/timeline/labels.js +4 -3
  333. package/dist/timeline/timeline.d.ts +23 -11
  334. package/dist/timeline/timeline.js +115 -31
  335. package/dist/timeline/web-calls.d.ts +14 -14
  336. package/dist/timeline/web-calls.js +18 -30
  337. package/dist/tool-gate.d.ts +13 -1
  338. package/dist/tool-gate.js +43 -3
  339. package/dist/tool-keys-store.js +2 -4
  340. package/dist/tool-keys.d.ts +11 -0
  341. package/dist/tool-keys.js +16 -0
  342. package/dist/tool-plane.d.ts +50 -11
  343. package/dist/tool-plane.js +94 -30
  344. package/dist/tools.d.ts +5 -1
  345. package/dist/tools.js +7 -7
  346. package/dist/trigger-email.js +12 -6
  347. package/dist/triggers.d.ts +15 -34
  348. package/dist/triggers.js +119 -126
  349. package/dist/validate.d.ts +8 -1
  350. package/dist/validate.js +163 -23
  351. package/dist/web-fake.d.ts +2 -1
  352. package/dist/web-fake.js +8 -6
  353. package/dist/web-fetch.d.ts +8 -6
  354. package/dist/web-fetch.js +13 -11
  355. package/dist/web-holds.d.ts +32 -0
  356. package/dist/web-holds.js +86 -0
  357. package/dist/web-run.d.ts +32 -5
  358. package/dist/web-run.js +75 -28
  359. package/dist/web-save.d.ts +4 -9
  360. package/dist/web-save.js +27 -55
  361. package/dist/web-search.js +14 -25
  362. package/dist/wires.d.ts +4 -3
  363. package/dist/wires.js +5 -4
  364. package/dist/workspace/archil-claim.d.ts +12 -5
  365. package/dist/workspace/archil-claim.js +45 -5
  366. package/dist/workspace/attach.js +52 -19
  367. package/dist/workspace/attached-computers.d.ts +38 -11
  368. package/dist/workspace/attached-computers.js +81 -16
  369. package/dist/workspace/computer-deps.d.ts +29 -7
  370. package/dist/workspace/computer-deps.js +36 -18
  371. package/dist/workspace/computer-for-claim.d.ts +21 -4
  372. package/dist/workspace/computer-for-claim.js +166 -57
  373. package/dist/workspace/computer-intervals.d.ts +2 -0
  374. package/dist/workspace/computer-intervals.js +1 -1
  375. package/dist/workspace/computer-janitor.d.ts +48 -14
  376. package/dist/workspace/computer-janitor.js +153 -44
  377. package/dist/workspace/computer-kept.d.ts +158 -32
  378. package/dist/workspace/computer-kept.js +288 -63
  379. package/dist/workspace/computer-providers.d.ts +8 -3
  380. package/dist/workspace/computer-providers.js +12 -5
  381. package/dist/workspace/index.d.ts +1 -1
  382. package/dist/workspace/index.js +1 -1
  383. package/dist/workspace/local.js +41 -1
  384. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  385. package/dist/workspace/mount-revoke-left.js +72 -0
  386. package/dist/workspace/paired-route.d.ts +91 -0
  387. package/dist/workspace/paired-route.js +152 -0
  388. package/dist/workspace/resolve-computer.d.ts +5 -2
  389. package/dist/workspace/resolve-computer.js +9 -3
  390. package/dist/workspace/run-end-computers.d.ts +11 -5
  391. package/dist/workspace/run-end-computers.js +153 -28
  392. package/dist/workspace/run-tools.d.ts +22 -3
  393. package/dist/workspace/run-tools.js +17 -5
  394. package/dist/workspace/run-workspace.d.ts +14 -1
  395. package/dist/workspace/run-workspace.js +34 -1
  396. package/dist/workspace/workspace.d.ts +6 -0
  397. package/dist/wrapped.d.ts +8 -2
  398. package/dist/wrapped.js +21 -6
  399. package/package.json +12 -13
  400. package/skills/agentrun-serve/SKILL.md +5 -2
  401. package/templates/README.md +25 -9
  402. package/dist/console/assets/backend-DVhHzJX2.js +0 -166
  403. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  404. package/dist/console/assets/index-okP-y8PK.js +0 -747
@@ -28,7 +28,8 @@
28
28
  // it on only with an address of that origin. The address row and the key row are written one after the other, and a
29
29
  // runner in another process may read them between the two writes, or after a write that failed: a pair that does not
30
30
  // match is read as a gateway with no key, so a key never goes to an address it was not saved for.
31
- import { gatewayBase, HarnessUnavailable } from "./provider.js";
31
+ import { textUpTo } from "./answer-text.js";
32
+ import { gatewayBase, HarnessUnavailable, modelGatewayBase } from "./provider.js";
32
33
  import { ApiError, invalid } from "./errors.js";
33
34
  import { envValue } from "./key-meta.js";
34
35
  import { GATEWAY_KEY_ENV, TIERS } from "./model.js";
@@ -166,10 +167,11 @@ export function withSavedGateway(env, saved) {
166
167
  }
167
168
  /** The variables of the gateway's fields that the environment sets. */
168
169
  const setAtStart = (env) => [BASE_VAR, IDS_VAR, ...TIERS.map((tier) => TIER_VARS[tier]), GATEWAY_KEY_ENV].filter((name) => envValue(env, name) !== undefined);
169
- /** Why `value` may not be the gateway's address (gatewayBase's one rule, under the field's name), or undefined. */
170
- function baseProblem(field, value) {
170
+ /** Why `value` may not be the gateway's address, under the field's name, or undefined: by `rule`, the one address rule
171
+ * (gatewayBase) unless given another. */
172
+ function baseProblem(field, value, rule = gatewayBase) {
171
173
  try {
172
- gatewayBase(field, value);
174
+ rule(field, value);
173
175
  return undefined;
174
176
  }
175
177
  catch (error) {
@@ -178,6 +180,11 @@ function baseProblem(field, value) {
178
180
  throw error;
179
181
  }
180
182
  }
183
+ /** The rule a run holds the gateway to (modelGatewayBase: the address rule, and an API that is no gateway's, Particle's). */
184
+ const runRule = (field, value) => modelGatewayBase(value, field);
185
+ /** Why a run refuses `value` as the gateway, in a run's words, or null: the view's `problem`, which the console's first
186
+ * screen shows, and what a save refuses. */
187
+ const runProblem = (field, value) => baseProblem(field, value, runRule) ?? null;
181
188
  const originOf = (base) => new URL(gatewayBase("base_url", base)).origin;
182
189
  export async function gatewayView({ store, env }) {
183
190
  const set_at_start = setAtStart(env);
@@ -191,7 +198,7 @@ export async function gatewayView({ store, env }) {
191
198
  models: Object.fromEntries(TIERS.map((tier) => [tier, envValue(env, TIER_VARS[tier]) ?? null])),
192
199
  set_at_start,
193
200
  secret: secretMeta(GATEWAY_SECRET, key ? { set: true, source: "env", changedAt: null } : { set: false }),
194
- problem: baseProblem(BASE_VAR, base) ?? null,
201
+ problem: runProblem(BASE_VAR, base),
195
202
  };
196
203
  }
197
204
  const saved = await gatewaySettingOf(store.settings);
@@ -205,7 +212,7 @@ export async function gatewayView({ store, env }) {
205
212
  models: Object.fromEntries(TIERS.map((tier) => [tier, envValue(env, TIER_VARS[tier]) ?? saved?.models[tier] ?? null])),
206
213
  set_at_start,
207
214
  secret,
208
- problem: saved ? (baseProblem("base_url", saved.base_url) ?? null) : null,
215
+ problem: saved ? runProblem("base_url", saved.base_url) : null,
209
216
  };
210
217
  }
211
218
  /** 409 while the environment names its own gateway: nothing saved here would take effect. */
@@ -233,7 +240,8 @@ export async function saveGateway(deps, body) {
233
240
  if (base === undefined || !base)
234
241
  issues.push({ field: "base_url", reason: body.base_url === undefined ? "missing" : "wrong_type", message: "base_url is the gateway's address, such as https://gateway.example/v1" });
235
242
  else {
236
- const problem = baseProblem("base_url", base);
243
+ // A run's rule, so nothing is saved that no run could use.
244
+ const problem = runProblem("base_url", base);
237
245
  if (problem)
238
246
  issues.push({ field: "base_url", reason: "invalid", message: problem });
239
247
  }
@@ -309,7 +317,7 @@ export async function testGateway(deps, body, signal) {
309
317
  if (given.base_url !== undefined && (typeof given.base_url !== "string" || !given.base_url.trim()))
310
318
  issues.push({ field: "base_url", reason: "wrong_type", message: "base_url is the gateway's address as text" });
311
319
  else if (typeof given.base_url === "string") {
312
- const problem = baseProblem("base_url", given.base_url.trim());
320
+ const problem = runProblem("base_url", given.base_url.trim());
313
321
  if (problem)
314
322
  issues.push({ field: "base_url", reason: "invalid", message: problem });
315
323
  }
@@ -329,7 +337,8 @@ export async function testGateway(deps, body, signal) {
329
337
  if (base === undefined)
330
338
  return { ok: false, why: "No model gateway is saved here: enter its address to test it." };
331
339
  const field = typeof given.base_url === "string" ? "base_url" : inForce.field;
332
- const problem = baseProblem(field, base);
340
+ // A run's rule, as Save's: an address no run could use is said so, and never asked.
341
+ const problem = runProblem(field, base);
333
342
  if (problem)
334
343
  return { ok: false, why: problem };
335
344
  const root = gatewayBase(field, base);
@@ -358,7 +367,8 @@ async function listModels(root, key, fetcher, signal) {
358
367
  await answer.body?.cancel();
359
368
  return { ok: false, why: `The gateway answered GET ${url} with a redirect (${answer.status}), and AgentRun follows none: a key goes only to the address you give. Use the address it redirects to.` };
360
369
  }
361
- const read = await textUpTo(answer, MAX_TEST_BYTES);
370
+ // A body that breaks off is read as none: the checks below say what that answer was.
371
+ const read = await textUpTo(answer, MAX_TEST_BYTES).catch(() => "");
362
372
  if (read === undefined)
363
373
  return { ok: false, why: `The gateway's answer to GET ${url} is over ${MAX_TEST_BYTES / (1024 * 1024)} MB, more than a list of models: is this an OpenAI-compatible gateway's address?` };
364
374
  const text = read;
@@ -380,32 +390,6 @@ async function listModels(root, key, fetcher, signal) {
380
390
  const ids = [...new Set(data.flatMap((entry) => (isObject(entry) && typeof entry.id === "string" && !idIssue(entry.id) && !(key && entry.id.includes(key)) ? [entry.id] : [])))].slice(0, MAX_LISTED);
381
391
  return { ok: true, models: ids };
382
392
  }
383
- /** `answer`'s body as text, read up to `max` bytes; undefined once it is longer (the rest is cancelled, never read), and
384
- * "" for a body that could not be read. */
385
- async function textUpTo(answer, max) {
386
- const reader = answer.body?.getReader();
387
- if (!reader)
388
- return "";
389
- const chunks = [];
390
- let size = 0;
391
- try {
392
- for (;;) {
393
- const { done, value } = await reader.read();
394
- if (done)
395
- break;
396
- size += value.byteLength;
397
- if (size > max) {
398
- await reader.cancel().catch(() => { });
399
- return undefined;
400
- }
401
- chunks.push(value);
402
- }
403
- }
404
- catch {
405
- return "";
406
- }
407
- return Buffer.concat(chunks).toString("utf8");
408
- }
409
393
  /** The gateway's own words after a refusal: its JSON's error message, else its text, short. */
410
394
  function detail(text, scrub) {
411
395
  let said = text;
package/dist/model.d.ts CHANGED
@@ -162,10 +162,11 @@ export declare const PROVIDER_KEYS: Readonly<Record<string, readonly string[]>>;
162
162
  /** The gateway's key (AGENT_MODEL_BASE_URL's), which its every model is reached on. */
163
163
  export declare const GATEWAY_KEY_ENV = "AGENT_MODEL_API_KEY";
164
164
  /** The model keys a pi run takes, by the models chooseModel picks for it: the keys of each one's provider (PROVIDER_KEYS),
165
- * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's the host's model
166
- * of that tier; through a gateway (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as
167
- * chooseModel is, faux or not, so a run on the faux model is handed what a run on its model would be. */
168
- export declare function modelKeys(env: NodeJS.ProcessEnv, ref: string | undefined, tiers?: readonly Tier[]): string[];
165
+ * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's from `tierRefs`
166
+ * (a revision's model_tiers, as runModels takes them) else the host's model of that tier; through a gateway
167
+ * (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as chooseModel is, faux or not, so a
168
+ * run on the faux model is handed what a run on its model would be. */
169
+ export declare function modelKeys(env: NodeJS.ProcessEnv, ref: string | undefined, tiers?: readonly Tier[], tierRefs?: Readonly<Partial<Record<Tier, string>>>): string[];
169
170
  /** `value` as a thinking level (THINKING_LEVELS, exactly), else undefined: a revision's `thinking` or the host's
170
171
  * `AGENT_THINKING` that names none is no level. A run's effort is its own, else these (runs-over-store.ts prepareLaunch). */
171
172
  export declare function thinkingLevel(value: unknown): ThinkingLevel | undefined;
package/dist/model.js CHANGED
@@ -188,7 +188,7 @@ export const MODEL_SOURCES = ["faux", "gateway", "providers", "chatgpt"];
188
188
  export function modelSource(env) {
189
189
  const each = (name) => Object.fromEntries(TIERS.map((tier) => [tier, name(tier)]));
190
190
  if (env[FAUX_ENV])
191
- return { source: "faux", route_prefix: null, ...each((tier) => `faux/${fauxModel(env, tier)}`) };
191
+ return { source: "faux", route_prefix: null, ...each((tier) => `${FAUX_PROVIDER}/${fauxModel(env, tier)}`) };
192
192
  if (env.AGENT_MODEL_BASE_URL)
193
193
  return { source: "gateway", route_prefix: MODEL_PROVIDER, ...each((tier) => (hostModel(env, tier) ? `${MODEL_PROVIDER}/${hostModel(env, tier)}` : null)) };
194
194
  if (signedIn(env) && !Object.values(PROVIDER_KEYS).flat().some((name) => env[name]))
@@ -397,13 +397,14 @@ const REQUEST_KEYS = PROVIDER_KEYS["amazon-bedrock"];
397
397
  /** The gateway's key (AGENT_MODEL_BASE_URL's), which its every model is reached on. */
398
398
  export const GATEWAY_KEY_ENV = "AGENT_MODEL_API_KEY";
399
399
  /** The model keys a pi run takes, by the models chooseModel picks for it: the keys of each one's provider (PROVIDER_KEYS),
400
- * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's the host's model
401
- * of that tier; through a gateway (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as
402
- * chooseModel is, faux or not, so a run on the faux model is handed what a run on its model would be. */
403
- export function modelKeys(env, ref, tiers = ["default"]) {
400
+ * the default tier's from `ref` (an agentic revision's own) else the host's default, each other tier's from `tierRefs`
401
+ * (a revision's model_tiers, as runModels takes them) else the host's model of that tier; through a gateway
402
+ * (`AGENT_MODEL_BASE_URL`), where every model is the gateway's, its key alone. Asked as chooseModel is, faux or not, so a
403
+ * run on the faux model is handed what a run on its model would be. */
404
+ export function modelKeys(env, ref, tiers = ["default"], tierRefs = {}) {
404
405
  if (env.AGENT_MODEL_BASE_URL)
405
406
  return [GATEWAY_KEY_ENV];
406
- const named = tiers.map((tier) => (tier === "default" ? ref : undefined) ?? hostModel(env, tier));
407
+ const named = tiers.map((tier) => (tier === "default" ? ref : tierRefs[tier]) ?? hostModel(env, tier));
407
408
  const providers = named.flatMap((name) => (name && name.indexOf("/") > 0 ? [name.slice(0, name.indexOf("/"))] : []));
408
409
  return [...new Set(providers.flatMap((provider) => PROVIDER_KEYS[provider] ?? []))];
409
410
  }
package/dist/monid.d.ts CHANGED
@@ -25,6 +25,8 @@ export type MonidOptions = {
25
25
  /** The most a run is waited for, its first request and every read together (150 s: monid's runs take 1 to 120 s). */
26
26
  waitMs?: number;
27
27
  sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
28
+ /** When a save's reads (the listing, an inspect) stop being sent (epoch ms); READ_BUDGET_MS after the first, unset. */
29
+ readsEnd?: number;
28
30
  };
29
31
  /** What a run's answer says monid charged, in USD: its cost; else undefined when monid charged nothing (UNCHARGED), and
30
32
  * null for every other answer, which may have been charged (one with no cost, FAILED, TIMED_OUT, a run stopped by its
@@ -77,16 +79,27 @@ type MonidPinOutcome = {
77
79
  message: string;
78
80
  }[];
79
81
  };
82
+ /** One server's reads of monid's listing and inspects, shared by its saves (monidReads). */
83
+ export type MonidReads = Map<string, {
84
+ answer: Promise<unknown>;
85
+ at?: number;
86
+ }>;
87
+ /** The reads one server's saves share, by key and what is read: a read out now is joined, not sent again, and one that
88
+ * answered is reused for SHARED_READ_MS. One that failed is dropped once it ends: the next save reads anew. */
89
+ export declare const monidReads: () => MonidReads;
80
90
  /** The monid grants among `grants` pinned against monid's listing on `key` (pinned at a save, never at a run): each
81
91
  * provider's wildcard read as the endpoints monid lists for it now (at most MONID_WILDCARD_MAX), each endpoint inspected
82
92
  * for its description, input and price; a grant `previous` made too carries its pin, unread (as server.ts mcpListingOf).
83
93
  * A grant monid lists nothing for is refused, as is every grant to read with no key or monid unreadable. An endpoint
84
- * with no fixed price (fixedUsd) is pinned with none, and warned of (usageWords). Undefined when no grant is monid's. */
94
+ * with no fixed price (fixedUsd) is pinned with none, and warned of (usageWords). Undefined when no grant is monid's.
95
+ * With `shared` (monidReads), the listing and each inspect are read once for the saves that ask at once. */
85
96
  export declare function pinMonid(grants: readonly string[], options: {
86
97
  key: string | undefined;
87
98
  fetch?: typeof fetch;
88
99
  signal?: AbortSignal;
89
100
  sleep?: MonidOptions["sleep"];
101
+ shared?: MonidReads;
102
+ budgetMs?: number;
90
103
  previous?: {
91
104
  grants: readonly string[];
92
105
  pin: MonidPinBody | null;
package/dist/monid.js CHANGED
@@ -5,7 +5,10 @@
5
5
  // At the save (server.ts saveable, the one check of a create, an edit and an inline run): each grant is read against
6
6
  // monid's listing (a provider's wildcard: every endpoint it lists, GET /v1/endpoints; one endpoint: POST /v1/inspect),
7
7
  // and the pin is stamped on the revision, a grant its current revision made too carried unread. A grant monid does not
8
- // list is refused in words, so is one that cannot be read now (no key, monid unreachable). A run reads only its pin.
8
+ // list is refused in words, so is one that cannot be read now (no key, monid unreachable). A read monid refuses for its
9
+ // rate, fails (5xx) or leaves unanswered past its limit is sent again inside the save's time (READ_BUDGET_MS, from the
10
+ // save's start), and one server's saves share each read (monidReads): saves that arrive together read the listing once,
11
+ // each waiting on it no longer than its own time. A run reads only its pin.
9
12
  //
10
13
  // An endpoint priced by usage (per result, per unit, metered, a matrix or tier with a usage part) is pinned too, with no
11
14
  // fixed price, and the save's warnings name it (usageWords): monid can't cap what such a call charges. Its maxCost
@@ -25,7 +28,7 @@
25
28
  // provider answers 202 with a run id, read again every POLL_MS until it ends, for at most WAIT_MS in all; a run the
26
29
  // caller stops, or one that outlasts the wait, is asked to stop. Every answer reaches the model as JSON, cut at CLIP
27
30
  // characters, the whole of it then filed under the run's work/evidence/monid/.
28
- import { randomUUID } from "node:crypto";
31
+ import { createHash, randomUUID } from "node:crypto";
29
32
  import { workspaceErrorWords } from "./workspace/index.js";
30
33
  import { wireName } from "./catalog.js";
31
34
  import { formatToolName, monidNameOf, parseToolName, sameWireWords } from "./tool-names.js";
@@ -45,10 +48,20 @@ const TERMINAL = ["COMPLETED", "FAILED", "BLOCKED", "STOPPED", "TIMED_OUT"];
45
48
  const MIN_READ_MS = 100;
46
49
  /** How many inspects a save has out at once. */
47
50
  const INSPECTS_AT_ONCE = 8;
48
- /** A save's read of the listing or an inspect, refused for the rate (429) or failed by monid (5xx), is read again after
49
- * what monid says to wait (Retry-After, 2 s when it says nothing, at most READ_WAIT_MS), READ_TRIES times in all. */
50
- const READ_TRIES = 4;
51
+ /** A save's read of the listing or an inspect, refused for the rate (429), failed by monid (5xx) or not answered in
52
+ * time, is sent again after what monid says to wait (Retry-After, 2 s when it says nothing, at least READ_WAIT_MIN_MS
53
+ * and at most READ_WAIT_MS), at most READ_RESENDS times, while that read's waits add up to at most READ_WAITS_MS and
54
+ * the save is inside READ_BUDGET_MS of its start: a burst of saves on one key waits out monid's rate inside the save's
55
+ * own time, and only then is refused. */
56
+ const READ_WAIT_MIN_MS = 250;
51
57
  const READ_WAIT_MS = 10_000;
58
+ const READ_WAITS_MS = 20_000;
59
+ const READ_RESENDS = 20;
60
+ const READ_BUDGET_MS = 45_000;
61
+ /** Why a save's read is not sent, or not waited on, past its time (READ_BUDGET_MS). */
62
+ const OUT_OF_TIME = "no answer within the save's time";
63
+ /** How long one server's saves share a read of monid's listing or an inspect that answered (monidReads). */
64
+ const SHARED_READ_MS = 60_000;
52
65
  /** On an answer monid charged nothing for: the run never ran (refused as sent), was blocked or stopped, or the provider
53
66
  * failed. A symbol, so the model never reads it. */
54
67
  const UNCHARGED = Symbol("monid.uncharged");
@@ -137,17 +150,27 @@ export function monidClient(options) {
137
150
  return { status: res.status, body: isObject(json) ? json : { message: text.slice(0, 500) }, ...(retryAfter >= 0 ? { retryAfter } : {}) };
138
151
  }
139
152
  catch (error) {
140
- return { status: 0, body: { message: signal?.aborted ? "stopped by the caller" : limit.aborted ? `no answer in ${ms / 1000} s` : String(error?.message ?? error) } };
153
+ const timedOut = !signal?.aborted && limit.aborted;
154
+ return { status: 0, body: { message: signal?.aborted ? "stopped by the caller" : timedOut ? `no answer in ${ms / 1000} s` : String(error?.message ?? error) }, ...(timedOut ? { timedOut: true } : {}) };
141
155
  }
142
156
  };
143
157
  const answer = (res) => (res.status >= 200 && res.status < 300 ? res.body : failure(res.status, res.body));
144
- /** A save's read, safe to repeat (READ_TRIES). */
158
+ /** When this client's reads stop being sent (READ_BUDGET_MS after its first, unless given). */
159
+ let readsEnd = options.readsEnd;
160
+ /** A save's read, safe to repeat (READ_WAITS_MS, READ_BUDGET_MS); any other refusal (401, 403, 404), or monid out of
161
+ * reach (a request that failed before its limit), is its answer. */
145
162
  const read = async (method, path, body, signal) => {
146
- for (let tries = 1;; tries++) {
147
- const res = await call(method, path, body, signal);
148
- if ((res.status !== 429 && res.status < 500) || tries >= READ_TRIES || signal?.aborted)
163
+ const end = (readsEnd ??= Date.now() + READ_BUDGET_MS);
164
+ if (Date.now() >= end)
165
+ return { status: 0, body: { message: OUT_OF_TIME } };
166
+ for (let waited = 0, resends = 0;; resends++) {
167
+ const res = await call(method, path, body, signal, Math.min(requestMs, Math.max(MIN_READ_MS, end - Date.now())));
168
+ const wait = Math.min(READ_WAIT_MS, Math.max(READ_WAIT_MIN_MS, (res.retryAfter ?? 2) * 1000));
169
+ const again = res.status === 429 || res.status >= 500 || res.timedOut === true;
170
+ if (!again || signal?.aborted || resends >= READ_RESENDS || waited + wait > READ_WAITS_MS || Date.now() + wait >= end)
149
171
  return res;
150
- await sleep(Math.min(READ_WAIT_MS, (res.retryAfter ?? 2) * 1000), signal);
172
+ waited += wait;
173
+ await sleep(wait, signal);
151
174
  }
152
175
  };
153
176
  const stop = async (runId, why) => {
@@ -280,12 +303,54 @@ function inputSchema(input) {
280
303
  }
281
304
  return { type: "object", additionalProperties: false, properties, ...(required.length ? { required } : {}) };
282
305
  }
306
+ /** The reads one server's saves share, by key and what is read: a read out now is joined, not sent again, and one that
307
+ * answered is reused for SHARED_READ_MS. One that failed is dropped once it ends: the next save reads anew. */
308
+ export const monidReads = () => new Map();
309
+ /** `read`'s answer, shared through `reads` under `id` (monidReads): joined while it is out, kept while `kept` says it
310
+ * answered. A save that joins a read another started waits on it until its own `end` at most, then has `late()`.
311
+ * Without `reads`, read alone. */
312
+ function sharedRead(reads, id, read, kept, end, late) {
313
+ if (!reads)
314
+ return read();
315
+ const now = Date.now();
316
+ for (const [one, entry] of reads)
317
+ if (entry.at !== undefined && now - entry.at >= SHARED_READ_MS)
318
+ reads.delete(one);
319
+ const had = reads.get(id);
320
+ if (had) {
321
+ if (had.at !== undefined)
322
+ return had.answer;
323
+ let timer;
324
+ const lateness = new Promise((resolve) => (timer = setTimeout(() => resolve(late()), Math.max(0, end - now))));
325
+ return Promise.race([had.answer, lateness]).finally(() => clearTimeout(timer));
326
+ }
327
+ const entry = {
328
+ answer: read().then((answer) => {
329
+ if (reads.get(id) !== entry)
330
+ return answer;
331
+ if (kept(answer))
332
+ entry.at = Date.now();
333
+ else
334
+ reads.delete(id);
335
+ return answer;
336
+ }, (error) => {
337
+ if (reads.get(id) === entry)
338
+ reads.delete(id);
339
+ throw error;
340
+ }),
341
+ };
342
+ reads.set(id, entry);
343
+ return entry.answer;
344
+ }
283
345
  /** The monid grants among `grants` pinned against monid's listing on `key` (pinned at a save, never at a run): each
284
346
  * provider's wildcard read as the endpoints monid lists for it now (at most MONID_WILDCARD_MAX), each endpoint inspected
285
347
  * for its description, input and price; a grant `previous` made too carries its pin, unread (as server.ts mcpListingOf).
286
348
  * A grant monid lists nothing for is refused, as is every grant to read with no key or monid unreadable. An endpoint
287
- * with no fixed price (fixedUsd) is pinned with none, and warned of (usageWords). Undefined when no grant is monid's. */
349
+ * with no fixed price (fixedUsd) is pinned with none, and warned of (usageWords). Undefined when no grant is monid's.
350
+ * With `shared` (monidReads), the listing and each inspect are read once for the saves that ask at once. */
288
351
  export async function pinMonid(grants, options) {
352
+ // The save's reads stop READ_BUDGET_MS (or `budgetMs`) after it starts, a wait on another save's read included.
353
+ const readsEnd = Date.now() + (options.budgetMs ?? READ_BUDGET_MS);
289
354
  const pin = {};
290
355
  const before = options.previous;
291
356
  const named = grants.flatMap((tool) => {
@@ -304,7 +369,7 @@ export async function pinMonid(grants, options) {
304
369
  const reads = named.filter((grant) => grant.read && !(grant.parsed.kind === "monid" && pin[grant.tool]));
305
370
  if (reads.length && !options.key)
306
371
  return { refused: reads.map(({ tool }) => ({ tool, message: `${tool} is pinned to what monid lists when the agent is saved, and there is no monid key here to read it with: save the monid key in Settings → API Keys first.` })) };
307
- const refused = reads.length ? await readPins(reads, pin, { ...options, key: options.key }) : [];
372
+ const refused = reads.length ? await readPins(reads, pin, { ...options, key: options.key, readsEnd }) : [];
308
373
  // Two endpoints the harnesses would call by one name (wireName folds `.` and `/`): neither could be told apart.
309
374
  const wires = new Map();
310
375
  for (const tool of Object.keys(pin).sort()) {
@@ -322,28 +387,40 @@ export async function pinMonid(grants, options) {
322
387
  }
323
388
  /** The grants `reads` read against monid's listing into `pin`; why each that could not be is refused. */
324
389
  async function readPins(named, pin, options) {
325
- const client = monidClient({ key: options.key, ...(options.fetch ? { fetch: options.fetch } : {}), ...(options.sleep ? { sleep: options.sleep } : {}) });
390
+ const { readsEnd } = options;
391
+ const client = monidClient({ key: options.key, readsEnd, ...(options.fetch ? { fetch: options.fetch } : {}), ...(options.sleep ? { sleep: options.sleep } : {}) });
326
392
  // monid's own words, which a save's refusal returns to its caller: the key they were read with cut from them, in
327
393
  // every form a run's error is redacted of (key-refusal.ts redacted).
328
394
  const key = options.key;
329
395
  const said = (error) => redacted(String(error), [key]);
396
+ // The shared reads are told apart by a digest of the key they were read with, never the key.
397
+ const keyId = createHash("sha256").update(key).digest("hex");
330
398
  const refused = [];
331
399
  // Each endpoint to pin, by catalog name: each wildcard's provider's as monid lists them, then the grants' own.
332
400
  const wanted = new Map();
333
401
  const providers = new Set(named.flatMap(({ parsed }) => (parsed.kind === "monid-provider" ? [parsed.provider] : [])));
334
402
  if (providers.size) {
335
- const listed = new Map();
336
- // Every page, a bounded number of them: monid's listing is not filtered by provider.
337
- for (let cursor, page = 0; (page === 0 || cursor) && page < 500; page++) {
338
- const res = await client.endpoints(cursor, options.signal);
339
- if (res.error !== undefined)
340
- return named.map(({ tool }) => ({ tool, message: `${tool} could not be pinned: monid's listing could not be read (${said(res.error)}).` }));
341
- for (const item of Array.isArray(res.items) ? res.items : []) {
342
- if (isObject(item) && typeof item.provider === "string" && typeof item.endpoint === "string" && providers.has(item.provider))
343
- listed.set(item.provider, [...(listed.get(item.provider) ?? []), item.endpoint]);
403
+ // Every provider's endpoints, every page, a bounded number of them: monid's listing is not filtered by provider.
404
+ const listing = await sharedRead(options.shared, `${keyId} listing`, async () => {
405
+ const listed = new Map();
406
+ for (let cursor, page = 0; (page === 0 || cursor) && page < 500; page++) {
407
+ const res = await client.endpoints(cursor, options.signal);
408
+ if (res.error !== undefined)
409
+ return { error: res.error };
410
+ for (const item of Array.isArray(res.items) ? res.items : []) {
411
+ if (isObject(item) && typeof item.provider === "string" && typeof item.endpoint === "string") {
412
+ const endpoints = listed.get(item.provider) ?? [];
413
+ listed.set(item.provider, endpoints);
414
+ endpoints.push(item.endpoint);
415
+ }
416
+ }
417
+ cursor = typeof res.cursor === "string" && res.cursor ? res.cursor : undefined;
344
418
  }
345
- cursor = typeof res.cursor === "string" && res.cursor ? res.cursor : undefined;
346
- }
419
+ return { listed };
420
+ }, (answer) => "listed" in answer, readsEnd, () => ({ error: OUT_OF_TIME }));
421
+ if ("error" in listing)
422
+ return named.map(({ tool }) => ({ tool, message: `${tool} could not be pinned: monid's listing could not be read (${said(listing.error)}).` }));
423
+ const { listed } = listing;
347
424
  for (const { tool, parsed } of named) {
348
425
  if (parsed.kind !== "monid-provider")
349
426
  continue;
@@ -365,7 +442,7 @@ async function readPins(named, pin, options) {
365
442
  const inspectOne = async () => {
366
443
  for (let next = queue.shift(); next; next = queue.shift()) {
367
444
  const [tool, at] = next;
368
- const res = await client.inspect(at, options.signal);
445
+ const res = await sharedRead(options.shared, `${keyId} inspect ${JSON.stringify([at.provider, at.endpoint])}`, () => client.inspect(at, options.signal), (answer) => answer.error === undefined, readsEnd, () => ({ error: OUT_OF_TIME }));
369
446
  if (res.status === 404)
370
447
  refused.push({ tool, message: `monid lists no endpoint ${at.endpoint} of a provider ${at.provider}.` });
371
448
  else if (res.error !== undefined)
@@ -5,10 +5,14 @@ export declare const OLLAMA_PROVIDER = "ollama";
5
5
  export declare const OLLAMA_API = "ollama-chat";
6
6
  /** The most context a request asks Ollama for (options.num_ctx), and so the most window a model has here: 64k. */
7
7
  export declare const OLLAMA_NUM_CTX = 65536;
8
- /** How long a listing may take, all of it: a stuck Ollama costs a caller this once per OLLAMA_TTL_MS at most. */
8
+ /** How long a listing may take, all of it: a stuck Ollama costs a caller this only where nothing is kept for its address
9
+ * (ollamaModels); after that it is asked behind its callers. */
9
10
  export declare const OLLAMA_LIST_TIMEOUT_MS = 2000;
10
- /** How long an address's listing is kept before it is asked again (behind the caller, which takes the kept one). */
11
+ /** How long an address's listing is kept before it is asked again (behind the caller, which takes the kept one). A
12
+ * failed ask is never kept fresh (listOllama). */
11
13
  export declare const OLLAMA_TTL_MS = 30000;
14
+ /** Ollama's port, where OLLAMA_HOST names none and no scheme. */
15
+ export declare const OLLAMA_PORT = "11434";
12
16
  /** A model as Ollama lists it: its tag, its capabilities, and the context it was trained on (undefined: /api/show says none). */
13
17
  export type OllamaListed = {
14
18
  readonly name: string;
@@ -49,10 +53,13 @@ export declare function ollamaHostOf(env: NodeJS.ProcessEnv, ownMachine: boolean
49
53
  export declare function ollamaHostRefused(env: NodeJS.ProcessEnv): string | undefined;
50
54
  /**
51
55
  * The models the Ollama `env` names has, asked now: its tags (/api/tags), each one's capabilities and trained context
52
- * (/api/show), in the order Ollama lists them. All of it within `timeoutMs`, with no redirect followed; a refused
53
- * OLLAMA_HOST, a down or hung Ollama, or an answer of the wrong shape lists none, and nothing is thrown. A model /api/show
54
- * does not answer for, before the deadline included, is left out and the others kept; so is a cloud model (remote_host or
55
- * remote_model, in either answer). The answer is kept for its address (ollamaModels, ollamaKept). `fetch`: a test's.
56
+ * (/api/show), in the order Ollama lists them. All of it within `timeoutMs`, with no redirect followed; nothing is thrown.
57
+ * A model /api/show refuses is left out and the others kept; so is a cloud model (remote_host or remote_model, in either
58
+ * answer). The answer is kept for its address (ollamaModels, ollamaKept), fresh for OLLAMA_TTL_MS. A failed ask (a
59
+ * hung Ollama, an /api/tags of the wrong shape, or the deadline passing before every /api/show answered) is no listing:
60
+ * the address keeps the models it had (none kept, what this ask got), stale at once, so the next caller takes them and
61
+ * asks again behind it. A refused connection is an Ollama that is down: its address keeps none, stale too. `fetch`: a
62
+ * test's.
56
63
  */
57
64
  export declare function listOllama(env: NodeJS.ProcessEnv, { fetch: send, timeoutMs }?: {
58
65
  fetch?: typeof fetch;
@@ -77,8 +84,9 @@ export declare function ollamaModels(env: NodeJS.ProcessEnv): Promise<readonly O
77
84
  * kept is gone from the answer (model.ts chooseModel, once the host's default no longer answers). A listing already
78
85
  * under way for the address is awaited, never doubled. */
79
86
  export declare function ollamaRelisted(env: NodeJS.ProcessEnv): Promise<readonly OllamaListed[]>;
80
- /** The models the Ollama `env` names had when last asked (ollamaModels): none where it was never asked. Synchronous, for
81
- * the host's default model (model.ts hostModel), which a listing primes before it is read. */
87
+ /** The models the Ollama `env` names had when last listed (ollamaModels; a failed ask keeps the ones before it, a refused
88
+ * one none): none where it was never asked. Synchronous, for the host's default model (model.ts hostModel), which a
89
+ * listing primes before it is read. */
82
90
  export declare function ollamaKept(env: NodeJS.ProcessEnv): readonly OllamaListed[];
83
91
  /** `env`'s Ollama listing as last kept (ollamaKept), in one string: each model's tag, capabilities and trained context.
84
92
  * A server compares it to see a model pulled, removed or an Ollama started since it made its offers (server.ts). */
@@ -93,6 +101,12 @@ export declare function ollamaToolsModels(env: NodeJS.ProcessEnv): string[];
93
101
  export declare const ollamaToolsModel: (env: NodeJS.ProcessEnv) => string | undefined;
94
102
  /** The provider of `listed` (its chat models) at `base`: keyless, $0, each model's window its context (contextOf). */
95
103
  export declare function ollamaProvider(base: string, listed: readonly OllamaListed[], env: NodeJS.ProcessEnv): import("@earendil-works/pi-ai").Provider<"ollama-chat">;
104
+ /** What a request asks Ollama past pi-ai's own options (model-route.ts ollamaAsks): `format`, the JSON schema its answer is
105
+ * held to (/api/chat's format); `think: false`, a thinking model asked not to think. */
106
+ export type OllamaAsks = {
107
+ format?: Record<string, unknown>;
108
+ think?: false;
109
+ };
96
110
  /** `context` as /api/chat's body for `model`: the current system prompt first, each message in Ollama's shape (a call's
97
111
  * arguments an object, a result `tool` with the tool's name, images as base64), and the current tools in its `tools`. */
98
- export declare function chatBody(model: Model<string>, context: TranscriptContext, options: SimpleStreamOptions | undefined): Record<string, unknown>;
112
+ export declare function chatBody(model: Model<string>, context: TranscriptContext, options: (SimpleStreamOptions & OllamaAsks) | undefined): Record<string, unknown>;
@@ -13,7 +13,9 @@
13
13
  // default context is small, so every request names it: options.num_ctx, the model's trained context up to 64k
14
14
  // (OLLAMA_NUM_CTX), and the model's window here is that same number.
15
15
  // Listing never stalls a caller: one short deadline for the whole listing, no redirects, and a down, hung or refused Ollama
16
- // lists no models and throws nothing. Each address's answer is kept (OLLAMA_TTL_MS) and refreshed behind the caller.
16
+ // throws nothing. Each address's answer is kept (OLLAMA_TTL_MS) and refreshed behind the caller; a failed ask is no
17
+ // answer: the models kept before it stay (none for a refused one: that Ollama is down), and are asked again at the next
18
+ // call (listOllama).
17
19
  import { AsyncLocalStorage } from "node:async_hooks";
18
20
  import { calculateCost, collapseSystemMessages, createAssistantMessageEventStream, getCurrentSystemPrompt, getCurrentTools } from "@earendil-works/pi-ai";
19
21
  import { transformMessages } from "@earendil-works/pi-ai/api/transform-messages";
@@ -25,12 +27,14 @@ export const OLLAMA_PROVIDER = "ollama";
25
27
  export const OLLAMA_API = "ollama-chat";
26
28
  /** The most context a request asks Ollama for (options.num_ctx), and so the most window a model has here: 64k. */
27
29
  export const OLLAMA_NUM_CTX = 65_536;
28
- /** How long a listing may take, all of it: a stuck Ollama costs a caller this once per OLLAMA_TTL_MS at most. */
30
+ /** How long a listing may take, all of it: a stuck Ollama costs a caller this only where nothing is kept for its address
31
+ * (ollamaModels); after that it is asked behind its callers. */
29
32
  export const OLLAMA_LIST_TIMEOUT_MS = 2_000;
30
- /** How long an address's listing is kept before it is asked again (behind the caller, which takes the kept one). */
33
+ /** How long an address's listing is kept before it is asked again (behind the caller, which takes the kept one). A
34
+ * failed ask is never kept fresh (listOllama). */
31
35
  export const OLLAMA_TTL_MS = 30_000;
32
36
  /** Ollama's port, where OLLAMA_HOST names none and no scheme. */
33
- const OLLAMA_PORT = "11434";
37
+ export const OLLAMA_PORT = "11434";
34
38
  const ZERO = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
35
39
  /**
36
40
  * The base URL OLLAMA_HOST names, as the ollama CLI reads it (envconfig.Host): unset, this machine on 11434; with no
@@ -72,7 +76,8 @@ function splitHostPort(hostport) {
72
76
  }
73
77
  return [hostport, undefined];
74
78
  }
75
- /** Each address's last listing, by base URL, and the listing under way for it. */
79
+ /** Each address's last listing, by base URL (`at` -Infinity: a failed ask's, stale at once), and the listing under way
80
+ * for it. */
76
81
  const kept = new Map();
77
82
  const asking = new Map();
78
83
  /** The clock a listing is kept by: Date.now, or a test's (ollamaClock). */
@@ -162,27 +167,48 @@ async function shownOf(ask, name) {
162
167
  }
163
168
  /**
164
169
  * The models the Ollama `env` names has, asked now: its tags (/api/tags), each one's capabilities and trained context
165
- * (/api/show), in the order Ollama lists them. All of it within `timeoutMs`, with no redirect followed; a refused
166
- * OLLAMA_HOST, a down or hung Ollama, or an answer of the wrong shape lists none, and nothing is thrown. A model /api/show
167
- * does not answer for, before the deadline included, is left out and the others kept; so is a cloud model (remote_host or
168
- * remote_model, in either answer). The answer is kept for its address (ollamaModels, ollamaKept). `fetch`: a test's.
170
+ * (/api/show), in the order Ollama lists them. All of it within `timeoutMs`, with no redirect followed; nothing is thrown.
171
+ * A model /api/show refuses is left out and the others kept; so is a cloud model (remote_host or remote_model, in either
172
+ * answer). The answer is kept for its address (ollamaModels, ollamaKept), fresh for OLLAMA_TTL_MS. A failed ask (a
173
+ * hung Ollama, an /api/tags of the wrong shape, or the deadline passing before every /api/show answered) is no listing:
174
+ * the address keeps the models it had (none kept, what this ask got), stale at once, so the next caller takes them and
175
+ * asks again behind it. A refused connection is an Ollama that is down: its address keeps none, stale too. `fetch`: a
176
+ * test's.
169
177
  */
170
178
  export async function listOllama(env, { fetch: send = globalThis.fetch, timeoutMs = OLLAMA_LIST_TIMEOUT_MS } = {}) {
171
179
  const base = baseOf(env);
172
180
  if (base === undefined)
173
181
  return [];
174
- const ask = askerOf(base, send, AbortSignal.timeout(timeoutMs));
182
+ const deadline = AbortSignal.timeout(timeoutMs);
183
+ const ask = askerOf(base, send, deadline);
175
184
  let models = [];
185
+ let whole = false;
186
+ let down = false;
176
187
  try {
177
188
  const tags = (await ask("/api/tags"));
178
- const names = (Array.isArray(tags?.models) ? tags.models : []).filter((tag) => !remote(tag)).map((tag) => tag?.name ?? tag?.model).filter((name) => typeof name === "string" && name.length > 0);
189
+ if (!Array.isArray(tags?.models))
190
+ throw new Error("/api/tags: no models list");
191
+ const names = tags.models.filter((tag) => !remote(tag)).map((tag) => tag?.name ?? tag?.model).filter((name) => typeof name === "string" && name.length > 0);
179
192
  models = (await Promise.all(names.map((name) => shownOf(ask, name)))).filter((model) => model !== undefined);
193
+ whole = !deadline.aborted;
180
194
  }
181
- catch {
182
- models = [];
195
+ catch (error) {
196
+ down = refused(error);
197
+ }
198
+ const before = kept.get(base)?.models;
199
+ const listing = whole ? { at: now(), models } : { at: -Infinity, models: !down && before?.length ? before : models };
200
+ kept.set(base, listing);
201
+ return listing.models;
202
+ }
203
+ /** Whether `error` is a refused connection (ECONNREFUSED anywhere in its causes): nothing listens at the address. */
204
+ function refused(error) {
205
+ for (let at = error; at instanceof Error; at = at.cause) {
206
+ if (at.code === "ECONNREFUSED")
207
+ return true;
208
+ if (at instanceof AggregateError && at.errors.some(refused))
209
+ return true;
183
210
  }
184
- kept.set(base, { at: now(), models });
185
- return models;
211
+ return false;
186
212
  }
187
213
  /** How long a run gives the /api/show of the one Ollama model it names (ollamaShown): longer than a listing's, since the
188
214
  * run cannot start without it and Ollama may be loading another model. */
@@ -228,8 +254,9 @@ export async function ollamaRelisted(env) {
228
254
  kept.delete(base);
229
255
  return ollamaModels(env);
230
256
  }
231
- /** The models the Ollama `env` names had when last asked (ollamaModels): none where it was never asked. Synchronous, for
232
- * the host's default model (model.ts hostModel), which a listing primes before it is read. */
257
+ /** The models the Ollama `env` names had when last listed (ollamaModels; a failed ask keeps the ones before it, a refused
258
+ * one none): none where it was never asked. Synchronous, for the host's default model (model.ts hostModel), which a
259
+ * listing primes before it is read. */
233
260
  export function ollamaKept(env) {
234
261
  const base = baseOf(env);
235
262
  return base === undefined ? [] : (kept.get(base)?.models ?? []);
@@ -314,14 +341,16 @@ export function chatBody(model, context, options) {
314
341
  }
315
342
  }
316
343
  const window = Math.min(model.contextWindow, OLLAMA_NUM_CTX);
344
+ const topP = options?.samplingParams?.top_p;
317
345
  return {
318
346
  model: model.id,
319
347
  messages,
320
348
  ...(tools.length ? { tools: tools.map((tool) => ({ type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters } })) } : {}),
321
349
  stream: true,
322
- // A thinking model asked to reason thinks; asked nothing, Ollama's default.
323
- ...(model.reasoning && options?.reasoning ? { think: true } : {}),
324
- options: { num_ctx: window, ...(options?.maxTokens ? { num_predict: options.maxTokens } : {}), ...(options?.temperature === undefined ? {} : { temperature: options.temperature }) },
350
+ // A thinking model asked to reason thinks; asked not to (think false), does not; asked nothing, Ollama's default.
351
+ ...(model.reasoning && options?.reasoning ? { think: true } : model.reasoning && options?.think === false ? { think: false } : {}),
352
+ ...(options?.format ? { format: options.format } : {}),
353
+ options: { num_ctx: window, ...(options?.maxTokens ? { num_predict: options.maxTokens } : {}), ...(options?.temperature === undefined ? {} : { temperature: options.temperature }), ...(typeof topP === "number" ? { top_p: topP } : {}) },
325
354
  };
326
355
  }
327
356
  /** One request on /api/chat, its NDJSON read into pi-ai's events: text and thinking as they stream, each tool call whole,