@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
@@ -1,31 +1,11 @@
1
1
  import type { BoxProvider } from "@parcha/pi-transport";
2
2
  import { type DockerNetwork, egressBlockedBy } from "./box-egress.js";
3
- /** The settings that bound a Docker box; unset, their defaults: enough for a build, and safe on a laptop, where one run's
4
- * runaway build or fork bomb would otherwise starve everything else. */
5
- export declare const BOX_CPUS_ENV = "AGENTRUN_BOX_CPUS";
6
- export declare const BOX_MEMORY_ENV = "AGENTRUN_BOX_MEMORY";
7
- export declare const BOX_PIDS_ENV = "AGENTRUN_BOX_PIDS";
8
- /** 2 CPUs' time: a CFS quota (pi-transport's Docker provider), which holds whatever CPU count Docker's VM has. */
9
- export declare const DEFAULT_BOX_CPUS = 2;
10
- /** 4 GiB, swap included (--memory-swap the same). */
11
- export declare const DEFAULT_BOX_MEMORY = "4g";
12
- /** Processes and threads at once. */
13
- export declare const DEFAULT_BOX_PIDS = 1024;
14
- /** A Docker box's limits, as pi-transport's Docker provider takes them. */
15
- export type BoxLimits = {
16
- cpus: number;
17
- memory: string;
18
- pidsLimit: number;
19
- };
20
- /** A Docker box's limits from `env`: each setting's value, or its default when unset or empty. A value that is not one, or
21
- * that every create would fail on (less than a 1 ms quota, less memory than Docker gives, more processes than the kernel
22
- * allows), throws, naming its setting: the start checks them (startServe), so no run meets one. */
23
- export declare function boxLimitsOf(env: NodeJS.ProcessEnv): BoxLimits;
24
- /** A Docker size (boxLimitsOf's memory) in MiB, the fraction dropped. */
25
- export declare const memoryMbOf: (memory: string) => number;
26
3
  /** The setting that names the hosts a box may reach: a comma list of hosts, each a name or `*.` and a name, which
27
4
  * replaces the default list; `none` for no network at all. Unset or empty, the default. */
28
5
  export declare const BOX_ALLOW_ENV = "AGENTRUN_BOX_ALLOW";
6
+ /** Whether the operator set the setting (a list of their own, or none), not left it to the default: a browser is held to
7
+ * the operator's list, never to the default, which is a sandbox's package-install list and no browsing policy. */
8
+ export declare const boxAllowSetIn: (env: NodeJS.ProcessEnv) => boolean;
29
9
  /** The hosts a box reaches when the setting names none: the package registries pip and npm (and yarn) install from, and
30
10
  * GitHub for a clone or an archive. */
31
11
  export declare const DEFAULT_BOX_ALLOW: readonly string[];
@@ -1,60 +1,16 @@
1
- // A box's settings as the server reads them at its start: a Docker box's limits (AGENTRUN_BOX_CPUS, _MEMORY, _PIDS), the
2
- // hosts a box may reach (AGENTRUN_BOX_ALLOW) and what a server's Docker boxes reach from them, and, under `--faux` only,
3
- // the tests' faux box provider. A setting that is not one throws, naming it: the start checks each, so no run meets one.
1
+ // A box's settings as the server reads them at its start: the hosts a box may reach (AGENTRUN_BOX_ALLOW) and what a
2
+ // server's Docker boxes reach from them, and, under `--faux` only, the tests' faux box provider. A setting that is not one
3
+ // throws, naming it: the start checks each, so no run meets one. A Docker computer's size (AGENTRUN_BOX_CPUS, _MEMORY,
4
+ // _PIDS) is workspace/computer-deps.ts dockerLimitsOf.
4
5
  import { pathToFileURL } from "node:url";
5
6
  import { egressBlockedBy } from "./box-egress.js";
6
7
  import { vmDocker } from "./box-egress-vm.js";
