@parcha/agentrun-serve 0.1.0-beta.33 → 0.1.0-beta.34

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 (381) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +266 -201
  3. package/dist/adapters.d.ts +0 -4
  4. package/dist/adapters.js +11 -15
  5. package/dist/agent-rows.d.ts +98 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +60 -25
  9. package/dist/agents.d.ts +9 -125
  10. package/dist/agents.js +15 -305
  11. package/dist/answer-json.d.ts +23 -0
  12. package/dist/answer-json.js +58 -0
  13. package/dist/api-only.d.ts +1 -1
  14. package/dist/api-only.js +2 -2
  15. package/dist/bash-read-only.d.ts +22 -0
  16. package/dist/bash-read-only.js +701 -0
  17. package/dist/box-settings.d.ts +3 -23
  18. package/dist/box-settings.js +7 -51
  19. package/dist/boxes.d.ts +17 -0
  20. package/dist/boxes.js +27 -20
  21. package/dist/browser-commands.d.ts +5 -2
  22. package/dist/browser-commands.js +4 -4
  23. package/dist/browser-computer.d.ts +5 -0
  24. package/dist/browser-computer.js +21 -0
  25. package/dist/browser-cost.d.ts +9 -6
  26. package/dist/browser-cost.js +92 -50
  27. package/dist/browser-live.d.ts +7 -20
  28. package/dist/browser-live.js +15 -93
  29. package/dist/browser-person.d.ts +18 -51
  30. package/dist/browser-person.js +94 -277
  31. package/dist/cap.d.ts +8 -5
  32. package/dist/cap.js +12 -5
  33. package/dist/cli.js +39 -13
  34. package/dist/closed-pipes.d.ts +2 -0
  35. package/dist/closed-pipes.js +13 -0
  36. package/dist/computer-commands.d.ts +2 -0
  37. package/dist/computer-commands.js +2 -0
  38. package/dist/computer-keys.js +5 -2
  39. package/dist/computer-setting.d.ts +20 -4
  40. package/dist/computer-setting.js +25 -5
  41. package/dist/computers.d.ts +30 -2
  42. package/dist/computers.js +70 -11
  43. package/dist/confine.d.ts +120 -0
  44. package/dist/confine.js +436 -0
  45. package/dist/console/assets/index-RPHGlXmM.js +540 -0
  46. package/dist/console/assets/index-opTN5Naq.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decision-rows.d.ts +1 -1
  49. package/dist/decision-rows.js +1 -1
  50. package/dist/docker-daemon.d.ts +31 -0
  51. package/dist/docker-daemon.js +56 -0
  52. package/dist/effort-guidance.js +4 -3
  53. package/dist/environment.d.ts +0 -3
  54. package/dist/environment.js +3 -5
  55. package/dist/errors.d.ts +0 -2
  56. package/dist/errors.js +6 -9
  57. package/dist/filed-answer.d.ts +32 -0
  58. package/dist/filed-answer.js +160 -0
  59. package/dist/files.d.ts +1 -3
  60. package/dist/files.js +2 -4
  61. package/dist/github-connection.d.ts +1 -1
  62. package/dist/graph-view.d.ts +3 -5
  63. package/dist/graph-view.js +4 -14
  64. package/dist/handed-values.d.ts +9 -0
  65. package/dist/handed-values.js +26 -0
  66. package/dist/harness-install.d.ts +1 -7
  67. package/dist/harness-install.js +1 -18
  68. package/dist/harness-opencode/adapter.d.ts +7 -0
  69. package/dist/harness-opencode/adapter.js +23 -6
  70. package/dist/harness-opencode/index.d.ts +1 -1
  71. package/dist/harness-opencode/index.js +1 -1
  72. package/dist/harness-opencode/verify.d.ts +17 -0
  73. package/dist/harness-opencode/verify.js +30 -10
  74. package/dist/harness-table.js +6 -1
  75. package/dist/heard.js +1 -1
  76. package/dist/held-fd.d.ts +5 -0
  77. package/dist/held-fd.js +14 -0
  78. package/dist/host-calls.d.ts +20 -0
  79. package/dist/host-calls.js +12 -0
  80. package/dist/host-tools.d.ts +4 -21
  81. package/dist/host-tools.js +4 -61
  82. package/dist/host.d.ts +2 -4
  83. package/dist/host.js +2 -7
  84. package/dist/import-summary.d.ts +1 -5
  85. package/dist/import-summary.js +0 -21
  86. package/dist/import.d.ts +6 -6
  87. package/dist/import.js +14 -15
  88. package/dist/key-refusal.d.ts +5 -1
  89. package/dist/key-refusal.js +19 -4
  90. package/dist/learn/check.d.ts +6 -2
  91. package/dist/learn/check.js +83 -29
  92. package/dist/learn/folder.d.ts +5 -1
  93. package/dist/learn/folder.js +10 -3
  94. package/dist/learn/grade.d.ts +14 -0
  95. package/dist/learn/grade.js +68 -12
  96. package/dist/learn/index.d.ts +4 -4
  97. package/dist/learn/index.js +4 -4
  98. package/dist/learn/reflect.d.ts +31 -2
  99. package/dist/learn/reflect.js +79 -4
  100. package/dist/learn/relevance.d.ts +24 -0
  101. package/dist/learn/relevance.js +91 -0
  102. package/dist/learn/secrets.d.ts +7 -1
  103. package/dist/learn/secrets.js +86 -19
  104. package/dist/learn/skills.d.ts +112 -14
  105. package/dist/learn/skills.js +556 -52
  106. package/dist/learned-workflow.d.ts +32 -1
  107. package/dist/learned-workflow.js +100 -9
  108. package/dist/learning-routes.d.ts +8 -4
  109. package/dist/learning-routes.js +23 -9
  110. package/dist/learning-run.d.ts +9 -26
  111. package/dist/learning-run.js +22 -32
  112. package/dist/learning-words.d.ts +12 -5
  113. package/dist/learning-words.js +18 -9
  114. package/dist/learning.d.ts +93 -77
  115. package/dist/learning.js +176 -304
  116. package/dist/live/stream.js +1 -1
  117. package/dist/live/translate.js +12 -2
  118. package/dist/local-models.d.ts +11 -5
  119. package/dist/local-models.js +13 -8
  120. package/dist/mcp-gateway.d.ts +11 -49
  121. package/dist/mcp-gateway.js +44 -135
  122. package/dist/mcp-oauth.d.ts +10 -14
  123. package/dist/mcp-oauth.js +14 -32
  124. package/dist/mcp-probe.d.ts +0 -7
  125. package/dist/mcp-probe.js +4 -10
  126. package/dist/mcp-servers-store.d.ts +6 -6
  127. package/dist/mcp-servers-store.js +12 -14
  128. package/dist/mcp-store.js +3 -4
  129. package/dist/mcp.js +4 -3
  130. package/dist/model.d.ts +6 -7
  131. package/dist/model.js +43 -27
  132. package/dist/monid.d.ts +0 -2
  133. package/dist/monid.js +3 -6
  134. package/dist/openapi.d.ts +8 -1
  135. package/dist/openapi.js +121 -47
  136. package/dist/page.d.ts +1 -3
  137. package/dist/page.js +6 -18
  138. package/dist/paid-calls.d.ts +21 -27
  139. package/dist/paid-calls.js +25 -60
  140. package/dist/propose.js +83 -39
  141. package/dist/push-handler.d.ts +1 -1
  142. package/dist/reflect-range.d.ts +25 -0
  143. package/dist/reflect-range.js +30 -0
  144. package/dist/refusal-words.d.ts +5 -1
  145. package/dist/refusal-words.js +5 -1
  146. package/dist/rows.d.ts +1 -1
  147. package/dist/run-cut.d.ts +0 -6
  148. package/dist/run-cut.js +0 -6
  149. package/dist/run-db.d.ts +2 -11
  150. package/dist/run-db.js +2 -37
  151. package/dist/run-launch.d.ts +19 -2
  152. package/dist/run-launch.js +13 -5
  153. package/dist/run-learning-served.d.ts +10 -4
  154. package/dist/run-learning-served.js +23 -13
  155. package/dist/run-reads-over-store.d.ts +1 -1
  156. package/dist/run-reads-over-store.js +15 -6
  157. package/dist/run-secrets.d.ts +1 -1
  158. package/dist/run-timeline-served.d.ts +5 -1
  159. package/dist/run-timeline-served.js +15 -4
  160. package/dist/run-view.d.ts +7 -8
  161. package/dist/run-view.js +26 -7
  162. package/dist/runnable.d.ts +18 -10
  163. package/dist/runnable.js +21 -10
  164. package/dist/runner/adapter-loop.d.ts +6 -1
  165. package/dist/runner/adapter-loop.js +423 -53
  166. package/dist/runner/adapter-run-spec.d.ts +21 -8
  167. package/dist/runner/adapter-run-spec.js +90 -32
  168. package/dist/runner/adapters/index.js +11 -1
  169. package/dist/runner/adapters/pi.d.ts +12 -2
  170. package/dist/runner/adapters/pi.js +16 -5
  171. package/dist/runner/beside.d.ts +30 -3
  172. package/dist/runner/beside.js +36 -5
  173. package/dist/runner/claim-secrets.d.ts +10 -1
  174. package/dist/runner/claim-secrets.js +48 -14
  175. package/dist/runner/cli-run-spec.d.ts +2 -0
  176. package/dist/runner/cli-run-spec.js +45 -16
  177. package/dist/runner/commands.js +1 -1
  178. package/dist/runner/computer-journal.d.ts +15 -2
  179. package/dist/runner/computer-journal.js +41 -5
  180. package/dist/runner/conformance/harness.js +118 -8
  181. package/dist/runner/conformance/subject.d.ts +4 -1
  182. package/dist/runner/dispatch.d.ts +8 -1
  183. package/dist/runner/dispatch.js +81 -7
  184. package/dist/runner/end-of-run.d.ts +8 -2
  185. package/dist/runner/end-of-run.js +10 -4
  186. package/dist/runner/github-app.js +1 -1
  187. package/dist/runner/harness-loops.d.ts +9 -1
  188. package/dist/runner/harness-loops.js +15 -2
  189. package/dist/runner/journal-kinds.d.ts +24 -6
  190. package/dist/runner/journal-kinds.js +20 -5
  191. package/dist/runner/journal-reader.d.ts +1 -1
  192. package/dist/runner/journal-reader.js +2 -2
  193. package/dist/runner/learning-ask.d.ts +4 -0
  194. package/dist/runner/learning-ask.js +15 -1
  195. package/dist/runner/learning-end.d.ts +18 -3
  196. package/dist/runner/learning-end.js +113 -11
  197. package/dist/runner/learning-loop.d.ts +5 -0
  198. package/dist/runner/learning-loop.js +26 -6
  199. package/dist/runner/main.d.ts +56 -9
  200. package/dist/runner/main.js +127 -18
  201. package/dist/runner/mcp-claim.js +1 -2
  202. package/dist/runner/mcp-run.d.ts +2 -0
  203. package/dist/runner/mcp-run.js +15 -5
  204. package/dist/runner/memory-claim.d.ts +9 -0
  205. package/dist/runner/memory-claim.js +25 -0
  206. package/dist/runner/metrics.d.ts +33 -1
  207. package/dist/runner/metrics.js +85 -1
  208. package/dist/runner/model-route.d.ts +13 -0
  209. package/dist/runner/model-route.js +133 -9
  210. package/dist/runner/reflect-hook.d.ts +12 -1
  211. package/dist/runner/reflect-hook.js +33 -3
  212. package/dist/runner/runner.d.ts +20 -0
  213. package/dist/runner/runner.js +56 -10
  214. package/dist/runner/store-port.d.ts +1 -1
  215. package/dist/runner/store-secrets.d.ts +3 -3
  216. package/dist/runner/store-secrets.js +8 -12
  217. package/dist/runner/text-tools.d.ts +44 -0
  218. package/dist/runner/text-tools.js +237 -0
  219. package/dist/runner/workflow-loop.d.ts +6 -0
  220. package/dist/runner/workflow-loop.js +6 -4
  221. package/dist/runner/workflow-spec.d.ts +18 -0
  222. package/dist/runner/workflow-spec.js +63 -17
  223. package/dist/runs-over-store.d.ts +7 -2
  224. package/dist/runs-over-store.js +60 -14
  225. package/dist/seal-key.js +5 -43
  226. package/dist/sealed-settings-store.d.ts +19 -4
  227. package/dist/sealed-settings-store.js +9 -9
  228. package/dist/sealing.d.ts +4 -0
  229. package/dist/sealing.js +20 -0
  230. package/dist/secret-cut.d.ts +1 -1
  231. package/dist/secret-cut.js +1 -1
  232. package/dist/secret-name.d.ts +9 -0
  233. package/dist/secret-name.js +15 -0
  234. package/dist/secret-writes.d.ts +0 -1
  235. package/dist/secret-writes.js +0 -1
  236. package/dist/server-fs.d.ts +4 -0
  237. package/dist/server-fs.js +8 -2
  238. package/dist/server-lock.d.ts +0 -24
  239. package/dist/server-lock.js +1 -80
  240. package/dist/server-secrets-store.d.ts +4 -4
  241. package/dist/server-secrets-store.js +9 -31
  242. package/dist/server-secrets.d.ts +4 -9
  243. package/dist/server-secrets.js +12 -36
  244. package/dist/server.d.ts +16 -38
  245. package/dist/server.js +145 -106
  246. package/dist/sign-ins-store.d.ts +34 -36
  247. package/dist/sign-ins-store.js +27 -38
  248. package/dist/sign-ins.d.ts +2 -119
  249. package/dist/sign-ins.js +5 -311
  250. package/dist/standard-webhooks.d.ts +1 -1
  251. package/dist/standard-webhooks.js +1 -1
  252. package/dist/stats.d.ts +3 -2
  253. package/dist/stats.js +1 -1
  254. package/dist/store/agent-body.d.ts +8 -2
  255. package/dist/store/agent-body.js +16 -4
  256. package/dist/store/index.d.ts +2 -2
  257. package/dist/store/index.js +2 -2
  258. package/dist/store/open.d.ts +6 -3
  259. package/dist/store/open.js +2 -2
  260. package/dist/store/postgres/connection.d.ts +18 -2
  261. package/dist/store/postgres/connection.js +156 -32
  262. package/dist/store/postgres/migrate.d.ts +4 -0
  263. package/dist/store/postgres/migrate.js +9 -2
  264. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  265. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  266. package/dist/store/postgres/store.d.ts +9 -2
  267. package/dist/store/postgres/store.js +9 -0
  268. package/dist/store/schema.js +1 -1
  269. package/dist/store/seal.js +2 -2
  270. package/dist/store/sqlite/connection.js +49 -5
  271. package/dist/store/sqlite/run-patch.d.ts +3 -0
  272. package/dist/store/sqlite/run-patch.js +3 -0
  273. package/dist/store/sqlite/store.js +41 -12
  274. package/dist/store/store.d.ts +35 -6
  275. package/dist/store/store.js +12 -2
  276. package/dist/store-reads/cap.d.ts +1 -1
  277. package/dist/store-reads/cap.js +22 -4
  278. package/dist/store-reads/journal.d.ts +9 -6
  279. package/dist/store-reads/journal.js +93 -17
  280. package/dist/store-reads/learning.d.ts +26 -8
  281. package/dist/store-reads/learning.js +12 -4
  282. package/dist/store-reads/workflow.d.ts +1 -1
  283. package/dist/store-reads/workflow.js +1 -1
  284. package/dist/store-view.d.ts +5 -1
  285. package/dist/store-view.js +53 -18
  286. package/dist/template-eval.d.ts +60 -4
  287. package/dist/template-eval.js +120 -54
  288. package/dist/templates.d.ts +24 -10
  289. package/dist/templates.js +69 -38
  290. package/dist/timeline/group.d.ts +33 -0
  291. package/dist/timeline/group.js +77 -0
  292. package/dist/timeline/index.d.ts +7 -0
  293. package/dist/timeline/index.js +7 -0
  294. package/dist/timeline/labels.d.ts +79 -0
  295. package/dist/timeline/labels.js +150 -0
  296. package/dist/timeline/origin.d.ts +56 -0
  297. package/dist/timeline/origin.js +92 -0
  298. package/dist/timeline/render-text.d.ts +11 -0
  299. package/dist/timeline/render-text.js +62 -0
  300. package/dist/timeline/timeline.d.ts +274 -0
  301. package/dist/timeline/timeline.js +1308 -0
  302. package/dist/timeline/util.d.ts +17 -0
  303. package/dist/timeline/util.js +49 -0
  304. package/dist/tool-gate.d.ts +41 -216
  305. package/dist/tool-gate.js +79 -540
  306. package/dist/tool-keys-store.d.ts +11 -12
  307. package/dist/tool-keys-store.js +24 -31
  308. package/dist/tool-keys.d.ts +5 -101
  309. package/dist/tool-keys.js +8 -267
  310. package/dist/tool-plane.d.ts +14 -42
  311. package/dist/tool-plane.js +23 -81
  312. package/dist/tool-settings-store.d.ts +1 -2
  313. package/dist/tool-settings-store.js +5 -8
  314. package/dist/tools.d.ts +30 -18
  315. package/dist/tools.js +97 -107
  316. package/dist/trigger-adapter.d.ts +2 -2
  317. package/dist/trigger-targets.d.ts +13 -1
  318. package/dist/trigger-targets.js +31 -1
  319. package/dist/triggers.d.ts +2 -2
  320. package/dist/triggers.js +3 -3
  321. package/dist/turn-end.d.ts +1 -1
  322. package/dist/turn-end.js +1 -1
  323. package/dist/turns.d.ts +0 -6
  324. package/dist/turns.js +0 -19
  325. package/dist/uploads.js +1 -1
  326. package/dist/usage.d.ts +0 -2
  327. package/dist/usage.js +0 -2
  328. package/dist/validate.d.ts +2 -0
  329. package/dist/validate.js +23 -14
  330. package/dist/webhooks.d.ts +102 -76
  331. package/dist/webhooks.js +266 -233
  332. package/dist/workflow-run.d.ts +114 -0
  333. package/dist/workflow-run.js +144 -0
  334. package/dist/workspace/beneath.d.ts +19 -0
  335. package/dist/workspace/beneath.js +106 -0
  336. package/dist/workspace/computer-deps.d.ts +24 -6
  337. package/dist/workspace/computer-deps.js +108 -20
  338. package/dist/workspace/computer-for-claim.d.ts +12 -11
  339. package/dist/workspace/computer-for-claim.js +76 -15
  340. package/dist/workspace/computer-hold.d.ts +6 -1
  341. package/dist/workspace/computer-hold.js +6 -1
  342. package/dist/workspace/computer-janitor.d.ts +47 -0
  343. package/dist/workspace/computer-janitor.js +182 -0
  344. package/dist/workspace/grep-worker.d.ts +5 -0
  345. package/dist/workspace/grep-worker.js +9 -6
  346. package/dist/workspace/index.d.ts +3 -2
  347. package/dist/workspace/index.js +3 -3
  348. package/dist/workspace/local.d.ts +11 -2
  349. package/dist/workspace/local.js +161 -43
  350. package/dist/workspace/resolve-computer.d.ts +50 -10
  351. package/dist/workspace/resolve-computer.js +46 -11
  352. package/dist/workspace/run-tools.d.ts +13 -31
  353. package/dist/workspace/run-tools.js +10 -27
  354. package/dist/workspace-paths.d.ts +0 -17
  355. package/dist/workspace-paths.js +1 -41
  356. package/dist/workspace.d.ts +0 -14
  357. package/dist/workspace.js +3 -96
  358. package/package.json +13 -13
  359. package/templates/README.md +9 -3
  360. package/templates/market-monitor/agent.md +2 -2
  361. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  362. package/dist/bound-files.d.ts +0 -4
  363. package/dist/bound-files.js +0 -164
  364. package/dist/coding-tools.d.ts +0 -47
  365. package/dist/coding-tools.js +0 -189
  366. package/dist/computer-adb.d.ts +0 -12
  367. package/dist/computer-adb.js +0 -14
  368. package/dist/console/assets/index-Dn0ngwG9.js +0 -535
  369. package/dist/console/assets/index-DvW6Aled.css +0 -1
  370. package/dist/grade.d.ts +0 -63
  371. package/dist/grade.js +0 -150
  372. package/dist/mcp-servers.d.ts +0 -269
  373. package/dist/mcp-servers.js +0 -456
  374. package/dist/packs.d.ts +0 -71
  375. package/dist/packs.js +0 -180
  376. package/dist/sealed-settings.d.ts +0 -60
  377. package/dist/sealed-settings.js +0 -171
  378. package/dist/sessions.d.ts +0 -6
  379. package/dist/sessions.js +0 -109
  380. package/dist/workspace/computer-serves.d.ts +0 -12
  381. package/dist/workspace/computer-serves.js +0 -15
