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

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 (466) hide show
  1. package/CHANGELOG.md +368 -0
  2. package/README.md +341 -208
  3. package/dist/adapters.d.ts +3 -4
  4. package/dist/adapters.js +18 -15
  5. package/dist/agent-rows.d.ts +99 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +75 -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/archil-settings.d.ts +11 -1
  16. package/dist/archil-settings.js +10 -0
  17. package/dist/bash-read-only.d.ts +35 -0
  18. package/dist/bash-read-only.js +778 -0
  19. package/dist/box-settings.d.ts +3 -23
  20. package/dist/box-settings.js +7 -51
  21. package/dist/boxes.d.ts +17 -0
  22. package/dist/boxes.js +27 -20
  23. package/dist/browser-commands.d.ts +5 -2
  24. package/dist/browser-commands.js +4 -4
  25. package/dist/browser-computer.d.ts +5 -0
  26. package/dist/browser-computer.js +21 -0
  27. package/dist/browser-cost.d.ts +9 -6
  28. package/dist/browser-cost.js +95 -51
  29. package/dist/browser-live.d.ts +7 -20
  30. package/dist/browser-live.js +15 -93
  31. package/dist/browser-person.d.ts +18 -51
  32. package/dist/browser-person.js +94 -277
  33. package/dist/budget.d.ts +0 -5
  34. package/dist/budget.js +0 -5
  35. package/dist/cap.d.ts +14 -8
  36. package/dist/cap.js +19 -9
  37. package/dist/cli.js +71 -18
  38. package/dist/closed-pipes.d.ts +2 -0
  39. package/dist/closed-pipes.js +13 -0
  40. package/dist/computer-commands.d.ts +2 -0
  41. package/dist/computer-commands.js +2 -0
  42. package/dist/computer-keys.d.ts +20 -10
  43. package/dist/computer-keys.js +36 -54
  44. package/dist/computer-setting.d.ts +20 -3
  45. package/dist/computer-setting.js +58 -10
  46. package/dist/computers.d.ts +35 -2
  47. package/dist/computers.js +72 -11
  48. package/dist/confine.d.ts +120 -0
  49. package/dist/confine.js +436 -0
  50. package/dist/console/assets/index-B7NKTU8E.css +1 -0
  51. package/dist/console/assets/index-CXZMgJE7.js +550 -0
  52. package/dist/console/index.html +2 -2
  53. package/dist/content-filter.d.ts +7 -0
  54. package/dist/content-filter.js +23 -0
  55. package/dist/decision-cap.d.ts +7 -29
  56. package/dist/decision-cap.js +3 -94
  57. package/dist/decision-rows.d.ts +1 -1
  58. package/dist/decision-rows.js +1 -1
  59. package/dist/docker-daemon.d.ts +31 -0
  60. package/dist/docker-daemon.js +56 -0
  61. package/dist/effort-guidance.js +4 -3
  62. package/dist/environment.d.ts +0 -3
  63. package/dist/environment.js +3 -5
  64. package/dist/errors.d.ts +1 -2
  65. package/dist/errors.js +9 -9
  66. package/dist/explain.js +3 -1
  67. package/dist/filed-answer.d.ts +32 -0
  68. package/dist/filed-answer.js +160 -0
  69. package/dist/files.d.ts +1 -3
  70. package/dist/files.js +2 -4
  71. package/dist/github-connection.d.ts +1 -1
  72. package/dist/github-connection.js +25 -7
  73. package/dist/github-faux.d.ts +26 -0
  74. package/dist/github-faux.js +76 -0
  75. package/dist/github.d.ts +6 -2
  76. package/dist/github.js +5 -3
  77. package/dist/graph-served.d.ts +5 -3
  78. package/dist/graph-served.js +14 -6
  79. package/dist/graph-view.d.ts +3 -5
  80. package/dist/graph-view.js +9 -16
  81. package/dist/handed-values.d.ts +9 -0
  82. package/dist/handed-values.js +26 -0
  83. package/dist/harness-install.d.ts +1 -7
  84. package/dist/harness-install.js +1 -18
  85. package/dist/harness-opencode/adapter.d.ts +7 -0
  86. package/dist/harness-opencode/adapter.js +23 -6
  87. package/dist/harness-opencode/harness.js +0 -1
  88. package/dist/harness-opencode/host/policy.js +2 -2
  89. package/dist/harness-opencode/index.d.ts +1 -1
  90. package/dist/harness-opencode/index.js +1 -1
  91. package/dist/harness-opencode/verify.d.ts +17 -0
  92. package/dist/harness-opencode/verify.js +30 -10
  93. package/dist/harness-table.js +6 -1
  94. package/dist/heard.js +1 -1
  95. package/dist/held-fd.d.ts +5 -0
  96. package/dist/held-fd.js +14 -0
  97. package/dist/host-calls.d.ts +20 -0
  98. package/dist/host-calls.js +12 -0
  99. package/dist/host-tools.d.ts +4 -21
  100. package/dist/host-tools.js +4 -61
  101. package/dist/host.d.ts +2 -4
  102. package/dist/host.js +2 -7
  103. package/dist/import-summary.d.ts +1 -5
  104. package/dist/import-summary.js +0 -21
  105. package/dist/import.d.ts +6 -6
  106. package/dist/import.js +14 -15
  107. package/dist/index.d.ts +1 -0
  108. package/dist/index.js +1 -0
  109. package/dist/key-refusal.d.ts +5 -1
  110. package/dist/key-refusal.js +19 -4
  111. package/dist/learn/check.d.ts +8 -2
  112. package/dist/learn/check.js +85 -31
  113. package/dist/learn/folder.d.ts +11 -4
  114. package/dist/learn/folder.js +17 -19
  115. package/dist/learn/grade.d.ts +18 -1
  116. package/dist/learn/grade.js +108 -14
  117. package/dist/learn/index.d.ts +5 -5
  118. package/dist/learn/index.js +5 -5
  119. package/dist/learn/learning.sh +1 -14
  120. package/dist/learn/notes.d.ts +14 -3
  121. package/dist/learn/notes.js +16 -6
  122. package/dist/learn/reflect.d.ts +31 -2
  123. package/dist/learn/reflect.js +83 -6
  124. package/dist/learn/relevance.d.ts +24 -0
  125. package/dist/learn/relevance.js +91 -0
  126. package/dist/learn/secrets.d.ts +7 -1
  127. package/dist/learn/secrets.js +86 -19
  128. package/dist/learn/skills.d.ts +159 -18
  129. package/dist/learn/skills.js +644 -64
  130. package/dist/learned-nodes.d.ts +14 -0
  131. package/dist/learned-nodes.js +8 -0
  132. package/dist/learned-workflow.d.ts +41 -6
  133. package/dist/learned-workflow.js +153 -18
  134. package/dist/learning-routes.d.ts +49 -4
  135. package/dist/learning-routes.js +113 -31
  136. package/dist/learning-run.d.ts +16 -31
  137. package/dist/learning-run.js +31 -38
  138. package/dist/learning-words.d.ts +12 -5
  139. package/dist/learning-words.js +18 -9
  140. package/dist/learning.d.ts +91 -97
  141. package/dist/learning.js +176 -320
  142. package/dist/live/stream.js +1 -1
  143. package/dist/live/translate.js +12 -2
  144. package/dist/llm.d.ts +4 -1
  145. package/dist/llm.js +4 -2
  146. package/dist/local-models.d.ts +11 -5
  147. package/dist/local-models.js +13 -8
  148. package/dist/mcp-gateway.d.ts +17 -49
  149. package/dist/mcp-gateway.js +55 -136
  150. package/dist/mcp-oauth.d.ts +10 -14
  151. package/dist/mcp-oauth.js +14 -32
  152. package/dist/mcp-probe.d.ts +0 -7
  153. package/dist/mcp-probe.js +4 -10
  154. package/dist/mcp-servers-store.d.ts +18 -18
  155. package/dist/mcp-servers-store.js +12 -14
  156. package/dist/mcp-store.js +3 -4
  157. package/dist/mcp.js +4 -3
  158. package/dist/model.d.ts +9 -7
  159. package/dist/model.js +51 -27
  160. package/dist/monid.d.ts +0 -2
  161. package/dist/monid.js +3 -6
  162. package/dist/openapi.d.ts +8 -1
  163. package/dist/openapi.js +156 -58
  164. package/dist/page.d.ts +1 -3
  165. package/dist/page.js +6 -18
  166. package/dist/paid-calls.d.ts +21 -27
  167. package/dist/paid-calls.js +26 -61
  168. package/dist/pause.d.ts +2 -19
  169. package/dist/pause.js +5 -74
  170. package/dist/port-models.d.ts +10 -3
  171. package/dist/port-models.js +26 -6
  172. package/dist/propose.d.ts +2 -0
  173. package/dist/propose.js +80 -45
  174. package/dist/push-handler.d.ts +1 -1
  175. package/dist/reflect-range.d.ts +25 -0
  176. package/dist/reflect-range.js +30 -0
  177. package/dist/refusal-words.d.ts +5 -1
  178. package/dist/refusal-words.js +5 -1
  179. package/dist/rows.d.ts +1 -1
  180. package/dist/run-cut.d.ts +0 -6
  181. package/dist/run-cut.js +0 -6
  182. package/dist/run-db.d.ts +2 -11
  183. package/dist/run-db.js +2 -37
  184. package/dist/run-launch.d.ts +21 -2
  185. package/dist/run-launch.js +14 -5
  186. package/dist/run-learning-served.d.ts +21 -4
  187. package/dist/run-learning-served.js +23 -13
  188. package/dist/run-reads-over-store.d.ts +5 -3
  189. package/dist/run-reads-over-store.js +25 -14
  190. package/dist/run-secrets.d.ts +1 -1
  191. package/dist/run-timeline-served.d.ts +5 -1
  192. package/dist/run-timeline-served.js +27 -6
  193. package/dist/run-view.d.ts +37 -22
  194. package/dist/run-view.js +85 -38
  195. package/dist/runnable.d.ts +21 -10
  196. package/dist/runnable.js +35 -12
  197. package/dist/runner/adapter-loop.d.ts +36 -5
  198. package/dist/runner/adapter-loop.js +663 -69
  199. package/dist/runner/adapter-run-spec.d.ts +42 -8
  200. package/dist/runner/adapter-run-spec.js +186 -52
  201. package/dist/runner/adapters/index.js +11 -1
  202. package/dist/runner/adapters/pi.d.ts +40 -2
  203. package/dist/runner/adapters/pi.js +110 -27
  204. package/dist/runner/beside.d.ts +38 -3
  205. package/dist/runner/beside.js +54 -5
  206. package/dist/runner/claim-secrets.d.ts +16 -1
  207. package/dist/runner/claim-secrets.js +62 -14
  208. package/dist/runner/cli-run-spec.d.ts +5 -0
  209. package/dist/runner/cli-run-spec.js +159 -41
  210. package/dist/runner/commands.js +1 -1
  211. package/dist/runner/computer-journal.d.ts +15 -2
  212. package/dist/runner/computer-journal.js +41 -5
  213. package/dist/runner/conformance/harness.d.ts +1 -0
  214. package/dist/runner/conformance/harness.js +123 -13
  215. package/dist/runner/conformance/subject.d.ts +4 -1
  216. package/dist/runner/dispatch.d.ts +8 -1
  217. package/dist/runner/dispatch.js +81 -7
  218. package/dist/runner/end-of-run.d.ts +8 -2
  219. package/dist/runner/end-of-run.js +10 -4
  220. package/dist/runner/github-app.d.ts +7 -2
  221. package/dist/runner/github-app.js +47 -16
  222. package/dist/runner/harness-loops.d.ts +15 -2
  223. package/dist/runner/harness-loops.js +38 -2
  224. package/dist/runner/journal-kinds.d.ts +60 -6
  225. package/dist/runner/journal-kinds.js +43 -5
  226. package/dist/runner/journal-reader.d.ts +1 -1
  227. package/dist/runner/journal-reader.js +2 -2
  228. package/dist/runner/learning-ask.d.ts +4 -0
  229. package/dist/runner/learning-ask.js +15 -1
  230. package/dist/runner/learning-end.d.ts +18 -3
  231. package/dist/runner/learning-end.js +194 -20
  232. package/dist/runner/learning-loop.d.ts +7 -0
  233. package/dist/runner/learning-loop.js +36 -8
  234. package/dist/runner/learning-seed.d.ts +6 -0
  235. package/dist/runner/learning-seed.js +6 -0
  236. package/dist/runner/loop-contract.d.ts +4 -0
  237. package/dist/runner/main.d.ts +61 -9
  238. package/dist/runner/main.js +144 -20
  239. package/dist/runner/mcp-claim.d.ts +3 -0
  240. package/dist/runner/mcp-claim.js +7 -3
  241. package/dist/runner/mcp-github.d.ts +11 -2
  242. package/dist/runner/mcp-github.js +55 -4
  243. package/dist/runner/mcp-run.d.ts +2 -0
  244. package/dist/runner/mcp-run.js +16 -5
  245. package/dist/runner/memory-claim.d.ts +9 -0
  246. package/dist/runner/memory-claim.js +25 -0
  247. package/dist/runner/metrics.d.ts +46 -1
  248. package/dist/runner/metrics.js +156 -1
  249. package/dist/runner/model-route.d.ts +16 -0
  250. package/dist/runner/model-route.js +134 -10
  251. package/dist/runner/reflect-hook.d.ts +12 -1
  252. package/dist/runner/reflect-hook.js +33 -3
  253. package/dist/runner/runner.d.ts +20 -0
  254. package/dist/runner/runner.js +146 -18
  255. package/dist/runner/spec-holds.d.ts +7 -2
  256. package/dist/runner/spec-holds.js +4 -3
  257. package/dist/runner/store-port.d.ts +1 -1
  258. package/dist/runner/store-secrets.d.ts +3 -3
  259. package/dist/runner/store-secrets.js +8 -12
  260. package/dist/runner/text-tools.d.ts +44 -0
  261. package/dist/runner/text-tools.js +237 -0
  262. package/dist/runner/workflow-host.d.ts +7 -2
  263. package/dist/runner/workflow-host.js +3 -1
  264. package/dist/runner/workflow-loop.d.ts +10 -1
  265. package/dist/runner/workflow-loop.js +14 -6
  266. package/dist/runner/workflow-spec.d.ts +21 -0
  267. package/dist/runner/workflow-spec.js +217 -93
  268. package/dist/runs-over-store.d.ts +14 -3
  269. package/dist/runs-over-store.js +100 -23
  270. package/dist/seal-key.d.ts +0 -2
  271. package/dist/seal-key.js +5 -45
  272. package/dist/sealed-settings-store.d.ts +19 -4
  273. package/dist/sealed-settings-store.js +9 -9
  274. package/dist/sealing.d.ts +4 -0
  275. package/dist/sealing.js +20 -0
  276. package/dist/secret-cut.d.ts +1 -1
  277. package/dist/secret-cut.js +1 -1
  278. package/dist/secret-name.d.ts +9 -0
  279. package/dist/secret-name.js +15 -0
  280. package/dist/secret-writes.d.ts +0 -1
  281. package/dist/secret-writes.js +0 -1
  282. package/dist/server-fs.d.ts +4 -0
  283. package/dist/server-fs.js +8 -2
  284. package/dist/server-lock.d.ts +0 -24
  285. package/dist/server-lock.js +5 -85
  286. package/dist/server-secrets-store.d.ts +4 -4
  287. package/dist/server-secrets-store.js +9 -31
  288. package/dist/server-secrets.d.ts +4 -9
  289. package/dist/server-secrets.js +12 -36
  290. package/dist/server.d.ts +37 -56
  291. package/dist/server.js +322 -134
  292. package/dist/sign-ins-store.d.ts +34 -36
  293. package/dist/sign-ins-store.js +27 -38
  294. package/dist/sign-ins.d.ts +2 -119
  295. package/dist/sign-ins.js +5 -311
  296. package/dist/standard-webhooks.d.ts +1 -1
  297. package/dist/standard-webhooks.js +1 -1
  298. package/dist/stats.d.ts +3 -2
  299. package/dist/stats.js +1 -1
  300. package/dist/stop-signals.d.ts +4 -2
  301. package/dist/stop-signals.js +5 -3
  302. package/dist/store/agent-body.d.ts +12 -2
  303. package/dist/store/agent-body.js +22 -4
  304. package/dist/store/deadline.d.ts +18 -0
  305. package/dist/store/deadline.js +45 -0
  306. package/dist/store/index.d.ts +2 -2
  307. package/dist/store/index.js +2 -2
  308. package/dist/store/open.d.ts +6 -3
  309. package/dist/store/open.js +2 -2
  310. package/dist/store/postgres/connection.d.ts +22 -2
  311. package/dist/store/postgres/connection.js +211 -41
  312. package/dist/store/postgres/migrate.d.ts +4 -0
  313. package/dist/store/postgres/migrate.js +9 -2
  314. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  315. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  316. package/dist/store/postgres/store.d.ts +9 -2
  317. package/dist/store/postgres/store.js +9 -0
  318. package/dist/store/schema.js +1 -1
  319. package/dist/store/seal.js +2 -2
  320. package/dist/store/sqlite/connection.js +14 -5
  321. package/dist/store/sqlite/run-patch.d.ts +3 -0
  322. package/dist/store/sqlite/run-patch.js +3 -0
  323. package/dist/store/sqlite/store.js +41 -12
  324. package/dist/store/store.d.ts +35 -6
  325. package/dist/store/store.js +12 -2
  326. package/dist/store-reads/cap.d.ts +1 -1
  327. package/dist/store-reads/cap.js +22 -4
  328. package/dist/store-reads/journal.d.ts +9 -6
  329. package/dist/store-reads/journal.js +129 -18
  330. package/dist/store-reads/learning.d.ts +82 -8
  331. package/dist/store-reads/learning.js +184 -11
  332. package/dist/store-reads/workflow.d.ts +1 -1
  333. package/dist/store-reads/workflow.js +1 -1
  334. package/dist/store-view.d.ts +19 -1
  335. package/dist/store-view.js +95 -27
  336. package/dist/template-eval.d.ts +60 -4
  337. package/dist/template-eval.js +120 -54
  338. package/dist/templates.d.ts +33 -14
  339. package/dist/templates.js +82 -46
  340. package/dist/timeline/group.d.ts +33 -0
  341. package/dist/timeline/group.js +77 -0
  342. package/dist/timeline/index.d.ts +7 -0
  343. package/dist/timeline/index.js +7 -0
  344. package/dist/timeline/labels.d.ts +79 -0
  345. package/dist/timeline/labels.js +150 -0
  346. package/dist/timeline/origin.d.ts +56 -0
  347. package/dist/timeline/origin.js +92 -0
  348. package/dist/timeline/render-text.d.ts +11 -0
  349. package/dist/timeline/render-text.js +62 -0
  350. package/dist/timeline/timeline.d.ts +282 -0
  351. package/dist/timeline/timeline.js +1308 -0
  352. package/dist/timeline/util.d.ts +17 -0
  353. package/dist/timeline/util.js +49 -0
  354. package/dist/tool-budget.d.ts +18 -0
  355. package/dist/tool-budget.js +50 -0
  356. package/dist/tool-gate.d.ts +47 -218
  357. package/dist/tool-gate.js +87 -545
  358. package/dist/tool-keys-store.d.ts +11 -12
  359. package/dist/tool-keys-store.js +24 -31
  360. package/dist/tool-keys.d.ts +5 -101
  361. package/dist/tool-keys.js +8 -267
  362. package/dist/tool-plane.d.ts +23 -52
  363. package/dist/tool-plane.js +23 -81
  364. package/dist/tool-settings-store.d.ts +1 -2
  365. package/dist/tool-settings-store.js +5 -8
  366. package/dist/tools.d.ts +67 -25
  367. package/dist/tools.js +170 -119
  368. package/dist/trigger-adapter.d.ts +2 -2
  369. package/dist/trigger-targets.d.ts +13 -1
  370. package/dist/trigger-targets.js +31 -1
  371. package/dist/triggers.d.ts +2 -2
  372. package/dist/triggers.js +3 -3
  373. package/dist/turn-end.d.ts +1 -1
  374. package/dist/turn-end.js +1 -1
  375. package/dist/turns.d.ts +0 -6
  376. package/dist/turns.js +0 -19
  377. package/dist/uploads.d.ts +28 -5
  378. package/dist/uploads.js +83 -10
  379. package/dist/usage.d.ts +1 -49
  380. package/dist/usage.js +3 -84
  381. package/dist/validate.d.ts +4 -0
  382. package/dist/validate.js +33 -14
  383. package/dist/webhooks.d.ts +102 -76
  384. package/dist/webhooks.js +266 -233
  385. package/dist/workflow-run.d.ts +114 -0
  386. package/dist/workflow-run.js +144 -0
  387. package/dist/workspace/archil-claim.d.ts +2 -2
  388. package/dist/workspace/archil-claim.js +4 -3
  389. package/dist/workspace/archil-disk.d.ts +10 -1
  390. package/dist/workspace/archil-disk.js +4 -0
  391. package/dist/workspace/archil-exec.d.ts +12 -2
  392. package/dist/workspace/archil-exec.js +16 -0
  393. package/dist/workspace/archil.d.ts +2 -2
  394. package/dist/workspace/archil.js +25 -5
  395. package/dist/workspace/attach.js +2 -0
  396. package/dist/workspace/beneath.d.ts +19 -0
  397. package/dist/workspace/beneath.js +106 -0
  398. package/dist/workspace/computer-deps.d.ts +26 -9
  399. package/dist/workspace/computer-deps.js +144 -43
  400. package/dist/workspace/computer-for-claim.d.ts +17 -14
  401. package/dist/workspace/computer-for-claim.js +99 -26
  402. package/dist/workspace/computer-hold.d.ts +6 -1
  403. package/dist/workspace/computer-hold.js +6 -1
  404. package/dist/workspace/computer-janitor.d.ts +47 -0
  405. package/dist/workspace/computer-janitor.js +182 -0
  406. package/dist/workspace/computer-ledger.d.ts +1 -8
  407. package/dist/workspace/computer-ledger.js +0 -3
  408. package/dist/workspace/computer-providers.d.ts +5 -3
  409. package/dist/workspace/computer-providers.js +11 -9
  410. package/dist/workspace/grep-worker.d.ts +5 -0
  411. package/dist/workspace/grep-worker.js +9 -6
  412. package/dist/workspace/hands.d.ts +5 -2
  413. package/dist/workspace/hands.js +4 -3
  414. package/dist/workspace/index.d.ts +6 -5
  415. package/dist/workspace/index.js +4 -4
  416. package/dist/workspace/local.d.ts +14 -2
  417. package/dist/workspace/local.js +170 -43
  418. package/dist/workspace/paths.js +3 -2
  419. package/dist/workspace/pi-env.d.ts +4 -0
  420. package/dist/workspace/pi-env.js +3 -2
  421. package/dist/workspace/resolve-computer.d.ts +55 -10
  422. package/dist/workspace/resolve-computer.js +66 -14
  423. package/dist/workspace/run-tools.d.ts +15 -31
  424. package/dist/workspace/run-tools.js +19 -30
  425. package/dist/workspace/workspace.d.ts +5 -0
  426. package/dist/workspace-paths.d.ts +0 -17
  427. package/dist/workspace-paths.js +1 -41
  428. package/dist/workspace.d.ts +0 -17
  429. package/dist/workspace.js +4 -110
  430. package/package.json +14 -14
  431. package/skills/agentrun-serve/SKILL.md +1 -1
  432. package/templates/README.md +11 -5
  433. package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
  434. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
  435. package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
  436. package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
  437. package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
  438. package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
  439. package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
  440. package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
  441. package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
  442. package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
  443. package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
  444. package/templates/market-monitor/agent.md +2 -2
  445. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  446. package/templates/release-notes/agent.md +11 -0
  447. package/dist/bound-files.d.ts +0 -4
  448. package/dist/bound-files.js +0 -164
  449. package/dist/coding-tools.d.ts +0 -47
  450. package/dist/coding-tools.js +0 -189
  451. package/dist/computer-adb.d.ts +0 -12
  452. package/dist/computer-adb.js +0 -14
  453. package/dist/console/assets/index-Dn0ngwG9.js +0 -535
  454. package/dist/console/assets/index-DvW6Aled.css +0 -1
  455. package/dist/grade.d.ts +0 -63
  456. package/dist/grade.js +0 -150
  457. package/dist/mcp-servers.d.ts +0 -269
  458. package/dist/mcp-servers.js +0 -456
  459. package/dist/packs.d.ts +0 -71
  460. package/dist/packs.js +0 -180
  461. package/dist/sealed-settings.d.ts +0 -60
  462. package/dist/sealed-settings.js +0 -171
  463. package/dist/sessions.d.ts +0 -6
  464. package/dist/sessions.js +0 -109
  465. package/dist/workspace/computer-serves.d.ts +0 -12
  466. package/dist/workspace/computer-serves.js +0 -15