7
- /** The settings that bound a Docker box; unset, their defaults: enough for a build, and safe on a laptop, where one run's
8
- * runaway build or fork bomb would otherwise starve everything else. */
9
- export const BOX_CPUS_ENV = "AGENTRUN_BOX_CPUS";
10
- export const BOX_MEMORY_ENV = "AGENTRUN_BOX_MEMORY";
11
- export const BOX_PIDS_ENV = "AGENTRUN_BOX_PIDS";
12
- /** 2 CPUs' time: a CFS quota (pi-transport's Docker provider), which holds whatever CPU count Docker's VM has. */
13
- export const DEFAULT_BOX_CPUS = 2;
14
- /** 4 GiB, swap included (--memory-swap the same). */
15
- export const DEFAULT_BOX_MEMORY = "4g";
16
- /** Processes and threads at once. */
17
- export const DEFAULT_BOX_PIDS = 1024;
18
- /** The fewest CPUs a quota gives: the kernel's least quota is 1 ms of each 100 ms period. A quota is also a whole number of
19
- * µs, so a count too large for one (or a long string of digits, which reads as Infinity) is refused too. */
20
- const MIN_BOX_CPUS = 0.01;
21
- const MIB = 1024 * 1024;
22
- /** A size's units as Docker reads them, each 1024 of the one before. */
23
- const SIZE_UNITS = { b: 1, k: 1024, m: MIB, g: 1024 * MIB };
24
- /** The least memory Docker gives a container. */
25
- const MIN_BOX_MEMORY = 6 * MIB;
26
- /** The most processes a cgroup may be given (the kernel's PID_MAX_LIMIT); above it, every create fails. */
27
- const MAX_BOX_PIDS = 4_194_304;
28
- /** A Docker box's limits from `env`: each setting's value, or its default when unset or empty. A value that is not one, or
29
- * that every create would fail on (less than a 1 ms quota, less memory than Docker gives, more processes than the kernel
30
- * allows), throws, naming its setting: the start checks them (startServe), so no run meets one. */
31
- export function boxLimitsOf(env) {
32
- const read = (name, what, takes) => {
33
- const value = env[name];
34
- if (!value)
35
- return undefined;
36
- if (!takes(value))
37
- throw new Error(`${name} is ${what}; it is ${JSON.stringify(value)}`);
38
- return value;
39
- };
40
- const cpus = read(BOX_CPUS_ENV, "a number of CPUs of at least 0.01, such as 2 or 1.5", (value) => /^\d+(\.\d+)?$/.test(value) && Number(value) >= MIN_BOX_CPUS && Number.isSafeInteger(Math.round(Number(value) * 100_000)));
41
- const memory = read(BOX_MEMORY_ENV, "a size of at least 6m with its unit (b, k, m or g), such as 512m or 4g", (value) => {
42
- const size = /^(\d+(?:\.\d+)?)([bkmg])$/i.exec(value);
43
- // Its bytes as Docker reads them, and pi-transport's Docker provider: the number times the unit, the fraction dropped.
44
- const bytes = size ? Math.floor(Number(size[1]) * SIZE_UNITS[size[2].toLowerCase()]) : 0;
45
- return Number.isSafeInteger(bytes) && bytes >= MIN_BOX_MEMORY;
46
- });
47
- const pids = read(BOX_PIDS_ENV, "a whole number from 1 to 4194304, such as 1024", (value) => /^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= MAX_BOX_PIDS);
48
- return { cpus: cpus === undefined ? DEFAULT_BOX_CPUS : Number(cpus), memory: memory ?? DEFAULT_BOX_MEMORY, pidsLimit: pids === undefined ? DEFAULT_BOX_PIDS : Number(pids) };
49
- }
50
- /** A Docker size (boxLimitsOf's memory) in MiB, the fraction dropped. */
51
- export const memoryMbOf = (memory) => {
52
- const size = /^(\d+(?:\.\d+)?)([bkmg])$/i.exec(memory);
53
- return size ? Math.floor((Number(size[1]) * SIZE_UNITS[size[2].toLowerCase()]) / MIB) : 0;
54
- };
55
8
  /** The setting that names the hosts a box may reach: a comma list of hosts, each a name or `*.` and a name, which
56
9
  * replaces the default list; `none` for no network at all. Unset or empty, the default. */
57
10
  export const BOX_ALLOW_ENV = "AGENTRUN_BOX_ALLOW";
11
+ /** Whether the operator set the setting (a list of their own, or none), not left it to the default: a browser is held to
12
+ * the operator's list, never to the default, which is a sandbox's package-install list and no browsing policy. */
13
+ export const boxAllowSetIn = (env) => (env[BOX_ALLOW_ENV] ?? "").trim() !== "";
58
14
  /** The hosts a box reaches when the setting names none: the package registries pip and npm (and yarn) install from, and
59
15
  * GitHub for a clone or an archive. */
60
16
  export const DEFAULT_BOX_ALLOW = Object.freeze(["pypi.org", "files.pythonhosted.org", "registry.npmjs.org", "registry.yarnpkg.com", "github.com", "codeload.github.com"]);
package/dist/boxes.d.ts CHANGED
@@ -90,3 +90,20 @@ export declare function enabledBoxes(env: NodeJS.ProcessEnv): Set<BoxId>;
90
90
  export declare function boxRegistry(env: NodeJS.ProcessEnv, options?: BoxRegistryOptions): Promise<BoxRegistry>;
91
91
  /** The start's log line: the boxes available, the rest, and why each box AGENTRUN_BOXES lists (`listed`) is not available. */
92
92
  export declare function boxesLog(offers: readonly BoxOffer[], listed: ReadonlySet<BoxId>): Record<string, string>;
93
+ /** What `docker version` says of this machine's Docker daemon: it answers (`up`), or why not. `absent`: no daemon
94
+ * answers this process (no docker command, a call that fails, or one that names no daemon); not absent: one is there,
95
+ * and its socket refuses this process (the group it lacks). */
96
+ export type DockerDaemon = {
97
+ readonly up: true;
98
+ } | {
99
+ readonly up: false;
100
+ readonly absent: boolean;
101
+ readonly reason: string;
102
+ };
103
+ /** Asks this machine's Docker daemon its version (`docker version`), as the Docker box's start probe and the Docker
104
+ * computer's check (docker-daemon.ts) do: the CLI is on PATH and its daemon answers this user. `signal` bounds it. */
105
+ export declare function askDockerDaemon(env: NodeJS.ProcessEnv, signal: AbortSignal, groups?: {
106
+ file: string;
107
+ user: string;
108
+ ids: readonly number[];
109
+ }): Promise<DockerDaemon>;
package/dist/boxes.js CHANGED
@@ -165,32 +165,39 @@ async function load(name, importer) {
165
165
  return { ok: false, reason: missing ? `install ${name} to use this box` : `${name} did not load (${errorName(error)})` };
166
166
  }
167
167
  }