@@ -9,12 +9,16 @@
9
9
  // - any other model answers through the route's own fetch: the Messages request runs on pi-ai's model of it (the faux
10
10
  // core under --faux, never the network; another provider's or the gateway's on its key from `env`), and its events
11
11
  // come back as a Messages stream.
12
+ // A model whose catalog entry takes its tools as text (local-models.ts `toolsAs`) gets them in its system prompt and
13
+ // its calls read back from its reply (text-tools.ts), on this translation alone.
12
14
  // Its price is pi-ai's calculateCost on the catalog's cost, tiers included (a request past a model's tier is priced at
13
15
  // the tier, as its provider bills it), and its cost is that catalog entry, tiers included, for the cap's judgement.
16
+ import { randomUUID } from "node:crypto";
14
17
  import { calculateCost } from "@earendil-works/pi-ai";
15
18
  import { chooseModel, runModels } from "../model.js";
16
19
  import { providerFor } from "../provider.js";
17
20
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
21
+ import { callsOfText, toolsAsText } from "./text-tools.js";
18
22
  /** The origin a route with its own fetch names: nothing is ever sent there, its fetch answers every request. */
19
23
  export const ROUTE_ORIGIN = "https://model-route.invalid";
20
24
  /** The wires a caller of routeOf speaks when it names none: Anthropic's Messages alone. */