@@ -1,4 +1,45 @@
1
- import { type DecisionLike, type EntryLike, type RunMetrics } from "@parcha/pi-durable-agent/timeline";
1
+ import { type DecisionLike, type EntryLike, type RunMetrics } from "../timeline/index.js";
2
+ /** What a run's booking says one of its sessions spent: its requests (a hold given back unused is none), their known
3
+ * sum, how many have no known cost, their tokens, and how many of the requests have no known tokens (`unmetered`: booked
4
+ * with no usage, or sent and never answered), in no token sum; and its requests by the model each was sent on (`models`:
5
+ * its runner.request's model, "" for one that names none). */
6
+ export type BookedSpend = {
7
+ readonly usd: number | null;
8
+ readonly known: number;
9
+ readonly unpriced: number;
10
+ readonly requests: number;
11
+ readonly unmetered: number;
12
+ readonly models: Readonly<Record<string, number>>;
13
+ readonly tokens: {
14
+ input: number;
15
+ output: number;
16
+ cacheRead: number;
17
+ cacheWrite: number;
18
+ };
19
+ };
20
+ /** What the run's booking (the kernel's runner.request and runner.turn records, the model proxy's own) says its requests
21
+ * cost, over `entries`, every conversation of the run's journal: its model requests (`model`: every session but the
22
+ * paid-tools one, TOOL_SESSION, and the decisions one, DECISION_SESSION), its paid tool calls (`paid`: the paid-tools
23
+ * session alone), or its decisions (`decisions`: that session alone, which their receipts also show, so no usage row
24
+ * counts them twice). Each request at what it was booked at (`bookedUsd`, else its `usd`); one booked at no known cost,
25
+ * or with no runner.turn yet (in flight, or cut off by a crash before its answer was booked), makes the sum unknown
26
+ * (null), its known part kept, as sessionSpendOf counts it. A CLI harness's own record carries no per-request cost, nor do
27
+ * a workflow's model nodes (pi-ai's $0 for a model it has no price for): their model requests' cost is this, the
28
+ * booking's. */
29
+ export declare function bookedSpend(entries: readonly EntryLike[], which: "model" | "paid" | "decisions"): BookedSpend;
30
+ /** Whether a run's record carries no cost of its own, so its usage row and its live spend are its booking's: a CLI
31
+ * harness's record (`cli`), or a workflow's (its model nodes' answers carry pi-ai's $0). A pi run's answers carry their
32
+ * booking (adapters/pi.ts afterResponse). */
33
+ export declare function costIsBooked(entries: readonly EntryLike[], cli: boolean): boolean;
34
+ /** What the run has spent as its cap reads it (the kernel's sessionSpendOf over every session's records: a request still
35
+ * out at its hold and bound), for a run whose cost is its booking: the runs list's figure while it runs. Null when one
36
+ * session's is unknown, never 0 for it. */
37
+ export declare function bookedCapSpend(entries: readonly EntryLike[]): number | null;
38
+ /** The bound of a run's requests since its spend last fit under `capUsd`, as the kernel's overCapOf reads it: each model
39
+ * request, in each model session's order, at the figure the cap counts it at, after what the paid tools and decisions
40
+ * spent; reset to 0 whenever the spend fits, else grown by each request's bound. What its over-cap row (run-view.ts
41
+ * withOverCap) reads to tell a cache miss within that bound from a run that spent past its cap. 0 when nothing ran. */
42
+ export declare function overCapBound(entries: readonly EntryLike[], capUsd: number): number;
2
43
  /** A run's metrics as the end commit writes them (the StoredMetrics JSON on the run row): the timeline's count, with the
3
44
  * effort the run ran at and, on a harness other than pi, the model its revision named. */