168
+ /** Asks this machine's Docker daemon its version (`docker version`), as the Docker box's start probe and the Docker
169
+ * computer's check (docker-daemon.ts) do: the CLI is on PATH and its daemon answers this user. `signal` bounds it. */
170
+ export async function askDockerDaemon(env, signal, groups = ownGroups()) {
171
+ // Its environment is the server's through the cut a run's takes (withoutSecrets): no box key, no other secret, no
172
+ // name shaped like a key.
173
+ const dockerEnv = withoutSecrets(env);
174
+ const answer = await new Promise((resolve) => execFile("docker", ["version", "--format", "{{.Server.Version}}"], { env: dockerEnv, signal, maxBuffer: 64 * 1024 }, (error, stdout, stderr) => {
175
+ const code = error?.code;
176
+ resolve({ ...(error ? { failed: typeof code === "number" ? `exit ${code}` : errorName(error), ...(SOCKET_DENIED.test(String(stderr)) ? { denied: true } : {}) } : {}), out: String(stdout) });
177
+ }));
178
+ const absent = (reason) => ({ up: false, absent: true, reason });
179
+ // The box's probe runs once, at the start: each fix takes a restart. Docker is on by default, so its reason is often a
180
+ // first-time user's first read: what is wrong in plain words, what the probe saw, then what to do.
181
+ if (answer.failed === "ENOENT")
182
+ return absent("Docker isn't running on this machine (no docker command on PATH): install or start Docker, then restart AgentRun");
183
+ // Its socket refused this process: the group it lacks, and how to get it without a reboot (the words, never docker's):
184
+ // a restart alone where the group file already lists this user, else joining it first.
185
+ if (answer.denied)
186
+ return { up: false, absent: false, reason: (await joinedSince(groups)) ? DOCKER_NOT_IN_GROUP : DOCKER_JOIN_GROUP };
187
+ if (answer.failed)
188
+ return absent(`Docker isn't running on this machine, or this user may not use it (docker version failed: ${answer.failed}): start Docker, or add this user to the docker group, then restart AgentRun`);
189
+ if (!answer.out.trim())
190
+ return absent("Docker isn't running on this machine (docker version named no daemon): start Docker, then restart AgentRun");
191
+ return { up: true };
192
+ }
168
193
  const PROBES = {
169
194
  /** `docker version` names the daemon's version: the CLI is on PATH and its daemon answers this user. */
170
195
  async docker(env, signal, options) {
171
196
  const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/docker").then((module) => module.dockerBoxes));
172
197
  if (!boxes.ok)
173
198
  return unavailable("docker", boxes.reason);
174
- // Its environment is the server's through the cut a run's takes (withoutSecrets): no box key, no other secret, no
175
- // name shaped like a key.
176
- const dockerEnv = withoutSecrets(env);
177
- const answer = await new Promise((resolve) => execFile("docker", ["version", "--format", "{{.Server.Version}}"], { env: dockerEnv, signal, maxBuffer: 64 * 1024 }, (error, stdout, stderr) => {
178
- const code = error?.code;
179
- resolve({ ...(error ? { failed: typeof code === "number" ? `exit ${code}` : errorName(error), ...(SOCKET_DENIED.test(String(stderr)) ? { denied: true } : {}) } : {}), out: String(stdout) });
180
- }));
181
- // The probe runs once, at the start: each fix takes a restart. Docker is on by default, so its reason is often a
182
- // first-time user's first read: what is wrong in plain words, what the probe saw, then what to do.
183
- if (answer.failed === "ENOENT")
184
- return unavailable("docker", "Docker isn't running on this machine (no docker command on PATH): install or start Docker, then restart AgentRun");
185
- // Its socket refused this process: the group it lacks, and how to get it without a reboot (the words, never docker's):
186
- // a restart alone where the group file already lists this user, else joining it first.
187
- if (answer.denied)
188
- return unavailable("docker", (await joinedSince(options.groups ?? ownGroups())) ? DOCKER_NOT_IN_GROUP : DOCKER_JOIN_GROUP);
189
- if (answer.failed)
190
- return unavailable("docker", `Docker isn't running on this machine, or this user may not use it (docker version failed: ${answer.failed}): start Docker, or add this user to the docker group, then restart AgentRun`);
191
- if (!answer.out.trim())
192
- return unavailable("docker", "Docker isn't running on this machine (docker version named no daemon): start Docker, then restart AgentRun");
193
- return available("docker", boxes.value());
199
+ const daemon = await askDockerDaemon(env, signal, options.groups);
200
+ return daemon.up ? available("docker", boxes.value()) : unavailable("docker", daemon.reason);
194
201
  },
195
202
  /** One authenticated read the provider makes anyway: the box with a name no box has (lowercase letters, digits and
196
203
  * dashes). An answer of no such box (404) means Daytona took the key; 401 or 403 means it refused it. */
@@ -14,11 +14,14 @@ export interface JournalEntry {
14
14
  readonly kind: string;
15
15
  readonly data: unknown;
16
16
  }
17
+ /** The ask a `waiting` hand-over entry holds, or undefined when the entry is not one (or is damaged). The runner writes the
18
+ * session as `session`; a PendingAsk names it `tag`. The one reading of an ask, the server's and the run's process's. */
19
+ export declare function waitingAsk(data: unknown): PendingAsk | undefined;
17
20
  /** The browser ask the run view shows: the newest ask still waiting (unanswered and not expired), or undefined. Over the
18
- * run's journal entries and its hand-over commands, as the old openAsk read it over the run's files. (store-view.ts calls
21
+ * run's journal entries and its hand-over commands. (store-view.ts calls
19
22
  * this for the run's served `pending`.) */
20
23
  export declare function browserAsk(entries: readonly JournalEntry[], commands?: readonly Command[], now?: number): PendingAsk | undefined;
21
- /** The ask a hand-over answer targets and how it already stands, mirroring the old answerAsk's choice: the newest ask still
24
+ /** The ask a hand-over answer targets and how it already stands: the newest ask still
22
25
  * waiting, else the newest ask at all; its answer when it has one, `expired` when it is past its expiry, else open (no
23
26
  * answer). Undefined when the run has asked nothing. */
24
27
  export declare function handBackTarget(entries: readonly JournalEntry[], commands?: readonly Command[], now?: number): {
@@ -10,8 +10,8 @@ export const BROWSER_HANDOVER_KIND = "agent.handover";
10
10
  const TAG = /^[A-Za-z0-9._:-]{1,200}$/;
11
11
  const OUTCOMES = ["done", "cancelled", "expired"];
12
12
  /** The ask a `waiting` hand-over entry holds, or undefined when the entry is not one (or is damaged). The runner writes the
13
- * session as `session`; a PendingAsk names it `tag`. */
14
- function waitingAsk(data) {
13
+ * session as `session`; a PendingAsk names it `tag`. The one reading of an ask, the server's and the run's process's. */
14
+ export function waitingAsk(data) {
15
15
  const v = data;
16
16
  if (!v || v.state !== "waiting")
17
17
  return undefined;
@@ -68,13 +68,13 @@ function asksIn(entries) {
68
68
  return asks.sort((a, b) => Date.parse(b.asked_at) - Date.parse(a.asked_at) || b.id.localeCompare(a.id));
69
69
  }
70
70
  /** The browser ask the run view shows: the newest ask still waiting (unanswered and not expired), or undefined. Over the
71
- * run's journal entries and its hand-over commands, as the old openAsk read it over the run's files. (store-view.ts calls
71
+ * run's journal entries and its hand-over commands. (store-view.ts calls
72
72
  * this for the run's served `pending`.) */
73
73
  export function browserAsk(entries, commands = [], now = Date.now()) {
74
74
  const answered = answersOf(entries, commands);
75
75
  return asksIn(entries).find((ask) => !answered.has(ask.id) && Date.parse(ask.expires_at) > now);
76
76
  }
77
- /** The ask a hand-over answer targets and how it already stands, mirroring the old answerAsk's choice: the newest ask still
77
+ /** The ask a hand-over answer targets and how it already stands: the newest ask still
78
78
  * waiting, else the newest ask at all; its answer when it has one, `expired` when it is past its expiry, else open (no
79
79
  * answer). Undefined when the run has asked nothing. */
80
80
  export function handBackTarget(entries, commands = [], now = Date.now()) {
@@ -0,0 +1,5 @@
1
+ import type { BrowserProvider } from "@parcha/pi-browser";
2
+ import type { ClaimBrowser } from "./workspace/resolve-computer.js";
3
+ /** pi-browser's provider over the claim's browser `computer`. A session its provider says is gone (or not found) is gone;
4
+ * any other failure to read it is thrown in its words. */
5
+ export declare function claimBrowserProvider(computer: ClaimBrowser): BrowserProvider;
@@ -0,0 +1,21 @@
1
+ /** What a session of the claim's browser is opened with: none of a run's session settings (no proxy, Verified browser,
2
+ * place, region or context by id) and no saved profile, which the computer protocol does not carry. */
3
+ const SETTINGS = { proxies: false, verified: false, geolocation: false, region: false, context: false };
4
+ /** pi-browser's provider over the claim's browser `computer`. A session its provider says is gone (or not found) is gone;
5
+ * any other failure to read it is thrown in its words. */
6
+ export function claimBrowserProvider(computer) {
7
+ return {
8
+ name: computer.provider,
9
+ caps: { timeoutModel: "wall-clock", maxLifetimeS: computer.maxLifetimeS, survivesDisconnect: true, releaseIsAsync: false, profiles: false, extension: "preinstalled", settings: SETTINGS },
10
+ create: async (spec, signal) => ({ id: await computer.open(spec.tag, spec.maxLifetimeS, signal), tag: spec.tag }),
11
+ findByTag: async (tag, signal) => (await computer.find(tag, signal)).map((id) => ({ id, tag })),
12
+ status: (ref) => computer.url(ref.id).then(() => "running", (error) => {
13
+ const code = error?.code;
14
+ if (code === "gone" || code === "not_found")
15
+ return "gone";
16
+ throw error;
17
+ }),
18
+ attach: async (ref) => ({ sdkCdpUrl: await computer.url(ref.id) }),
19
+ release: (ref) => computer.close(ref.id),
20
+ };
21
+ }
@@ -1,16 +1,18 @@
1
1
  import type { Context } from "@earendil-works/chord";
2
2
  import type { Refusal } from "@parcha/agentrun-kernel";
3
- import { type Conversation, type Session, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
3
+ import { type Harness, type Conversation, type Session, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
4
4
  import type { SessionCharge } from "@parcha/pi-browser";
5
5
  import type { BeforeCreate } from "@parcha/pi-browser/durable";
6
+ import { BROWSER_CHARGED } from "./cap.js";
6
7
  import { type PaidBooking } from "./paid-calls.js";
7
8
  /** The run journal's record of a browser session about to be created at its provider: its tag (pi-browser's, which a
8
9
  * reconcile finds the vendor's session by), its conversation and the hold its call keeps for it (`held_usd`, null with
9
- * no cap). Written with pi-browser's own `creating` record and synced (barriers.ts browserSessionOpen) before the vendor
10
- * is asked, so a box loss never leaves a session billed that no record in the store names. */
10
+ * no cap). Written with pi-browser's own `creating` record and flushed before the vendor is asked, so a lost box never
11
+ * leaves a session billed that no record in the store names. */
11
12
  export declare const BROWSER_SESSION_OPEN = "agentrun.browser_session_open";
12
13
  /** List prices by pi-browser provider name (`provider.name`): Browserbase's (pi-browser's LIST_PRICES), $0.12 an hour with
13
- * a one-minute minimum; Kernel's headless browser, about $0.06 an hour billed by the second; a local Chrome (`cdp`), free. */
14
+ * a one-minute minimum; Kernel's headless browser, about $0.06 an hour billed by the second; a local Chrome (`cdp`, and
15
+ * the `local` computer provider's), free. */
14
16
  export declare const BROWSER_PRICES: Readonly<Record<string, {
15
17
  usdPerHour: number;
16
18
  minimumS: number;
@@ -32,6 +34,7 @@ export declare function browserPrice(provider: string, env: NodeJS.ProcessEnv):
32
34
  };
33
35
  /** A cap refusal as the run's pause reads it (its words; for good, or for room with its figures). */
34
36
  type LedgerRefusal = Refusal;
37
+ export { BROWSER_CHARGED };
35
38
  /** One run's browser bookings, for its one provider at `price` with pi-browser's idle window `idleS`. `release` lets go of
36
39
  * a conversation's session (pi-browser's release, "close"). `log` takes the line that says a charge went uncounted
37
40
  * (default: the server's stderr). */
@@ -41,12 +44,13 @@ export declare function browserSpend(provider: string, price: {
41
44
  }, idleS: number, release: (conversation: Pick<Conversation, "id" | "commit">, context: Context) => Promise<void>, log?: (line: string) => void, ledger?: {
42
45
  paid?: PaidBooking;
43
46
  pause?: (refusal: LedgerRefusal) => Promise<void>;
47
+ flush?: () => Promise<void>;
44
48
  }): {
45
49
  onCharge: (charge: SessionCharge, tx: Tx, call?: {
46
50
  callId: string;
47
51
  }) => Promise<void>;
48
52
  watch: (harness: Pick<Session, "observeCommits" | "closed">, inventory?: string) => void;
49
- reopened: (harness: Pick<Session, "snapshot">, docs: {
53
+ reopened: (harness: Pick<Session, "snapshot"> & Partial<Pick<Harness, "conversation">>, docs: {
50
54
  Inventory: unknown;
51
55
  Sessions: unknown;
52
56
  }, context: Context) => Promise<void>;
@@ -65,4 +69,3 @@ export declare function browserSpend(provider: string, price: {
65
69
  stretch: number;
66
70
  ledgerIdle: () => Promise<void>;
67
71
  };
68
- export {};
@@ -1,21 +1,22 @@
1
1
  import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
2
- import { TOOL_COST } from "@parcha/pi-durable-agent/timeline";
3
- import { BARRIER, syncNow } from "@parcha/pi-durable-disk";
4
- import { addSpend, keepHold, paidCall, runCap, SPEND_CAP_REACHED } from "./cap.js";
5
- import { paidStep, runJournal } from "./paid-calls.js";
2
+ import { TOOL_COST } from "./timeline/index.js";
3
+ import { addSpend, BROWSER_CHARGED, keepHold, paidCall, runCap, SPEND_CAP_REACHED } from "./cap.js";
4
+ import { paidStep } from "./paid-calls.js";
6
5
  import { logLine } from "./print.js";
7
6
  import { forModel } from "./result.js";
8
7
  /** The run journal's record of a browser session about to be created at its provider: its tag (pi-browser's, which a
9
8
  * reconcile finds the vendor's session by), its conversation and the hold its call keeps for it (`held_usd`, null with
10
- * no cap). Written with pi-browser's own `creating` record and synced (barriers.ts browserSessionOpen) before the vendor
11
- * is asked, so a box loss never leaves a session billed that no record in the store names. */
9
+ * no cap). Written with pi-browser's own `creating` record and flushed before the vendor is asked, so a lost box never
10
+ * leaves a session billed that no record in the store names. */
12
11
  export const BROWSER_SESSION_OPEN = "agentrun.browser_session_open";
13
12
  /** List prices by pi-browser provider name (`provider.name`): Browserbase's (pi-browser's LIST_PRICES), $0.12 an hour with
14
- * a one-minute minimum; Kernel's headless browser, about $0.06 an hour billed by the second; a local Chrome (`cdp`), free. */
13
+ * a one-minute minimum; Kernel's headless browser, about $0.06 an hour billed by the second; a local Chrome (`cdp`, and
14
+ * the `local` computer provider's), free. */
15
15
  export const BROWSER_PRICES = Object.freeze({
16
16
  browserbase: { usdPerHour: 0.12, minimumS: 60 },
17
17
  kernel: { usdPerHour: 0.06, minimumS: 0 },
18
18
  cdp: { usdPerHour: 0, minimumS: 0 },
19
+ local: { usdPerHour: 0, minimumS: 0 },
19
20
  });
20
21
  /** An operator's price for a provider, in USD an hour: this prefix and the provider's name in capitals
21
22
  * (AGENTRUN_BROWSER_USD_PER_HOUR_BROWSERBASE, _KERNEL, _CDP). */
@@ -36,29 +37,37 @@ export function browserPrice(provider, env) {
36
37
  }
37
38
  /** Up to the millionth of a dollar, so the cap's words name a figure never below the hold. */
38
39
  const microUsd = (usd) => Math.ceil(Math.round(usd * 1e12) / 1e6) / 1e6;
40
+ export { BROWSER_CHARGED };
41
+ /** The tool a browser step on the run's one ledger names (main's charge's `tool`, the timeline's BROWSER_CHARGE): the run
42
+ * view folds its charge into its call's row, as main's. */
43
+ const BROWSER_TOOL = "browser";
39
44
  /** One run's browser bookings, for its one provider at `price` with pi-browser's idle window `idleS`. `release` lets go of
40
45
  * a conversation's session (pi-browser's release, "close"). `log` takes the line that says a charge went uncounted
41
46
  * (default: the server's stderr). */
42
47
  export function browserSpend(provider, price, idleS, release, log = (line) => void process.stderr.write(`agentrun-serve: ${line}\n`), ledger = {}) {
43
- /** The runner's one ledger (the kernel cap's paidCalls), when the run has one: each browser call is one paid request on
44
- * it, held at the hold main takes for it and settled at the charges booked under it; a charge under no call (a
45
- * session's release, its top-up to the minute) is one more, settled at that charge. In place of this process's spend. */
48
+ /** The runner's one ledger (the kernel cap's paidCalls), when the run has one. Its holds are hold-only steps (`hold`:
49
+ * money reserved, never spent, given back when let go or when a claim is lost): each browser call's, held at the hold
50
+ * main takes for it, a session's reserve, a person's time. Its money is its charges: each one paid step of its own,
51
+ * owed (its time is spent at the provider: never refused, however the run's spend stands), settled at the charge,
52
+ * named by its session and time (`ref`) so it is booked once, and booked once its commit is in (booked); a reopen books
53
+ * any the root holds and the ledger lacks (reopened). In place of this process's spend. Every step names its tool
54
+ * ("browser") and, where it has them, its call and session, so the run view folds it as main's charge. */
46
55
  const paid = ledger.paid;
47
- /** Each browser call under way on the ledger: what has been charged under it (null: a charge with no price). */
48
- const chargedUnder = new Map();
49
- /** The ledger steps of charges under no call, until they are written (ledgerIdle). */
56
+ /** The ledger steps of charges and holds, until they are written (ledgerIdle). */
50
57
  const pending = new Set();
51
58
  let ledgerSeq = 0;
52
- /** A hold of `usd` under `name`: on the run's one ledger when it is given (a held paid step, settled at nothing when the
53
- * hold is let go, the time it held being booked by the session's own charge), else in this process's holds (keepHold).
54
- * On the ledger nothing is written to this process's holds or spend. `admitted`: the ledger's answer (refused in the
55
- * cap's words when it has no room). */
56
- const holdOf = (name, usd, basis) => {
59
+ /** A hold of `usd` under `name`: on the run's one ledger when it is given (a held paid step, given back when the hold is
60
+ * let go, the time it held being booked by the session's own charge), else in this process's holds (keepHold). On the
61
+ * ledger nothing is written to this process's holds or spend. `admitted`: the ledger's answer (refused in the cap's
62
+ * words when it has no room). `owed`: time its provider is already owed, run outside any call (a person's carried
63
+ * time, a session held from a reopen, a delayed release), held as main's keepHold holds it: never refused. A fresh
64
+ * session's reserve and a person's time to come (personTime) are not owed: the cap may refuse them. */
65
+ const holdOf = (name, usd, basis, options = {}) => {
57
66
  if (!paid)
58
67
  return { hold: keepHold(usd), admitted: Promise.resolve({}) };
59
68
  const booking = paid;
60
69
  const id = `browser:${name}#${(ledgerSeq += 1)}`;
61
- const admitted = booking.admit({ id, name, holdUsd: usd, basis, chargedBy: provider }).then(() => ({}), (error) => {
70
+ const admitted = booking.admit({ id, name, holdUsd: usd, basis, chargedBy: provider, tool: BROWSER_TOOL, hold: true, ...(options.tag ? { tag: options.tag } : {}), ...(options.owed ? { owed: true } : {}) }).then(() => ({}), (error) => {
62
71
  const capped = error?.code === "spend_cap_reached";
63
72
  const refused = capped ? String(error.message) : `${name} could not be held: ${String(error?.message ?? error)}`;
64
73
  // The cap's own refusal, as the run's pause reads it (a room refusal's figures; a refusal for good).
@@ -75,7 +84,8 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
75
84
  if (dropped)
76
85
  return;
77
86
  dropped = true;
78
- const settled = admitted.then((answer) => (answer.refused === undefined ? booking.settle(id, 0) : undefined)).catch(() => undefined);
87
+ // Given back: a hold is no charge (its time, when it ran, is booked by the session's own charge), never a $0 one.
88
+ const settled = admitted.then((answer) => (answer.refused === undefined ? booking.settle(id, 0, { givenBack: true }) : undefined)).catch(() => undefined);
79
89
  pending.add(settled);
80
90
  void settled.finally(() => pending.delete(settled));
81
91
  },
@@ -136,32 +146,37 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
136
146
  const calls = new Map();
137
147
  const take = (hold, usd) => void (hold && (hold.usd = Math.max(0, hold.usd - usd)));
138
148
  /** Booked in the commit that bills it: a TOOL_COST under the call that ran it (a release's, under its session's last
139
- * call), what it cost or null when its time has no price, and the seconds it was for, with what `booked` needs. A free
140
- * provider's time books nothing and holds nothing. */
149
+ * call; on the runner's ledger, a BROWSER_CHARGED, its money the ledger step's), what it cost or null when its time
150
+ * has no price, and the seconds it was for, with what `booked` needs. A free provider's time books nothing and holds
151
+ * nothing. */
141
152
  async function onCharge(charge, tx, call) {
142
153
  if (rate === 0)
143
154
  return;
144
155
  const usd = charge.state === "priced" ? charge.usd : null;
145
- if (paid) {
146
- const under = call?.callId;
147
- if (under !== undefined && chargedUnder.has(under)) {
148
- const so = chargedUnder.get(under) ?? null;
149
- chargedUnder.set(under, so === null || usd === null ? null : so + usd);
150
- }
151
- else {
152
- // A charge under no call under way (the release's, its top-up to the minute): one more paid request on the ledger,
153
- // held at nothing (its time is spent already) and settled at the charge.
154
- const step = paidStep(paid, `${charge.tag}${charge.final ? "@release" : "@charge"}`, { name: "this browser session's time", holdUsd: 0, basis: `${provider}'s session time, billed as it was charged`, by: charge.provider }, async () => undefined, () => usd).catch(() => undefined);
155
- pending.add(step);
156
- void step.finally(() => pending.delete(step));
157
- }
158
- }
159
156
  const data = { tool: "browser", charged_by: charge.provider, call: call?.callId ?? sessions.get(charge.tag)?.call ?? null, usd, seconds: charge.seconds, tag: charge.tag, conversation: charge.conversationId, at: charge.at, final: charge.final };
160
- await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: TOOL_COST, data });
157
+ // On the ledger, its money is the ledger's, booked once this commit is in (booked): the root keeps the record under a
158
+ // kind no cost reads.
159
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: paid ? BROWSER_CHARGED : TOOL_COST, data });
160
+ }
161
+ /** A charge on the run's one ledger, once its commit is in: one paid step of its own, owed (its time is spent at the
162
+ * provider, so the cap never refuses it, however the run's spend stands), settled at the charge, under its call (the
163
+ * one that ran it, else its session's last; none after a restart that lost it) and named by its session and time, so
164
+ * it is booked once whoever books it (this, or a reopen's: reopened). One that cannot be booked (its claim lost, a
165
+ * write that failed) is said in the log, and booked by the next claim's reopen. */
166
+ function bookOnLedger(booking, data) {
167
+ // Held at its charge (known: it was billed): a claim lost before its settle leaves it booked at that, never unknown
168
+ // (the kernel's bookCut books an owed step at its hold). A charge of an unknown amount holds nothing.
169
+ const owes = typeof data.usd === "number" && Number.isFinite(data.usd) && data.usd > 0 ? data.usd : 0;
170
+ const step = paidStep(booking, data.call ?? undefined, { name: "this browser session's time", holdUsd: owes, basis: `${provider}'s session time, billed as it was charged`, by: data.charged_by, tool: BROWSER_TOOL, tag: data.tag, owed: true, ref: chargeRef(data) }, async () => undefined, () => data.usd).then((stepped) => void ("refused" in stepped && log(logLine("browser_spend_unbooked", { said: `a browser charge of ${data.tag} was not booked on the run's ledger (${stepped.refused.slice(0, 200)}): the next claim's reopen books it` }))), (error) => void log(logLine("browser_spend_unbooked", { said: `a browser charge of ${data.tag} was not booked on the run's ledger (${String(error?.message ?? error).slice(0, 200)}): the next claim's reopen books it` })));
171
+ pending.add(step);
172
+ void step.finally(() => pending.delete(step));
173
+ return step;
161
174
  }
162
175
  /** A charge whose commit is in (watch): it joins what the run's process counts as spent, and moves the holds. Never
163
176
  * inside the commit, so one that fails changes neither. */
164
177
  function booked(data) {
178
+ if (paid)
179
+ bookOnLedger(paid, data);
165
180
  const usd = data.usd ?? 0;
166
181
  const session = sessions.get(data.tag);
167
182
  spendIn(data.usd);
@@ -192,8 +207,31 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
192
207
  }
193
208
  else {
194
209
  take(data.call === null ? undefined : calls.get(data.call)?.hold, usd + stretch);
195
- sessions.set(data.tag, { cid: data.conversation, reserve: holdOf("this browser session's reserve", stretch, `${provider}'s next stretch of session time, held until its release is booked`).hold, at: through, call: data.call });
210
+ sessions.set(data.tag, { cid: data.conversation, reserve: holdOf("this browser session's reserve", stretch, `${provider}'s next stretch of session time, held until its release is booked`, { tag: data.tag }).hold, at: through, call: data.call });
211
+ }
212
+ }
213
+ /** The one booking a charge names on the ledger: its session, its time, and whether it was the session's last. */
214
+ const chargeRef = (data) => `browser:${data.tag}@${data.at}${data.final ? "/final" : ""}`;
215
+ /** At a reopen, on the runner's one ledger: every charge the root holds (BROWSER_CHARGED) is booked there, once by its
216
+ * ref, so one whose commit landed and whose booking did not (its process lost between the two) is counted now; one
217
+ * booked already books nothing. */
218
+ async function bookRootCharges(harness, context) {
219
+ if (!paid)
220
+ return;
221
+ const root = await harness.conversation(ROOT_CONVERSATION_ID, context);
222
+ if (!root)
223
+ return;
224
+ const charges = [];
225
+ for (let cursor = undefined;;) {
226
+ const page = await root.entries({ order: "ascending" }, 500, cursor, context);
227
+ for (const entry of page.items)
228
+ if (entry.kind === BROWSER_CHARGED)
229
+ charges.push(entry.data);
230
+ if (page.next === undefined)
231
+ break;
232
+ cursor = page.next;
196
233
  }
234
+ await Promise.all(charges.map((data) => bookOnLedger(paid, data)));
197
235
  }
198
236
  /** At a reopen, after pi-browser's reconcile: every session its custody still tracks (each row of its inventory: kept,
199
237
  * unreached, still releasing, lost) is held from here as if opened in this process, at a stretch beside what it ran
@@ -202,6 +240,8 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
202
240
  async function reopened(harness, docs, context) {
203
241
  if (rate === 0)
204
242
  return;
243
+ if (harness.conversation)
244
+ await bookRootCharges(harness, context);
205
245
  const rows = Object.values((await harness.snapshot(docs.Inventory, context))?.rows ?? {});
206
246
  for (const row of rows.filter((r) => !sessions.has(r.tag))) {
207
247
  const record = (await harness.snapshot(docs.Sessions, row.conversationId, context))?.sessions?.find((s) => s.tag === row.tag);
@@ -211,7 +251,7 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
211
251
  continue;
212
252
  // Its reserve carries the down time, so its calls count what it runs from here (`at` now), not the down time again.
213
253
  const now = Date.now();
214
- sessions.set(row.tag, { cid: row.conversationId, reserve: holdOf("this browser session's reserve", stretch + usdOf(Math.max(0, now - at) / 1000), `${provider}'s session time since its last charge and its next stretch, held from the reopen`).hold, at: now, call: null });
254
+ sessions.set(row.tag, { cid: row.conversationId, reserve: holdOf("this browser session's reserve", stretch + usdOf(Math.max(0, now - at) / 1000), `${provider}'s session time since its last charge and its next stretch, held from the reopen`, { owed: true, tag: row.tag }).hold, at: now, call: null });
215
255
  }
216
256
  }
217
257
  /** The open-session inventory as committed: a session it no longer holds lets go of its reserve (released, billed or
@@ -230,7 +270,7 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
230
270
  continue;
231
271
  const usd = usdOf(CREATE_DEADLINE_S + stretchS);
232
272
  take([...calls.values()].find((c) => c.cid === row.conversationId)?.hold, usd);
233
- sessions.set(row.tag, { cid: row.conversationId, reserve: holdOf("this browser session's delayed release", usd, `${provider}'s session time for its create's deadline and a stretch, until its release is billed`).hold, at: Date.now(), call: null });
273
+ sessions.set(row.tag, { cid: row.conversationId, reserve: holdOf("this browser session's delayed release", usd, `${provider}'s session time for its create's deadline and a stretch, until its release is billed`, { owed: true, tag: row.tag }).hold, at: Date.now(), call: null });
234
274
  }
235
275
  }
236
276
  /** Applies each browser charge `harness` commits, and each change of pi-browser's inventory (the document of kind
@@ -258,7 +298,7 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
258
298
  advance: (publication) => {
259
299
  try {
260
300
  for (const change of publication.changes) {
261
- const data = change.type === "entry" && change.value.kind === TOOL_COST ? change.value.data : undefined;
301
+ const data = change.type === "entry" && (change.value.kind === TOOL_COST || change.value.kind === BROWSER_CHARGED) ? change.value.data : undefined;
262
302
  if (data?.tool === "browser" && typeof data.tag === "string")
263
303
  booked(data);
264
304
  }
@@ -297,18 +337,19 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
297
337
  const usd = microUsd(Math.max(0, usdOf(ranS) - carriedUsd) + 2 * stretch);
298
338
  const basis = `${provider}'s session time at $${rate} an hour: the ${Math.round(ranS)} s its session ran since its last charge, and twice the next stretch of ${stretchS} s (its ${price.minimumS} s minimum, the ${idleS} s idle window and ${RELEASE_ALLOWANCE_S} s for its release)`;
299
339
  if (ledger.paid) {
300
- // On the runner's one ledger: one paid request, held at that same figure, settled at the charges booked under
301
- // this call (a call with none charged nothing; one with an unpriced charge at its hold).
302
- chargedUnder.set(api.callId, 0);
340
+ // On the runner's one ledger: one hold-only step, held at that same figure and given back when the call returns
341
+ // (or its claim is lost): the call's charges are each their own step (booked).
303
342
  calls.set(api.callId, { cid: api.conversationId, hold: { usd, drop: () => { } } });
304
343
  try {
305
344
  // A provider whose time has no price is held at no figure: the cap's rule refuses it for good, as main does.
306
- const stepped = await paidStep(ledger.paid, api.callId, { name: "this browser call", holdUsd: rate === null ? Number.NaN : usd, basis, by: provider }, () => tool.execute(args, api, context), () => chargedUnder.get(api.callId) ?? null);
345
+ // One refused for room pauses the run (ledger.pause, the run's own: a native tool task runs in no host tool
346
+ // call's ledger), in the cap's words and figures, as an ask's person time does: its next request is refused
347
+ // and the run parks for a raise.
348
+ const stepped = await paidStep(ledger.paid, api.callId, { name: "this browser call", holdUsd: rate === null ? Number.NaN : usd, basis, by: provider, tool: BROWSER_TOOL, hold: true }, () => tool.execute(args, api, context), () => 0, ledger.pause);
307
349
  return "refused" in stepped ? await refuse(stepped.refused, api, context) : stepped.result;
308
350
  }
309
351
  finally {
310
352
  calls.delete(api.callId);
311
- chargedUnder.delete(api.callId);
312
353
  }
313
354
  }
314
355
  const paid = await paidCall("this browser call", async () => keepHold(usd), () => undefined, { usd, basis });
@@ -327,13 +368,14 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
327
368
  };
328
369
  }
329
370
  /** pi-browser's `beforeCreate`: the session's open recorded in the run's journal (BROWSER_SESSION_OPEN) beside its
330
- * `creating` record, and the journal synced (barriers.ts browserSessionOpen) before the vendor's session is created.
331
- * A sync that fails throws, and pi-browser creates nothing. */
371
+ * `creating` record, then flushed to disk (`ledger.flush`, the runner's store flush) before the vendor's session is
372
+ * created. The runner's flush before a tool call comes before the call opens its session, so it never covers this
373
+ * record. A write or a flush that fails throws, and pi-browser creates nothing. */
332
374
  const opening = async (open) => {
333
375
  const hold = [...calls.values()].find((c) => c.cid === open.conversationId)?.hold;
334
376
  const data = { tag: open.tag, conversation: open.conversationId, provider, held_usd: hold ? hold.usd : null };
335
377
  await open.commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: BROWSER_SESSION_OPEN, data })));
336
- await syncNow(runJournal(), BARRIER.browserSessionOpen);
378
+ await ledger.flush?.();
337
379
  };
338
380
  /** The cap's refusal as the call's error, and the conversation's session let go, so it runs no longer. */
339
381
  async function refuse(why, api, context) {
@@ -405,7 +447,7 @@ export function browserSpend(provider, price, idleS, release, log = (line) => vo
405
447
  if (!(to > from))
406
448
  return;
407
449
  // Spent at the provider already: held on the run's ledger (or this process's holds) until a charge books it.
408
- const { hold } = holdOf("a person's time in the browser", microUsd(usdOf((to - from) / 1000)), `${provider}'s session time a person used, until the session's next charge books it`);
450
+ const { hold } = holdOf("a person's time in the browser", microUsd(usdOf((to - from) / 1000)), `${provider}'s session time a person used, until the session's next charge books it`, { owed: true, tag });
409
451
  carried.set(tag, [...(carried.get(tag) ?? []), { hold, from, to }]);
410
452
  }
411
453
  /** Once every ledger step of a charge under no call is written (the runner's one ledger; nothing to wait for without). */