@@ -29,14 +33,13 @@ export async function routeOf(model, env = process.env, tier = "default", wires
29
33
  const chosen = await chooseModel(env, model, tier);
30
34
  if ("why" in chosen)
31
35
  throw new Error(chosen.why);
32
- const { models } = await runModels(env, tier === "default" ? model : undefined, [tier]);
36
+ const { models, unpriced } = await runModels(env, tier === "default" ? model : undefined, [tier]);
33
37
  const target = models.getModel(chosen.model.provider, chosen.model.modelId);
34
38
  if (!target)
35
39
  throw new Error(`no model ${chosen.model.provider}/${chosen.model.modelId} here`);
36
- const price = (_model, used) => {
37
- const usage = { ...used, totalTokens: used.input + used.output + used.cacheRead + used.cacheWrite, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
38
- return calculateCost(target, usage).total;
39
- };
40
+ // A model serve has no price for (runModels' `unpriced`) carries a placeholder cost of zeros: its requests are booked at
41
+ // no known price (null), never $0, as a CLI run's are (adapters.ts priceOf).
42
+ const price = (_model, used) => (unpriced.has(chosen.model.modelId) ? null : priceOn(target, used));
40
43
  // What the model takes as input and its input limits, on every wire: pi's session sends a model that takes no images
41
44
  // pi-ai's placeholder in place of one, and pi's read holds an image to the model's limits (port-models.ts sessionModel).
42
45
  const sees = { ...(target.input ? { input: target.input } : {}), ...(target.inputLimits ? { inputLimits: target.inputLimits } : {}) };
@@ -69,8 +72,13 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
69
72
  };
70
73
  return (async (_url, init = {}) => {
71
74
  const body = JSON.parse(String(init.body ?? "{}"));
72
- const context = contextOf(body, target, (id) => providerIds.get(id) ?? id);
73
- const events = models.streamSimple(target, context, { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(upstream ? { fetch: upstream } : {}) });
75
+ const built = contextOf(body, target, (id) => providerIds.get(id) ?? id);
76
+ // A model that takes its tools as text (its catalog entry's toolsAs): its tools in its system prompt, every call and
77
+ // result of its history as text, and its calls read from its reply. A request with no tools goes as it is.
78
+ const asText = target.toolsAs === "text" && (built.tools?.length ?? 0) > 0;
79
+ const context = asText ? toolsAsText(built) : built;
80
+ const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(upstream ? { fetch: upstream } : {}) };
81
+ const events = models.streamSimple(target, context, streamOptions);
74
82
  const encoder = new TextEncoder();
75
83
  const stream = new ReadableStream({
76
84
  async start(controller) {
@@ -80,20 +88,39 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
80
88
  // reports it ("500 {...}"), never this route's envelope around it.
81
89
  const sendError = (words) => controller.enqueue(encoder.encode(`event: error\n${words.split(/\r?\n/).map((line) => `data: ${line}`).join("\n")}\n\n`));
82
90
  send({ type: "message_start", message: { id: `msg_${Date.now().toString(36)}`, type: "message", role: "assistant", model: body.model ?? target.id, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } });
83
- // Messages blocks are numbered as sent; a thinking block of pi-ai's is not sent (it carries no signature here).
91
+ // Messages blocks are numbered as sent. A thinking block is sent too, so the model's reasoning reaches the run's
92
+ // record as a Timeline row; its text goes through the run's one redactor, so a held key the model quoted in its
93
+ // thinking is cut before pi's session journals it, not only at read. It carries no signature here, which the bridge
94
+ // back (contextOf) drops from a later turn's request, so none is needed and the cut thinking is never read as context.
84
95
  const blockOf = new Map();
85
96
  const sentJson = new Set();
86
97
  let blocks = 0;
98
+ // The thinking of the block being streamed, gathered so its whole text is redacted at once (its deltas are not sent).
99
+ let thinking = "";
87
100
  const open = (at) => {
88
101
  const index = blocks++;
89
102
  blockOf.set(at ?? -1, index);
90
103
  return index;
91
104
  };
92
105
  try {
93
- for await (const event of events) {
106
+ for await (const event of asText ? [] : events) {
94
107
  const at = event.contentIndex;
95
108
  if (event.type === "text_start")
96
109
  send({ type: "content_block_start", index: open(at), content_block: { type: "text", text: "" } });
110
+ else if (event.type === "thinking_start") {
111
+ thinking = "";
112
+ send({ type: "content_block_start", index: open(at), content_block: { type: "thinking", thinking: "", signature: "" } });
113
+ }
114
+ else if (event.type === "thinking_delta")
115
+ thinking += event.delta ?? "";
116
+ else if (event.type === "thinking_end") {
117
+ // The whole thinking at its end, through the run's one redactor, in one delta: a held key the model quoted is
118
+ // cut before pi's session journals it even where it spans two deltas (a cut per delta could miss a key split
119
+ // across them).
120
+ const index = blockOf.get(at ?? -1);
121
+ send({ type: "content_block_delta", index, delta: { type: "thinking_delta", thinking: redact(thinking) } });
122
+ send({ type: "content_block_stop", index });
123
+ }
97
124
  else if (event.type === "text_delta")
98
125
  send({ type: "content_block_delta", index: blockOf.get(at ?? -1), delta: { type: "text_delta", text: event.delta ?? "" } });
99
126
  else if (event.type === "toolcall_start") {
@@ -132,6 +159,79 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
132
159
  send({ type: "message_stop" });
133
160
  }
134
161
  }
162
+ if (asText) {
163
+ // The reply whole, then its text and its calls as Messages blocks. A reply that opens a call block and
164
+ // holds no call it can read is asked again, at most TEXT_TOOL_TRIES times in all, its usage summed, and
165
+ // only out of what the cap held for this one request (reaskTokens): the re-ask's output limit is what is
166
+ // left of it once the tries so far and the re-ask's own input, uncached, are paid.
167
+ const tools = built.tools ?? [];
168
+ const used = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
169
+ const outputHeld = body.max_tokens ?? target.maxTokens;
170
+ let heldUsd = 0;
171
+ let spentUsd = 0;
172
+ let replies = events;
173
+ let nextTokens = 0;
174
+ for (let attempt = 1;; attempt++) {
175
+ let again = false;
176
+ for await (const event of replies) {
177
+ if (event.type !== "done" && event.type !== "error")
178
+ continue;
179
+ const message = (event.type === "done" ? event.message : event.error) ?? {};
180
+ if (event.type === "error") {
181
+ sendError(redact(message.errorMessage ?? event.reason ?? "the model's request failed"));
182
+ break;
183
+ }
184
+ const given = message.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
185
+ const part = { input: given.input, output: given.output, cacheRead: given.cacheRead ?? 0, cacheWrite: given.cacheWrite ?? 0 };
186
+ used.input += part.input;
187
+ used.output += part.output;
188
+ used.cacheRead += part.cacheRead;
189
+ used.cacheWrite += part.cacheWrite;
190
+ if (attempt === 1 && outputHeld !== undefined)
191
+ heldUsd = priceOn(target, { ...part, output: outputHeld });
192
+ spentUsd += priceOn(target, part);
193
+ const said = (message.content ?? []).filter((each) => each.type === "text").map((each) => each.text ?? "").join("");
194
+ // A reply cut at its output limit may stop inside a call: a call block in it is never run, it is broken.
195
+ const cut = (event.reason ?? message.stopReason) === "length";
196
+ const parsed = callsOfText(said, tools);
197
+ const read = cut && (parsed.calls.length > 0 || parsed.broken) ? { text: said.trim(), calls: [], broken: true } : parsed;
198
+ if (read.broken && attempt < TEXT_TOOL_TRIES && outputHeld !== undefined) {
199
+ nextTokens = reaskTokens(target, part, heldUsd - spentUsd, outputHeld);
200
+ if (nextTokens > 0 && nextTokens >= part.output) {
201
+ again = true;
202
+ break;
203
+ }
204
+ }
205
+ // The reply's thinking first, as the streamed branch sends it: one block, its whole text through the run's
206
+ // one redactor before pi's session journals it.
207
+ const thought = (message.content ?? []).filter((each) => each.type === "thinking").map((each) => each.thinking ?? "").join("");
208
+ if (thought) {
209
+ const index = blocks++;
210
+ send({ type: "content_block_start", index, content_block: { type: "thinking", thinking: "", signature: "" } });
211
+ send({ type: "content_block_delta", index, delta: { type: "thinking_delta", thinking: redact(thought) } });
212
+ send({ type: "content_block_stop", index });
213
+ }
214
+ if (read.text) {
215
+ const index = blocks++;
216
+ send({ type: "content_block_start", index, content_block: { type: "text", text: "" } });
217
+ send({ type: "content_block_delta", index, delta: { type: "text_delta", text: read.text } });
218
+ send({ type: "content_block_stop", index });
219
+ }
220
+ for (const call of read.calls) {
221
+ const index = blocks++;
222
+ send({ type: "content_block_start", index, content_block: { type: "tool_use", id: messagesId(`call_${randomUUID().replace(/-/g, "").slice(0, 24)}`), name: call.name, input: {} } });
223
+ send({ type: "content_block_delta", index, delta: { type: "input_json_delta", partial_json: JSON.stringify(call.arguments) } });
224
+ send({ type: "content_block_stop", index });
225
+ }
226
+ const reason = read.calls.length ? "tool_use" : stopReasonOf(event.reason === "toolUse" ? "stop" : event.reason ?? message.stopReason);
227
+ send({ type: "message_delta", delta: { stop_reason: reason, stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite } });
228
+ send({ type: "message_stop" });
229
+ }
230
+ if (!again)
231
+ break;
232
+ replies = models.streamSimple(target, context, { ...streamOptions, maxTokens: nextTokens });
233
+ }
234
+ }
135
235
  }
136
236
  catch (error) {
137
237
  sendError(redact(error?.message ?? String(error)));
@@ -200,3 +300,27 @@ function contextOf(body, target, providerId) {
200
300
  ...(body.tools?.length ? { tools: body.tools.map((tool) => ({ name: tool.name, description: tool.description ?? "", parameters: tool.input_schema ?? { type: "object", properties: {} } })) } : {}),
201
301
  };
202
302
  }
303
+ /** How many times a text-tools reply is asked for when it opens a call block that holds no call it can read. */
304
+ const TEXT_TOOL_TRIES = 3;
305
+ /** `used` priced on `target`'s catalog entry: pi-ai's calculateCost, tiers included (the proxy's booking, and the cap's). */
306
+ function priceOn(target, used) {
307
+ const usage = { ...used, totalTokens: used.input + used.output + used.cacheRead + used.cacheWrite, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
308
+ return calculateCost(target, usage).total;
309
+ }
310
+ /** A text-tools re-ask's output limit: the most tokens it may answer with when what is left of the request's hold is
311
+ * `leftUsd` (its first try's input as it was billed and its output limit `outputHeld`, less every try so far) and its
312
+ * input, the prompt `last` was asked with, is priced uncached at the dearer of the input and cache-write prices, as the
313
+ * cap prices a fresh input. Never more than `outputHeld`; 0 when nothing is left. So the one hold the cap took for
314
+ * the request covers every try it makes. */
315
+ export function reaskTokens(target, last, leftUsd, outputHeld) {
316
+ const prompt = last.input + last.cacheRead + last.cacheWrite;
317
+ const at = (output) => Math.max(priceOn(target, { input: prompt, output, cacheRead: 0, cacheWrite: 0 }), priceOn(target, { input: 0, output, cacheRead: 0, cacheWrite: prompt }));
318
+ const inputUsd = at(0);
319
+ const perToken = (at(1_000_000) - inputUsd) / 1_000_000;
320
+ const room = leftUsd - inputUsd;
321
+ if (room < 0)
322
+ return 0;
323
+ if (!(perToken > 0))
324
+ return outputHeld;
325
+ return Math.max(0, Math.min(outputHeld, Math.floor(room / perToken)));
326
+ }
@@ -37,6 +37,11 @@ export type Checked = {
37
37
  };
38
38
  /** What the hook reads of the run and the host. */
39
39
  export interface ReflectDeps {
40
+ /** Whether the run's job gave nothing new to look back on: its only tool work was its learned workflows, each of them
41
+ * answering, with no error, no refused call, no approval and nothing said after its first message. Such a run is not
42
+ * asked its end-of-run turn (no model request, nothing spent looking back), and its learning is dropped `empty` in
43
+ * said.onlyWorkflow's words. Absent, or a read that throws: every run is asked. */
44
+ readonly nothingNew?: (runId: string) => Promise<boolean>;
40
45
  /** The run's facts for reflectSkip: whether it learns, a person's cancel, its cap reached, its cap and spend so far. */
41
46
  readonly facts: (runId: string) => Promise<{
42
47
  learns: boolean;
@@ -45,10 +50,16 @@ export interface ReflectDeps {
45
50
  capUsd?: number;
46
51
  costUsd: number | null;
47
52
  }>;
48
- /** The prompt's facts: how many notes the run started from, and the tools a workflow draft may name. */
53
+ /** The prompt's facts: how many notes the run started from, the tools a workflow draft may name, and the learned skills
54
+ * whose job the prompt asks for as a workflow draft (reflectPrompt's draftFor; none when absent). */
49
55
  readonly promptFacts: (runId: string, agentId: string) => Promise<{
50
56
  active: number;
51
57
  tools: readonly string[];
58
+ draftFor?: readonly string[];
59
+ described?: readonly {
60
+ readonly name: string;
61
+ readonly does: string;
62
+ }[];
52
63
  }>;
53
64
  /** What the person said in the run, and a trigger's input, as the checks and the grader read them. */
54
65
  readonly asked: (runId: string) => Promise<{
@@ -6,7 +6,7 @@
6
6
  // (`refuse`: the host's secrets and what it was handed, its sign-in pointer among them) is refused by the checks, and cut
7
7
  // from everything the hook keeps; a run whose list can't be read learns nothing.
8
8
  import { cutStrings } from "../key-refusal.js";
9
- import { reflectAgain, reflectPrompt, redactSecrets } from "../learn/index.js";
9
+ import { DRY_RUN_FAILED, reflectAgain, reflectDryRun, reflectPrompt, redactSecrets } from "../learn/index.js";
10
10
  import { said, STOPPED } from "../learning-words.js";
11
11
  /** How long a run's end-of-run turn may take before it is aborted and the run ends without it. */
12
12
  export const REFLECT_TIMEOUT_MS = 5 * 60_000;
@@ -21,6 +21,13 @@ const droppedRow = (turn, reason, detail, extra = {}) => ({ table: "learning_pro
21
21
  * answered, and the proposal's words. A proposal the checks kept holds none of them already (unstorable refuses it
22
22
  * whole). */
23
23
  const cutRow = (row, refuse) => row.table === "learning_proposals" ? { table: row.table, row: cutStrings(row.row, (text) => redactSecrets(text, refuse, Number.POSITIVE_INFINITY)) } : row;
24
+ /** The first workflow draft the checks left out of `checked` because its dry run failed (learn/skills.ts DRY_RUN_FAILED):
25
+ * its path and the check's words; undefined when none was. */
26
+ function dryRunFailure(checked) {
27
+ const problems = (checked.state === "proposed" ? checked.left ?? [] : checked.state === "dropped" && checked.reason === "checker" ? checked.problems : []);
28
+ const found = problems.find((problem) => problem?.rule === "workflow" && typeof problem.path === "string" && typeof problem.detail === "string" && problem.detail.startsWith(DRY_RUN_FAILED));
29
+ return found ? { path: found.path, detail: found.detail } : undefined;
30
+ }
24
31
  /** The end-of-run turn for runs that learn. */
25
32
  export function createReflectHook(deps) {
26
33
  return async (input) => {
@@ -54,6 +61,12 @@ export function createReflectHook(deps) {
54
61
  const answered = { answered_at: answeredAt, job_cost_usd: job, look_back_usd: total === null || job === null ? null : Math.max(0, Math.round((total - job) * 1e9) / 1e9) };
55
62
  return { also: rows.also.map((row) => (row.table === "learning_proposals" ? { ...row, row: { ...row.row, proposal: { ...row.row.proposal, ...answered } } } : row)) };
56
63
  };
64
+ // A job that only ran its learned workflows, each answering, with nothing said after its first message, gave nothing
65
+ // new to learn: it is not asked (no model request), and looking back cost nothing, $0 whether or not the job's own
66
+ // cost is known. Its words are the server's own.
67
+ if (input.outcome === "completed" && deps.nothingNew && (await deps.nothingNew(input.runId).catch(() => false))) {
68
+ return { also: [droppedRow(null, "empty", said.onlyWorkflow, { answered_at: answeredAt, job_cost_usd: job, look_back_usd: 0 })] };
69
+ }
57
70
  // What the run must never learn, read once, before it is asked anything: a run whose list can't be read learns
58
71
  // nothing, never over a shorter one.
59
72
  const read = deps.refuse ? await deps.refuse(input.runId).catch(() => "unreadable") : [];
@@ -63,10 +76,10 @@ export function createReflectHook(deps) {
63
76
  const close = async (rows) => ({ also: (await looked({ also: rows })).also.map((row) => cutRow(row, refuse)) });
64
77
  if (read === "unreadable")
65
78
  return close([droppedRow(null, "propose_failed", said.stopped(STOPPED.refuseUnread))]);
66
- const { active, tools } = await deps.promptFacts(input.runId, input.agentId);
79
+ const { active, tools, draftFor, described } = await deps.promptFacts(input.runId, input.agentId);
67
80
  const deadlineMs = deps.deadlineMs ?? REFLECT_TIMEOUT_MS;
68
81
  const started = now();
69
- const end = await input.ask(reflectPrompt({ dir: LEARNED_DIR, active, tools }), { origin: "reflect", deadlineMs });
82
+ const end = await input.ask(reflectPrompt({ dir: LEARNED_DIR, active, tools, ...(draftFor?.length ? { draftFor, ...(described?.length ? { described } : {}) } : {}) }), { origin: "reflect", deadlineMs });
70
83
  // closeLearning: how the turn ended.
71
84
  if ("timedOut" in end)
72
85
  return close([droppedRow(null, "reflect_timeout", said.stopped(STOPPED.timedOut))]);
@@ -99,6 +112,23 @@ export function createReflectHook(deps) {
99
112
  return close([droppedRow(turn, "propose_failed", said.stopped(STOPPED.notChecked))]);
100
113
  }
101
114
  }
115
+ else {
116
+ // A workflow draft the checks left out because its dry run failed is asked for again once, in the same turn and
117
+ // within its deadline, saying which draft and why: the second answer stands only when the checks keep it and no
118
+ // draft in it still fails its dry run, else the first answer's, that draft left out, stands (a repair that failed
119
+ // never costs a note the first answer kept). Never a third time (a turn asks again once, for either reason).
120
+ const dry = dryRunFailure(checked);
121
+ const left = deadlineMs - (now() - started);
122
+ const again = dry && left > 0 ? await input.ask(reflectDryRun(dry.path, dry.detail), { origin: "reflect", deadlineMs: left, again: true }) : undefined;
123
+ if (again && "ended" in again) {
124
+ const second = turnOf(again.answer);
125
+ const kept = await checkOf(second);
126
+ if (kept?.state === "proposed" && !dryRunFailure(kept)) {
127
+ turn = second;
128
+ checked = kept;
129
+ }
130
+ }
131
+ }
102
132
  if (checked.state === "dropped") {
103
133
  const detail = checked.reason === "empty" ? said.empty : checked.reason === "unparsed" ? said.unparsed : said.checker(checked.problems);
104
134
  return close([droppedRow(turn, checked.reason, detail, checked)]);
@@ -4,6 +4,14 @@ import { type Redact } from "./redact.js";
4
4
  import { type LiveTickerOptions } from "./live-ticker.js";
5
5
  /** Most runs a runner holds at once, unless told (RunnerOptions.loops). */
6
6
  export declare const RUNNER_LOOPS = 300;
7
+ /** How long a claim lasts unless renewed, unless told (RunnerOptions.leaseMs). */
8
+ export declare const RUNNER_LEASE_MS = 30000;
9
+ /** A claim not renewed by its until less this is lost here, unless told (RunnerOptions.stopMarginMs). */
10
+ export declare const RUNNER_STOP_MARGIN_MS = 5000;
11
+ /** The longest close() takes with the default lease (Runner.close): the drain, then the loops' stop, which waits for a
12
+ * loop that does not stop until its claim would run out (the lease less its margin, 25 s). A stop deadline that cuts the
13
+ * process sooner cuts a run's end short, and the run waits out its lease before another runner resumes it. */
14
+ export declare const runnerCloseBoundMs: (drainMs: number) => number;
7
15
  /** How often a runner renews the claims it holds, unless told (RunnerOptions.renewEveryMs). */
8
16
  export declare const RUNNER_RENEW_EVERY_MS = 10000;
9
17
  /** A runner's name when none is given: its host, its process and a part of a random id. */
@@ -52,6 +60,12 @@ export interface RunnerOptions {
52
60
  * run's own process drained on the server's stop) before it stops the rest for a shutdown, to resume. Its commands
53
61
  * still reach it meanwhile (a person's stop ends it at once). Default 0: every loop stopped at once. */
54
62
  drainMs?: number;
63
+ /** Claiming by memory as well as by count: a waiting run is claimed only while the runs this runner holds and it weigh
64
+ * no more than `budgetMib` together (each run's weight, `weigh`'s, is what a run of its harness reserves:
65
+ * runner/memory-claim.ts). Waiting runs are taken oldest first, and one that does not fit stops the claim there, so the
66
+ * runs behind it wait too and a heavy run is never passed over for ever by light ones. A run heavier than the whole
67
+ * budget is claimed when the runner holds nothing, so it never waits for ever. Absent: by count alone (`loops`). */
68
+ memory?: RunnerMemory;
55
69
  /** A refused stopped end that withdraws a call (endRefused): the first wait, its cap, and the tries at the cap before
56
70
  * the run ends on its row alone. Defaults END_RETRY_BACKOFF_MS, END_RETRY_CAP_MS, END_RETRY_AT_CAP. */
57
71
  endRetryBackoffMs?: number;
@@ -77,6 +91,12 @@ export interface RunnerOptions {
77
91
  clearTimeout(handle: unknown): void;
78
92
  };
79
93
  }
94
+ /** A runner's memory budget and its runs' weights, in MiB (RunnerOptions.memory). `weigh` answers each id it is given; an
95
+ * id it leaves out weighs nothing. */
96
+ export interface RunnerMemory {
97
+ readonly budgetMib: number;
98
+ weigh(runIds: readonly string[]): Promise<ReadonlyMap<string, number>>;
99
+ }
80
100
  export type RunnerEvent = {
81
101
  type: "claimed";
82
102
  claim: Claim;
@@ -18,6 +18,14 @@ import { heldRedactor, processSecretRedactor } from "./redact.js";
18
18
  import { withLiveTicker } from "./live-ticker.js";
19
19
  /** Most runs a runner holds at once, unless told (RunnerOptions.loops). */
20
20
  export const RUNNER_LOOPS = 300;
21
+ /** How long a claim lasts unless renewed, unless told (RunnerOptions.leaseMs). */
22
+ export const RUNNER_LEASE_MS = 30_000;
23
+ /** A claim not renewed by its until less this is lost here, unless told (RunnerOptions.stopMarginMs). */
24
+ export const RUNNER_STOP_MARGIN_MS = 5_000;
25
+ /** The longest close() takes with the default lease (Runner.close): the drain, then the loops' stop, which waits for a
26
+ * loop that does not stop until its claim would run out (the lease less its margin, 25 s). A stop deadline that cuts the
27
+ * process sooner cuts a run's end short, and the run waits out its lease before another runner resumes it. */
28
+ export const runnerCloseBoundMs = (drainMs) => drainMs + RUNNER_LEASE_MS - RUNNER_STOP_MARGIN_MS;
21
29
  /** How often a runner renews the claims it holds, unless told (RunnerOptions.renewEveryMs). */
22
30
  export const RUNNER_RENEW_EVERY_MS = 10_000;
23
31
  /** A runner's name when none is given: its host, its process and a part of a random id. */
@@ -45,7 +53,7 @@ const message = (error) => (error instanceof Error ? error.message : String(erro
45
53
  /** The run states a run patch makes final: a commit that lands one is the run's end, and its release. */
46
54
  const FINAL = new Set(["ended", "stopped", "failed"]);
47
55
  export function startRunner(options) {
48
- const { store, createLoop, name = runnerName(), loops = RUNNER_LOOPS, leaseMs = 30_000, renewEveryMs = RUNNER_RENEW_EVERY_MS, stopMarginMs = 5_000, pollMs = 1_000, commandPollMs = 500, resumeTries = 3, resumeBackoffMs = 5_000, interruptBackoffMs = 1_000, endWaitMs = 5_000, drainMs = 0, endRetryBackoffMs = END_RETRY_BACKOFF_MS, endRetryCapMs = END_RETRY_CAP_MS, endRetryAtCap = END_RETRY_AT_CAP, onEvent = () => { }, redact: given = processSecretRedactor(), now = Date.now, onBeat = () => { }, clock = { now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (handle) => clearTimeout(handle) }, } = options;
56
+ const { store, createLoop, name = runnerName(), loops = RUNNER_LOOPS, leaseMs = RUNNER_LEASE_MS, renewEveryMs = RUNNER_RENEW_EVERY_MS, stopMarginMs = RUNNER_STOP_MARGIN_MS, pollMs = 1_000, commandPollMs = 500, resumeTries = 3, resumeBackoffMs = 5_000, interruptBackoffMs = 1_000, endWaitMs = 5_000, drainMs = 0, memory, endRetryBackoffMs = END_RETRY_BACKOFF_MS, endRetryCapMs = END_RETRY_CAP_MS, endRetryAtCap = END_RETRY_AT_CAP, onEvent = () => { }, redact: given = processSecretRedactor(), now = Date.now, onBeat = () => { }, clock = { now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (handle) => clearTimeout(handle) }, } = options;
49
57
  // The one instance every run's loop gets (LoopDeps.redact), able to hold what each claim opens from the store
50
58
  // (redact.ts holdClaimed): a stored key is cut wherever a key of the runner's environment is.
51
59
  const redact = heldRedactor(given);
@@ -286,7 +294,7 @@ export function startRunner(options) {
286
294
  * so it throws EndNotWithdrawn and the run is left as it stands, not final, its stop untaken (endRefused retries it). A
287
295
  * lost claim (Fenced) writes neither.
288
296
  */
289
- const endRun = async (claim, given, take) => {
297
+ const endRun = async (claim, given, take, withdrawnAs = "withdrawn") => {
290
298
  // Why the run ended, as its end and its row say it: cut of every secret the runner holds (an error's text may echo one).
291
299
  const data = { ...given, summary: redact(given.summary) };
292
300
  // Unknown means it may withdraw: false only once the journal was read and no call of it waits.
@@ -305,7 +313,7 @@ export function startRunner(options) {
305
313
  // A stopped end withdraws every call still waiting for its answer (an ask with no answer), in this commit: the
306
314
  // approval card of a run whose loop could not start reads answered, never waiting for good.
307
315
  if (data.state === "stopped" && root) {
308
- const withdrawn = withdrawnAnswers(await journalEntries(journal, BACKGROUND_CONTEXT), new Date(now()).toISOString());
316
+ const withdrawn = withdrawnAnswers(await journalEntries(journal, BACKGROUND_CONTEXT), new Date(now()).toISOString(), withdrawnAs);
309
317
  mayWithdraw = withdrawn.length > 0;
310
318
  for (const answer of withdrawn) {
311
319
  const answerId = (await journal.mintId());
@@ -331,7 +339,7 @@ export function startRunner(options) {
331
339
  * call and the journal would not take it or could not be read: the refusal is then the run's (endRefused). */
332
340
  const endStopped = async (claim, stop) => {
333
341
  try {
334
- await endRun(claim, { state: "stopped", summary: endedBy(stop.kind === "cancel") }, [stop.id]);
342
+ await endRun(claim, { state: "stopped", summary: endedBy(stop.kind === "cancel") }, [stop.id], stop.kind === "cancel" ? "canceled" : "withdrawn");
335
343
  return true;
336
344
  }
337
345
  catch (error) {
@@ -500,7 +508,7 @@ export function startRunner(options) {
500
508
  }
501
509
  emit({ type: "released", runId: claim.runId, epoch: claim.epoch, end: "parked" });
502
510
  };
503
- const hold = (claim, sentAt) => {
511
+ const hold = (claim, sentAt, mib = 0) => {
504
512
  const fence = { lost: false };
505
513
  const abort = new AbortController();
506
514
  let firstDelivered;
@@ -514,7 +522,7 @@ export function startRunner(options) {
514
522
  delivered,
515
523
  redact,
516
524
  });
517
- const held = { claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false };
525
+ const held = { claim, loop, fence, abort, cursor: 0, stopping: false, ending: false, sealed: false, renewing: false, delivering: false, mib };
518
526
  // The loop's own end landed: the run is ending from here, its teardown included (no renew, no lost claim).
519
527
  ending = () => {
520
528
  held.ending = true;
@@ -546,10 +554,12 @@ export function startRunner(options) {
546
554
  const free = loops - runs.size - replaced.size;
547
555
  if (free <= 0)
548
556
  return;
549
- // One store call claims the batch, each run at its own epoch + 1 (store.runs.claimMany): filling 300 loops, or
550
- // taking a dead runner's runs over, is one transaction, not 300.
557
+ // By count alone, one store call claims the batch, each run at its own epoch + 1 (store.runs.claimMany): filling 300
558
+ // loops, or taking a dead runner's runs over, is one transaction, not 300. By memory, each run that fits is claimed
559
+ // on its own (claimByMemory).
551
560
  const sentAt = clock.now();
552
- const claims = await store.runs.claimMany(name, free, { leaseMs });
561
+ const weights = new Map();
562
+ const claims = memory ? await claimByMemory(memory, free, weights) : await store.runs.claimMany(name, free, { leaseMs });
553
563
  // A run whose untaken stop row has tries failed to apply that stop before: its claim only ends it (endRetried). Either
554
564
  // source of tries counts: a refused stopped end (endRefused, released running) or a failed resume (resumeFailed's
555
565
  // store.retry, released parked). One read of those claims' rows, made only when the batch has a released run.
@@ -577,7 +587,7 @@ export function startRunner(options) {
577
587
  replaced.add(before);
578
588
  void before.done.finally(() => replaced.delete(before));
579
589
  }
580
- hold(claim, sentAt);
590
+ hold(claim, sentAt, weights.get(claim.runId) ?? 0);
581
591
  }
582
592
  catch (error) {
583
593
  // The loop could not be made: the run fails here, so it is not claimed again and again.
@@ -595,6 +605,42 @@ export function startRunner(options) {
595
605
  polling = false;
596
606
  }
597
607
  };
608
+ /** Up to `free` waiting runs, oldest first, while they fit `memory`'s budget beside what this runner holds (a lost
609
+ * claim's loop still running holds its weight too): each claimed on its own, its weight put in `weights`. The first that
610
+ * does not fit ends the claim, unless the runner holds nothing: then it is claimed alone. */
611
+ const claimByMemory = async (budget, free, weights) => {
612
+ const waiting = await store.runs.claimable({ limit: free });
613
+ if (waiting.length === 0)
614
+ return [];
615
+ const weighed = await budget.weigh(waiting);
616
+ let heldMib = [...runs.values(), ...replaced].reduce((sum, held) => sum + held.mib, 0);
617
+ let holding = runs.size + replaced.size;
618
+ const claims = [];
619
+ for (const runId of waiting) {
620
+ const mib = weighed.get(runId) ?? 0;
621
+ if (holding > 0 && heldMib + mib > budget.budgetMib)
622
+ break;
623
+ if (closed || killed)
624
+ break;
625
+ // Another runner may have taken it since the read: then it is not this one's, and the next is tried. A claim that
626
+ // throws ends this poll's claims, keeping those that landed: they are held below, never left claimed and unstarted.
627
+ let claim;
628
+ try {
629
+ claim = await store.claim(runId, name, { leaseMs });
630
+ }
631
+ catch (error) {
632
+ emit({ type: "error", runId, step: "claim", message: message(error) });
633
+ break;
634
+ }
635
+ if (!claim)
636
+ continue;
637
+ claims.push(claim);
638
+ weights.set(runId, mib);
639
+ heldMib += mib;
640
+ holding += 1;
641
+ }
642
+ return claims;
643
+ };
598
644
  /** The poll's claim in flight, if any: close() waits for it, so a runner whose close resolved claims nothing after it. */
599
645
  let claiming;
600
646
  const poll = () => {
@@ -1,6 +1,6 @@
1
1
  import { type Store } from "../store/store.js";
2
2
  export type RunnerStore = Pick<Store, "claim" | "renew" | "renewMany" | "release" | "journal" | "flush" | "commands" | "commandsOf" | "take" | "retry"> & {
3
- readonly runs: Pick<Store["runs"], "claimMany" | "update">;
3
+ readonly runs: Pick<Store["runs"], "claimMany" | "claimable" | "update">;
4
4
  /** The runs' live view (run_live): the runner's live ticker writes each run's held state there. A store without it (a
5
5
  * test's) has no live view. */
6
6
  readonly live?: Store["live"];
@@ -4,8 +4,8 @@ import type { HeldRedact } from "./redact.js";
4
4
  /** The store slice the read needs. */
5
5
  export type StoreSecretsStore = Pick<Store, "sealedSecrets">;
6
6
  /** Every secret the server keeps sealed that `sealKey` opens: the store's (one read across its planes) and, where the runner
7
- * shares the server's data directory `data`, what it keeps sealed beside the store. None without a key. */
8
- export declare function storeSecrets(store: StoreSecretsStore, sealKey: Buffer | undefined, data?: string, adapters?: readonly TriggerAdapter[]): Promise<string[]>;
7
+ * shares the server's data directory `data`, what it keeps beside the store. */
8
+ export declare function storeSecrets(store: StoreSecretsStore, sealKey: Buffer, data?: string, adapters?: readonly TriggerAdapter[]): Promise<string[]>;
9
9
  /** The server's sealed secrets (storeSecrets) held by `redact`, the run's one redactor, before any of the run's text is
10
10
  * written. */
11
- export declare function holdStored(redact: HeldRedact, store: StoreSecretsStore, sealKey: Buffer | undefined, data?: string): Promise<void>;
11
+ export declare function holdStored(redact: HeldRedact, store: StoreSecretsStore, sealKey: Buffer, data?: string): Promise<void>;
@@ -5,16 +5,14 @@
5
5
  // echoes it back. One read of the store across all its planes (store.sealedSecrets): tool, model, computer and Archil keys
6
6
  // (sealed_keys); MCP credentials, their headers' values and OAuth tokens and client secret (mcp_servers), and a sign-in in
7
7
  // flight (mcp_oauth_pending); each trigger source's settings, a webhook trigger's signing secret and the GitHub App's key
8
- // and webhook secret among them (trigger_settings), but a field its source marks public; browser sign-in pointers, live
9
- // and forgotten; live viewer tokens; a launch's sealed part. Beside the store, what the data directory keeps sealed where
10
- // the runner shares it (the server's own list, server-secrets.ts openServerSecrets: the outbound webhook's signing secret,
11
- // the trigger settings files of a server that keeps them there). Each value in every spelling the server's list has
8
+ // and webhook secret among them, and the outbound webhook's signing secret (trigger_settings), but a field its source marks public; browser sign-in pointers, live
9
+ // and forgotten; live viewer tokens; a launch's sealed part. Beside the store, what the data directory keeps where the
10
+ // runner shares it (server-secrets.ts besideTheStore: the owner's API token and the sign-in session secret). Each value in every spelling the server's list has
12
11
  // (standard-webhooks.ts secretForms), a PEM key whole and line by line. A value that does not open under the runner's key
13
12
  // is left out: the store never holds one in the clear, and nothing of this runner can be handed it.
14
- import { unseal } from "@parcha/pi-durable-agent";
15
- import { openServerSecrets, ServerSecrets } from "../server-secrets.js";
13
+ import { unseal } from "../sealing.js";
14
+ import { besideTheStore, ServerSecrets } from "../server-secrets.js";
16
15
  import { TRIGGER_ADAPTERS } from "../trigger-adapters.js";
17
- import { SEAL_KEY_ENV } from "../tool-keys.js";
18
16
  /** The keys of a sealed JSON value that hold secrets: OAuth tokens, a client's secret, a PKCE verifier. */
19
17
  const JSON_SECRETS = ["access_token", "refresh_token", "id_token", "client_secret", "verifier"];
20
18
  /** The secret strings of an opened JSON value: each header's value (a bearer's token alone too), and every string under
@@ -52,7 +50,7 @@ function jsonSecrets(text) {
52
50
  walk(value);
53
51
  return out;
54
52
  }
55
- /** A PEM key whole, and each of its base64 lines (the short last one too), as the server lists one (sealed-settings.ts). */
53
+ /** A PEM key whole, and each of its base64 lines (the short last one too), as the server lists one (sealed-settings-store.ts). */
56
54
  const pemForms = (value) => [value, ...value.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("-----"))];
57
55
  /** What of one opened sealed value is a secret to hold, by its plane: `listed` with the server list's floor and spellings,
58
56
  * `whole` as it is (a PEM key's lines). */
@@ -74,10 +72,8 @@ function secretsOf(row, plain, adapters) {
74
72
  }
75
73
  }
76
74
  /** Every secret the server keeps sealed that `sealKey` opens: the store's (one read across its planes) and, where the runner
77
- * shares the server's data directory `data`, what it keeps sealed beside the store. None without a key. */
75
+ * shares the server's data directory `data`, what it keeps beside the store. */
78
76
  export async function storeSecrets(store, sealKey, data, adapters = TRIGGER_ADAPTERS) {
79
- if (!sealKey)
80
- return [];
81
77
  const listed = [];
82
78
  const whole = [];
83
79
  for (const row of await store.sealedSecrets.all()) {
@@ -95,7 +91,7 @@ export async function storeSecrets(store, sealKey, data, adapters = TRIGGER_ADAP
95
91
  const list = new ServerSecrets();
96
92
  list.add("store", () => listed);
97
93
  list.add("store-whole", () => whole, { whole: true });
98
- const beside = data ? openServerSecrets(data, { [SEAL_KEY_ENV]: sealKey.toString("base64") }, adapters).secrets.values() : [];
94
+ const beside = data ? besideTheStore(data).values() : [];
99
95
  return [...list.values(), ...beside];
100
96
  }
101
97
  /** The server's sealed secrets (storeSecrets) held by `redact`, the run's one redactor, before any of the run's text is
@@ -0,0 +1,44 @@
1
+ type Tool = {
2
+ name: string;
3
+ description?: string;
4
+ parameters?: unknown;
5
+ };
6
+ type Part = {
7
+ type: string;
8
+ text?: string;
9
+ id?: string;
10
+ name?: string;
11
+ arguments?: unknown;
12
+ data?: string;
13
+ mimeType?: string;
14
+ };
15
+ type Message = {
16
+ role: string;
17
+ content: Part[] | string;
18
+ toolCallId?: string;
19
+ toolName?: string;
20
+ isError?: boolean;
21
+ timestamp?: number;
22
+ [key: string]: unknown;
23
+ };
24
+ /** A pi-ai context, as far as tools as text reads and writes it. */
25
+ export type PiContext = {
26
+ systemPrompt?: string;
27
+ messages: Message[];
28
+ tools?: Tool[];
29
+ };
30
+ /** The system prompt's tools section, in DeepSeek V3.2's own words: how to call, then each tool's schema. */
31
+ export declare function toolsSection(tools: readonly Tool[]): string;
32
+ /** `context` with its tools in its system prompt and every tool call and result in its history written as text. */
33
+ export declare function toolsAsText(context: PiContext): PiContext;
34
+ /** A reply's text read as text and calls: each `<tool_call>` block whose JSON names a tool, in order; the rest is
35
+ * text. A block whose JSON does not parse stays text. */
36
+ export declare function callsOfText(said: string, tools?: readonly Tool[]): {
37
+ text: string;
38
+ calls: {
39
+ name: string;
40
+ arguments: Record<string, unknown>;
41
+ }[];
42
+ broken?: boolean;
43
+ };
44
+ export {};