4
45
  export type RunMetricsStored = RunMetrics & {
@@ -16,3 +57,7 @@ export declare function runMetrics(entries: readonly EntryLike[], options?: {
16
57
  metrics: RunMetricsStored;
17
58
  costUsd: number | null;
18
59
  };
60
+ export declare function cliRunMetrics(rootEntries: readonly EntryLike[], booked: BookedSpend, options: {
61
+ readonly effort?: string;
62
+ readonly model: string;
63
+ }): RunMetricsStored;
@@ -7,7 +7,137 @@
7
7
  // A pi run has no workflow decision receipts, so the decisions list is empty; a workflow run (when it joins the runner)
8
8
  // passes its decisions. `effort` is the level the run ran at and `model`, on a harness other than pi, the model its
9
9
  // revision named — both as storedMetrics added them, resolved by the caller from the run's launch and harness.
10
- import { runMetricsWithDecisions, timelineOf } from "@parcha/pi-durable-agent/timeline";
10
+ import { runMetricsWithDecisions, timelineOf } from "../timeline/index.js";
11
+ import { answeredUnpriced, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
12
+ import { DECISION_SESSION, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
13
+ import { KINDS, WORKFLOW_SESSION } from "./journal-kinds.js";
14
+ import { anthropicModelId } from "../provider.js";
15
+ /** The conversation each of the run's sessions books in, by its key: the first `agentrun.session.key` entry naming it. */
16
+ function sessionConversations(entries) {
17
+ const out = new Map();
18
+ for (const e of entries) {
19
+ if (e.kind !== KINDS.sessionKey)
20
+ continue;
21
+ const d = (e.data ?? {});
22
+ if (typeof d.key === "string" && !out.has(d.key) && Number.isFinite(Number(d.conversation)))
23
+ out.set(d.key, Number(d.conversation));
24
+ }
25
+ return out;
26
+ }
27
+ /** What the run's booking (the kernel's runner.request and runner.turn records, the model proxy's own) says its requests
28
+ * cost, over `entries`, every conversation of the run's journal: its model requests (`model`: every session but the
29
+ * paid-tools one, TOOL_SESSION, and the decisions one, DECISION_SESSION), its paid tool calls (`paid`: the paid-tools
30
+ * session alone), or its decisions (`decisions`: that session alone, which their receipts also show, so no usage row
31
+ * counts them twice). Each request at what it was booked at (`bookedUsd`, else its `usd`); one booked at no known cost,
32
+ * or with no runner.turn yet (in flight, or cut off by a crash before its answer was booked), makes the sum unknown
33
+ * (null), its known part kept, as sessionSpendOf counts it. A CLI harness's own record carries no per-request cost, nor do
34
+ * a workflow's model nodes (pi-ai's $0 for a model it has no price for): their model requests' cost is this, the
35
+ * booking's. */
36
+ export function bookedSpend(entries, which) {
37
+ const keyed = sessionConversations(entries);
38
+ const paidConv = keyed.get(TOOL_SESSION);
39
+ const decisionsConv = keyed.get(DECISION_SESSION);
40
+ const conv = (e) => Number(e.conversationId);
41
+ const chosen = (e) => (which === "paid" ? conv(e) === paidConv : which === "decisions" ? conv(e) === decisionsConv : conv(e) !== paidConv && conv(e) !== decisionsConv);
42
+ const turnOf = (e) => `${String(e.conversationId)}:${String(e.data?.turn)}`;
43
+ const answered = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.turn && chosen(e)).map(turnOf));
44
+ // The model each request was sent on, by its turn (its runner.request's `model`).
45
+ const sentOn = new Map(entries.filter((e) => e.kind === RUNNER_RECORDS.request && chosen(e)).map((e) => [turnOf(e), e.data?.model]));
46
+ const models = {};
47
+ const count = (e) => {
48
+ const model = sentOn.get(turnOf(e));
49
+ const name = typeof model === "string" ? model : "";
50
+ models[name] = (models[name] ?? 0) + 1;
51
+ };
52
+ let known = 0;
53
+ let unpriced = 0;
54
+ let requests = 0;
55
+ let unmetered = 0;
56
+ const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
57
+ for (const e of entries) {
58
+ if (!chosen(e))
59
+ continue;
60
+ if (e.kind === RUNNER_RECORDS.request && !answered.has(turnOf(e))) {
61
+ requests += 1;
62
+ count(e);
63
+ unpriced += 1;
64
+ unmetered += 1;
65
+ continue;
66
+ }
67
+ if (e.kind !== RUNNER_RECORDS.turn)
68
+ continue;
69
+ const d = (e.data ?? {});
70
+ if (d.givenBack === true || d.unsent === true)
71
+ continue;
72
+ requests += 1;
73
+ count(e);
74
+ // An answer with no price of its own was booked at its hold for the cap (answeredUnpriced): as a cost it is unknown.
75
+ const usd = answeredUnpriced(d) ? null : typeof d.bookedUsd === "number" && Number.isFinite(d.bookedUsd) ? d.bookedUsd : typeof d.usd === "number" && Number.isFinite(d.usd) ? d.usd : null;
76
+ if (usd === null)
77
+ unpriced += 1;
78
+ else
79
+ known += usd;
80
+ // The booking keeps a request's usage only when it reported some (runner.ts tokensOf): one with none is unmetered.
81
+ if (d.usage === undefined)
82
+ unmetered += 1;
83
+ for (const key of Object.keys(tokens))
84
+ if (typeof d.usage?.[key] === "number")
85
+ tokens[key] += d.usage[key];
86
+ }
87
+ return { usd: unpriced ? null : known, known, unpriced, requests, unmetered, models, tokens };
88
+ }
89
+ /** Whether a run's record carries no cost of its own, so its usage row and its live spend are its booking's: a CLI
90
+ * harness's record (`cli`), or a workflow's (its model nodes' answers carry pi-ai's $0). A pi run's answers carry their
91
+ * booking (adapters/pi.ts afterResponse). */
92
+ export function costIsBooked(entries, cli) {
93
+ return cli || sessionConversations(entries).has(WORKFLOW_SESSION);
94
+ }
95
+ /** What the run has spent as its cap reads it (the kernel's sessionSpendOf over every session's records: a request still
96
+ * out at its hold and bound), for a run whose cost is its booking: the runs list's figure while it runs. Null when one
97
+ * session's is unknown, never 0 for it. */
98
+ export function bookedCapSpend(entries) {
99
+ let spent = 0;
100
+ // Every conversation that holds booking records, keyed or not, as bookedSpend reads them.
101
+ const booking = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn).map((e) => Number(e.conversationId)));
102
+ for (const conversation of booking) {
103
+ const records = entries.filter((e) => Number(e.conversationId) === conversation && e.kind !== KINDS.sessionKey).map((e) => ({ kind: e.kind, data: (e.data ?? null) }));
104
+ const read = sessionSpendOf(records).spentUsd;
105
+ if (read === null)
106
+ return null;
107
+ spent += read;
108
+ }
109
+ return spent;
110
+ }
111
+ /** The bound of a run's requests since its spend last fit under `capUsd`, as the kernel's overCapOf reads it: each model
112
+ * request, in each model session's order, at the figure the cap counts it at, after what the paid tools and decisions
113
+ * spent; reset to 0 whenever the spend fits, else grown by each request's bound. What its over-cap row (run-view.ts
114
+ * withOverCap) reads to tell a cache miss within that bound from a run that spent past its cap. 0 when nothing ran. */
115
+ export function overCapBound(entries, capUsd) {
116
+ const keyed = sessionConversations(entries);
117
+ const paidConv = keyed.get(TOOL_SESSION);
118
+ const decisionsConv = keyed.get(DECISION_SESSION);
119
+ const others = [paidConv, decisionsConv].reduce((sum, conversation) => {
120
+ if (conversation === undefined)
121
+ return sum;
122
+ const read = sessionSpendOf(recordsIn(entries, conversation)).spentUsd;
123
+ return sum + (read ?? 0);
124
+ }, 0);
125
+ const booking = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn).map((e) => Number(e.conversationId)));
126
+ let running = others;
127
+ let bound = 0;
128
+ for (const conversation of booking) {
129
+ if (conversation === paidConv || conversation === decisionsConv)
130
+ continue;
131
+ const read = sessionSpendOf(recordsIn(entries, conversation));
132
+ for (const { turn, usd } of read.figures) {
133
+ running += usd ?? 0;
134
+ bound = running <= capUsd ? 0 : bound + (read.bounds.get(turn) ?? 0);
135
+ }
136
+ }
137
+ return bound;
138
+ }
139
+ /** The booking records of `conversation`, as the kernel's session readers take them. */
140
+ const recordsIn = (entries, conversation) => entries.filter((e) => Number(e.conversationId) === conversation && e.kind !== KINDS.sessionKey).map((e) => ({ kind: e.kind, data: (e.data ?? null) }));
11
141
  /** The run's metrics and cost from its journal `entries`. `decisions`: a workflow run's receipts (none for pi).
12
142
  * `effort`/`model`: the enrichment the old storedMetrics added. `costUsd` is the usage row's cost: null when a
13
143
  * response's cost is unknown, 0 before any request (costOf). */
@@ -22,3 +152,28 @@ export function runMetrics(entries, options = {}) {
22
152
  costUsd,
23
153
  };
24
154
  }
155
+ /** A CLI harness's run (its record the loop's: claude-agent, codex, opencode): its metrics from `rootEntries`, its root
156
+ * conversation's record (its tools), with its tokens and model requests those of `booked`, its booking's (bookedSpend
157
+ * "model", which the caller reads once for the run's cost too: what its model proxy booked each request at,
158
+ * runner.turn's usage), since the harness's own record carries none; each request counted at `model`, the model its
159
+ * run chose. Tokens are not a price: a request answered at no known price, with its usage, is metered all the same. */
160
+ /** `byModel` (a booking's requests by the model each was sent on) under the names a run's metrics use: the run's own
161
+ * model, and a request that names none, as `run` (the model it chose, `provider/model`, through OpenRouter or dotted
162
+ * too); any other (a learned node's tier, the hosted search's model) as its request names it. A booked name is the run's
163
+ * when it is one model by the router's match: its last segment, dots as dashes (provider.ts anthropicModelId: the
164
+ * booking names Anthropic's id, claude-haiku-4-5, for a run that chose openrouter/anthropic/claude-haiku-4.5). */
165
+ function modelsOf(byModel, run) {
166
+ const same = (name) => anthropicModelId({ provider: "anthropic", modelId: name.slice(name.lastIndexOf("/") + 1) });
167
+ const own = same(run);
168
+ const out = {};
169
+ for (const [model, n] of Object.entries(byModel)) {
170
+ const name = model === "" || same(model) === own ? run : model;
171
+ out[name] = (out[name] ?? 0) + n;
172
+ }
173
+ return out;
174
+ }
175
+ export function cliRunMetrics(rootEntries, booked, options) {
176
+ const { metrics: counted } = runMetrics(rootEntries, options);
177
+ const { tokens } = booked;
178
+ return { ...counted, input: tokens.input, output: tokens.output, cacheRead: tokens.cacheRead, cacheWrite: tokens.cacheWrite, requests: booked.requests, unmetered: booked.unmetered, models: modelsOf(booked.models, options.model) };
179
+ }
@@ -1,4 +1,5 @@
1
1
  import type { Wire } from "@parcha/agentrun-kernel";
2
+ import type { ToolsAs } from "../local-models.js";
2
3
  import { type PinnedModel, type Tier } from "../model.js";
3
4
  import { type Redact } from "./redact.js";
4
5
  /** What a request on a model costs, USD per million tokens, as pi-ai's catalog lists it (tiers included). */
@@ -35,6 +36,9 @@ export interface ModelRoute {
35
36
  readonly auth?: "bearer" | "x-api-key";
36
37
  };
37
38
  readonly model: string;
39
+ /** The model as the run names it (`provider/model-id`, chooseModel's): what the `llm` tool's answer says it ran on,
40
+ * never the session provider the runner reaches it through. */
41
+ readonly named?: string;
38
42
  /** The catalog's entry for the model, as pi-ai's model of it takes it: on every wire, what it takes as input (whether it
39
43
  * takes images) and its input limits (an image's most size), which pi's session and its read size an image by; on a
40
44
  * wire that carries its reasoning (Responses), also whether it reasons, its window and its output ceiling. */
@@ -67,6 +71,7 @@ type PiModel = {
67
71
  contextWindow?: number;
68
72
  input?: readonly string[];
69
73
  inputLimits?: unknown;
74
+ toolsAs?: ToolsAs;
70
75
  };
71
76
  type PiModels = {
72
77
  getModel(provider: string, id: string): unknown;
@@ -96,6 +101,11 @@ type PiMessage = {
96
101
  usage?: RouteUsage;
97
102
  stopReason?: string;
98
103
  errorMessage?: string;
104
+ content?: {
105
+ type: string;
106
+ text?: string;
107
+ thinking?: string;
108
+ }[];
99
109
  };
100
110
  /** The route of `model` ("provider/model-id"; undefined for the host's model of `tier`; a claimed run's pin, sent as
101
111
  * pinned: chooseModel's PinnedModel), resolved from `env` as main resolves a run's model, on a wire of `wires` (the
@@ -108,4 +118,10 @@ export declare function routeOf(model: string | PinnedModel | undefined, env?: N
108
118
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
109
119
  * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
110
120
  export declare function messagesFetch(models: PiModels, target: PiModel, redact?: Redact, upstream?: typeof fetch): typeof fetch;
121
+ /** 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
122
+ * `leftUsd` (its first try's input as it was billed and its output limit `outputHeld`, less every try so far) and its
123
+ * input, the prompt `last` was asked with, is priced uncached at the dearer of the input and cache-write prices, as the
124
+ * cap prices a fresh input. Never more than `outputHeld`; 0 when nothing is left. So the one hold the cap took for
125
+ * the request covers every try it makes. */
126
+ export declare function reaskTokens(target: PiModel, last: RouteUsage, leftUsd: number, outputHeld: number): number;
111
127
  export {};
@@ -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,18 +33,17 @@ 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 } : {}) };
43
- const route = { model: chosen.model.modelId, price, cost: target.cost, outputCeiling: target.maxTokens ?? null, like: sees };
46
+ const route = { model: chosen.model.modelId, named: `${chosen.model.provider}/${chosen.model.modelId}`, price, cost: target.cost, outputCeiling: target.maxTokens ?? null, like: sees };
44
47
  // An Anthropic model speaks Messages itself: the network, at its catalog origin, its key read by name per request.
45
48
  if (chosen.model.provider === "anthropic") {
46
49
  return { ...route, provider: { api: "anthropic-messages", origin: target.baseUrl ?? "https://api.anthropic.com", credential: () => env.ANTHROPIC_API_KEY ?? env.ANTHROPIC_AUTH_TOKEN ?? "" } };
@@ -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;