@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
@@ -8,203 +8,34 @@
8
8
  // as session time always is. The run stays working; the timeline says "You took over the browser" and how it came back.
9
9
  //
10
10
  // The agent asks: pi-browser holds the session for a person and calls `request`, which holds the person's time the same
11
- // way (refused, the tool's result says why), writes the ask's pending record in the run's directory, outside work/
12
- // (BROWSER_ASK_DIR/<id>.json, its id a digest of the session's tag and the model's request id, 0600 in 0700: the session's tag, the instruction, the done-when condition, when it was asked
13
- // and when it expires; never the live view's link or token), and commits a waiting row ("Waiting for you: <instruction>").
14
- // The server reads the record: the run is input_required/waiting with `pending.kind` browser, and run.needs_input fires.
15
- // The owner answers POST /v2/runs/{id}/browser/hand-back, which writes `<id>.answer.json` once (the first answer wins);
16
- // unanswered by `expires_at`, the run's process writes `expired` the same way. pi-browser's wait reads it through
17
- // `outcome`; a poll here ends any take-over at once and drops the hold. The records outlive a process that dies (the
18
- // run is started again and its next process takes the wait up, `adopt`), and go when the run ends, or when its process
19
- // lets its sessions go.
20
- import { createHash, randomBytes } from "node:crypto";
21
- import { closeSync, constants, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
22
- import { join } from "node:path";
23
- import { HOST_PHASE } from "@parcha/pi-durable-agent/timeline";
24
- /** The ask's directory in the run's directory (never in work/). */
25
- export const BROWSER_ASK_DIR = "browser-ask";
11
+ // way (refused, the tool's result says why) and commits the ask's waiting entry to the run's journal (an agent.handover
12
+ // note, its id a digest of the session's tag and the model's request id: the session's tag, the instruction, the
13
+ // done-when condition, when it was asked and when it expires; never the live view's link or token). That entry is the
14
+ // ask's one record: no file holds it, so nothing the run's agent reaches (its workspace, its file tools, the run's file
15
+ // list) can read, change or plant an ask. The server reads the journal (browser-commands.ts): the run is
16
+ // input_required/waiting with `pending.kind` browser, and run.needs_input fires. The owner answers POST
17
+ // /v2/runs/{id}/browser/hand-back, a command row the runner applies as the ask's answered entry (the first answer wins);
18
+ // the live view's hand-back and the ask's expiry are answered entries this process writes the same way. pi-browser's wait
19
+ // reads the answer through `outcome`; a poll here ends any take-over at once and drops the hold. An ask outlives a process
20
+ // that dies: the run's next claim reads it back from the journal and takes the wait up (`adopt`).
21
+ import { createHash } from "node:crypto";
22
+ import { HOST_PHASE } from "./timeline/index.js";
26
23
  /** How long a person's time lasts at most before it expires: an unanswered ask, and a take-over with no input. Its worth of session time is held up front. */
27
24
  export const PERSON_HOLD_MS = 15 * 60_000;
28
25
  /** How long a take-over outlasts its viewer. */
29
26
  export const PERSON_AWAY_MS = 2 * 60_000;
30
27
  /** Under `--faux` only (the tests, beside the fake browser's own FAUX_BROWSER_LOG): the two windows above, in ms, `<hold>,<away>`. */
31
28
  export const FAUX_PERSON_MS_ENV = "FAUX_BROWSER_PERSON_MS";
32
- /** For tests (under `--faux`): a file's path; the run's process dies once (making the file) right after it writes an ask's
33
- * record and before it commits the ask's row, as a crash there would. */
34
- export const FAUX_ASK_DIES_ENV = "FAUX_BROWSER_ASK_DIES";
35
- /** An ask's id: 32 characters (askIdOf). A record named otherwise (an earlier build's 22, named by the request id alone,
36
- * shared across sessions) is no ask: never read, shown, answered or taken up. */
29
+ /** An ask's id: 32 characters (askIdOf). An id of another shape (an earlier build's 22, named by the request id alone,
30
+ * shared across sessions) is no ask: never read, answered or taken up. */
37
31
  const ID = /^[A-Za-z0-9_-]{32}$/;
38
32
  const TAG = /^[A-Za-z0-9._:-]{1,200}$/;
39
- const OUTCOMES = ["done", "cancelled", "expired"];
40
33
  /** What the person sees of an instruction or a condition, at most. */
41
34
  const MAX_TEXT = 2000;
42
- /** The ask's id: pi-browser's request id is the model's, so the file is named by a digest of it, never by it; and of the
35
+ /** The ask's id: pi-browser's request id is the model's, so the ask is named by a digest of it, never by it; and of the
43
36
  * session's tag with it, since two conversations of one run (each its own session) may pick the same request id, and
44
37
  * each ask is its session's own: its instruction, its answer, its take-over. */
45
38
  export const askIdOf = (sessionTag, requestId) => createHash("sha256").update(`${sessionTag}\n${requestId}`).digest("base64url").slice(0, 32);
46
- /** Whether `at` is this user's alone, and not a link: a directory (0700) or a file (0600). */
47
- const ownAlone = (at, dir) => (dir ? at.isDirectory() : at.isFile()) && !at.isSymbolicLink() && (at.mode & 0o077) === 0 && (!process.getuid || at.uid === process.getuid());
48
- /** The run's ask directory when it is this user's alone; made (0700) when `make`. */
49
- function askDir(runDir, make = false) {
50
- const dir = join(runDir, BROWSER_ASK_DIR);
51
- if (make) {
52
- try {
53
- mkdirSync(dir, { mode: 0o700 });
54
- }
55
- catch (error) {
56
- if (error.code !== "EEXIST")
57
- throw error;
58
- }
59
- }
60
- try {
61
- return ownAlone(lstatSync(dir), true) ? dir : undefined;
62
- }
63
- catch {
64
- return undefined;
65
- }
66
- }
67
- /** A JSON file of this user's alone in the ask directory, or undefined: opened without following a link, and checked on
68
- * the handle it reads. */
69
- function readOwn(dir, name) {
70
- let fd;
71
- try {
72
- fd = openSync(join(dir, name), constants.O_RDONLY | constants.O_NOFOLLOW);
73
- return ownAlone(fstatSync(fd), false) ? JSON.parse(readFileSync(fd, "utf8")) : undefined;
74
- }
75
- catch {
76
- return undefined;
77
- }
78
- finally {
79
- if (fd !== undefined)
80
- closeSync(fd);
81
- }
82
- }
83
- /** Writes `value` as `name`, whole, 0600: under a name of its own first, then into place, replacing (`once` false) or only
84
- * when there is none yet (`once`, by a hard link, which never replaces). False when `once` found one there. */
85
- function writeOwn(dir, name, value, once) {
86
- const making = join(dir, `.${randomBytes(6).toString("hex")}.tmp`);
87
- writeFileSync(making, `${JSON.stringify(value)}\n`, { mode: 0o600, flag: "wx" });
88
- try {
89
- if (!once) {
90
- renameSync(making, join(dir, name));
91
- return true;
92
- }
93
- try {
94
- linkSync(making, join(dir, name));
95
- return true;
96
- }
97
- catch (error) {
98
- if (error.code === "EEXIST")
99
- return false;
100
- throw error;
101
- }
102
- }
103
- finally {
104
- try {
105
- unlinkSync(making);
106
- }
107
- catch {
108
- // renamed into place, or gone
109
- }
110
- }
111
- }
112
- const pendingOf = (value, id) => {
113
- const v = value;
114
- const ok = v?.id === id && typeof v.tag === "string" && TAG.test(v.tag) && typeof v.instruction === "string" && typeof v.completion_condition === "string" && Number.isFinite(Date.parse(String(v.asked_at))) && Number.isFinite(Date.parse(String(v.expires_at)));
115
- return ok ? { id, tag: v.tag, instruction: v.instruction, completion_condition: v.completion_condition, asked_at: v.asked_at, expires_at: v.expires_at } : undefined;
116
- };
117
- const answerOf = (value) => {
118
- const v = value;
119
- return v && OUTCOMES.includes(String(v.outcome)) && typeof v.at === "string" ? { outcome: v.outcome, at: v.at, ...(typeof v.reason === "string" ? { reason: v.reason } : {}) } : undefined;
120
- };
121
- /** Every ask the run's directory holds, newest first, each with its answer when it has one. */
122
- function asksIn(runDir) {
123
- if (!existsSync(join(runDir, BROWSER_ASK_DIR)))
124
- return [];
125
- const dir = askDir(runDir);
126
- if (!dir)
127
- return [];
128
- const found = [];
129
- for (const name of readdirSync(dir)) {
130
- const id = /^([A-Za-z0-9_-]{32})\.json$/.exec(name)?.[1];
131
- const ask = id ? pendingOf(readOwn(dir, name), id) : undefined;
132
- if (!ask)
133
- continue;
134
- const answer = answerOf(readOwn(dir, `${ask.id}.answer.json`));
135
- found.push({ ask, ...(answer ? { answer } : {}) });
136
- }
137
- return found.sort((a, b) => Date.parse(b.ask.asked_at) - Date.parse(a.ask.asked_at) || b.ask.id.localeCompare(a.ask.id));
138
- }
139
- /** The ask the run waits on: the newest unanswered one that has not expired, or undefined. Read where a run's status is
140
- * read (runs.ts statusOf), so a run with no ask costs one existence check. */
141
- export function openAsk(runDir, now = Date.now()) {
142
- const waiting = waitingAsk(runDir);
143
- return waiting && Date.parse(waiting.expires_at) > now ? waiting : undefined;
144
- }
145
- /** The newest unanswered ask, expired or not: one a process must still take up (answer it, or write its expiry), as a
146
- * restarted run's process does. */
147
- export function waitingAsk(runDir) {
148
- try {
149
- return asksIn(runDir).find(({ answer }) => !answer)?.ask;
150
- }
151
- catch {
152
- return undefined;
153
- }
154
- }
155
- /** Whether the run's directory still holds an ask's record, answered or not: one its agent's call may still be waiting
156
- * on (the records go when the run ends, or when its process lets its sessions go). */
157
- export function asked(runDir) {
158
- try {
159
- return asksIn(runDir).length > 0;
160
- }
161
- catch {
162
- return false;
163
- }
164
- }
165
- /** The ask the run waits on (`which`: "open", unexpired, as its status reads it; "waiting", expired or not, as a process
166
- * must still take up) once its own waiting row is in `rows`: the run's process writes the record first, then commits the
167
- * row. Each ask on a session writes one waiting row, in the order asked, so the nth ask on a session is in once that
168
- * session has n waiting rows, whatever other asks (another conversation's, answered or not) wrote meanwhile. */
169
- export function askShown(runDir, rows, which = "open") {
170
- const ask = which === "open" ? openAsk(runDir) : waitingAsk(runDir);
171
- if (!ask)
172
- return undefined;
173
- const on = asksIn(runDir).map(({ ask: each }) => each).filter((each) => each.tag === ask.tag).reverse();
174
- const nth = on.findIndex((each) => each.id === ask.id) + 1;
175
- return rows.filter((row) => row.kind === "waiting" && row.session === ask.tag).length >= nth ? ask : undefined;
176
- }
177
- /** The answer to ask `id`, or the first answer written now (at `at`, ms): `outcome` unless one is there already. */
178
- function answerOnce(dir, id, outcome, reason, at = Date.now()) {
179
- if (writeOwn(dir, `${id}.answer.json`, { outcome, at: new Date(at).toISOString(), ...(reason ? { reason } : {}) }, true))
180
- return outcome;
181
- return answerOf(readOwn(dir, `${id}.answer.json`))?.outcome ?? outcome;
182
- }
183
- /** The owner's answer to the run's ask: the newest one still waiting, as `openAsk` reads it (two conversations may each
184
- * ask), written when it is the first (`first`); with none waiting, the answer the newest one has. An ask past its expiry
185
- * has `expired`. Undefined when the run has asked nothing. */
186
- export function answerAsk(runDir, outcome, now = Date.now()) {
187
- const asks = asksIn(runDir);
188
- const target = asks.find(({ answer }) => !answer) ?? asks[0];
189
- const dir = askDir(runDir);
190
- if (!target || !dir)
191
- return undefined;
192
- if (target.answer)
193
- return { outcome: target.answer.outcome, first: false };
194
- if (Date.parse(target.ask.expires_at) <= now)
195
- return { outcome: answerOnce(dir, target.ask.id, "expired", undefined, now), first: false };
196
- const answered = answerOnce(dir, target.ask.id, outcome, undefined, now);
197
- return { outcome: answered, first: answered === outcome };
198
- }
199
- /** Removes every ask: the run's process that made them is gone. */
200
- export function dropAsks(runDir) {
201
- try {
202
- rmSync(join(runDir, BROWSER_ASK_DIR), { recursive: true, force: true });
203
- }
204
- catch {
205
- // left for the next start's, or the next exit's
206
- }
207
- }
208
39
  /** The rows a person's turns leave, beside the waiting row an ask writes. */
209
40
  const TAKEN = "You took over the browser";
210
41
  const GIVEN_BACK = "You handed the browser back";
@@ -238,9 +69,10 @@ const WAIT_WHAT = "keeping the browser open while you answer";
238
69
  const WAIT_SESSION_GONE = "the browser session it kept open for the person was let go";
239
70
  /** Why such a wait ends at its bound: the one a browser hand-over's ask waits (holdMs, PERSON_HOLD_MS by default). */
240
71
  const waitExpired = (holdMs) => `the person did not answer within ${holdMs >= 60_000 ? `${Math.round(holdMs / 60_000)} minutes` : `${Math.round(holdMs / 1000)} seconds`}, the bound a browser hand-over waits`;
241
- /** The run's process's side, for the run at `root`: `take` for the live view's takeOver, `handoff` for pi-browser's
242
- * HandoffPort. `gates` is the live view's registry (pi-browser's driving gates); `personTime` holds the person's time
243
- * under the cap (browser-cost.ts); `note` commits a root entry, which reaches the run's timeline. */
72
+ /** The run's process's side: `take` for the live view's takeOver, `handoff` for pi-browser's HandoffPort. `gates` is the
73
+ * live view's registry (pi-browser's driving gates); `personTime` holds the person's time under the cap
74
+ * (browser-cost.ts); `note` commits a root entry, which reaches the run's timeline. Every ask and every answer is an
75
+ * entry of the run's journal, read back through `asks` and `answered`. */
244
76
  export function personHands(options) {
245
77
  const holdMs = options.holdMs ?? PERSON_HOLD_MS;
246
78
  const timers = options.timers ?? { set: (run, ms) => setTimeout(run, ms).unref(), clear: (handle) => clearTimeout(handle) };
@@ -253,24 +85,40 @@ export function personHands(options) {
253
85
  let closed = false;
254
86
  const CLOSED = { refused: "the run's process is letting go of the browser" };
255
87
  const note = (kind, data) => options.note(kind, data).catch(() => undefined);
256
- /** The run's journal holds the answers (options.answered): the runner's path. */
257
- const journal = options.answered;
88
+ /** Each ask as the journal has it (its waiting entry), once read or made here: an ask never changes. */
89
+ const known = new Map();
90
+ /** The asks the journal holds, read into `known`; a read that fails leaves what is known. */
91
+ const readAsks = async () => {
92
+ for (const ask of await options.asks().catch(() => []))
93
+ if (ID.test(ask.id) && TAG.test(ask.tag))
94
+ known.set(ask.id, ask);
95
+ };
96
+ /** Ask `id` as the journal has it, read when it is not known yet. */
97
+ const recall = async (id) => {
98
+ if (!known.has(id))
99
+ await readAsks();
100
+ return known.get(id);
101
+ };
258
102
  /** Each ask's answer as the journal has it, once read: an answer never changes. */
259
103
  const fromJournal = new Map();
260
104
  /** The answer this process is writing for an ask, if any: a read waits for it. */
261
105
  const writing = new Map();
262
106
  /** Ask `id`'s answer from the journal, read through. */
263
107
  const journalRead = async (id) => {
264
- const known = fromJournal.get(id);
265
- if (known || !journal)
266
- return known;
267
- const found = await journal(id).catch(() => undefined);
108
+ const had = fromJournal.get(id);
109
+ if (had)
110
+ return had;
111
+ const found = await options.answered(id).catch(() => undefined);
268
112
  if (found)
269
113
  fromJournal.set(id, found);
270
114
  return found;
271
115
  };
116
+ /** The live view's hand-backs still finding the ask they answer (givenDone): a read of an answer waits for them, so the
117
+ * agent's wait hears the hand-back as soon as the person gave it. */
118
+ const giving = new Set();
272
119
  /** Ask `id`'s answer from the journal, once any this process is writing is in. */
273
120
  const readJournal = async (id) => {
121
+ await Promise.all([...giving]);
274
122
  await writing.get(id);
275
123
  return journalRead(id);
276
124
  };
@@ -443,48 +291,40 @@ export function personHands(options) {
443
291
  };
444
292
  /** Ask `id` ended at the run's cap (`words`): expired, written as its answer (the first, as any is), its wait told why. */
445
293
  const capAsk = (id, words) => {
446
- const dir = askDir(options.root);
447
- if (!dir || settled.has(id))
294
+ if (settled.has(id))
448
295
  return;
449
296
  capped.set(id, words);
450
- if (journal) {
451
- // The runner's path: the end is the journal's answer, now, unless the ask has one there already.
452
- const tag = open.get(id)?.tag ?? pendingOf(readOwn(dir, `${id}.json`), id)?.tag;
453
- if (tag)
454
- void answerInJournal(id, tag, "expired", new Date(now()).toISOString(), words).then(() => settle(id), () => undefined);
455
- return;
456
- }
457
- answerOnce(dir, id, "expired", words, now());
458
- settle(id);
297
+ // The end is the journal's answer, now, unless the ask has one there already.
298
+ const tag = open.get(id)?.tag ?? known.get(id)?.tag;
299
+ if (tag)
300
+ void answerInJournal(id, tag, "expired", new Date(now()).toISOString(), words).then(() => settle(id), () => undefined);
459
301
  };
460
- /** Session `tag`'s newest ask still waiting (unanswered, unexpired), answered done: the person handed that session's
461
- * browser back. Its hold goes with it (settle), and another session's ask is never touched. True when an ask was
462
- * settled here, whose row (settle's) says the hand-back. */
463
- const givenDone = (tag) => {
464
- const dir = askDir(options.root);
465
- // On the runner's path an ask's answer is the journal's (an answer file is never read there).
466
- const unanswered = (ask, answer) => (journal ? !fromJournal.has(ask.id) : !answer);
467
- const waiting = dir ? asksIn(options.root).find(({ ask, answer }) => unanswered(ask, answer) && ask.tag === tag && Date.parse(ask.expires_at) > Date.now())?.ask : undefined;
468
- if (!dir || !waiting || settled.has(waiting.id))
469
- return false;
470
- if (journal) {
302
+ /** Session `tag`'s newest ask still waiting (unanswered, unexpired), as the journal has it, answered done: the person
303
+ * handed that session's browser back. Its hold goes with it (settle), and another session's ask is never touched. True
304
+ * when an ask was answered here, whose row (settle's) says the hand-back. `at` (ms) is when the person handed it back:
305
+ * an ask open then is answered then, though the journal's read finishes after its expiry. */
306
+ const givenDone = async (tag, at) => {
307
+ await readAsks();
308
+ const newest = [...known.values()].filter((ask) => ask.tag === tag).sort((a, b) => Date.parse(b.asked_at) - Date.parse(a.asked_at) || b.id.localeCompare(a.id));
309
+ for (const ask of newest) {
310
+ await writing.get(ask.id);
311
+ if (settled.has(ask.id) || Date.parse(ask.expires_at) <= at || (await journalRead(ask.id)))
312
+ continue;
471
313
  // Written as the journal's answer, now, unless the ask has one there already (a person's answer that came first
472
314
  // writes its own row, settle's, as this one would).
473
- void answerInJournal(waiting.id, tag, "done", new Date(now()).toISOString()).then(() => settle(waiting.id), () => undefined);
315
+ await answerInJournal(ask.id, tag, "done", new Date(at).toISOString()).then(() => settle(ask.id), () => undefined);
474
316
  return true;
475
317
  }
476
- answerOnce(dir, waiting.id, "done", undefined, now());
477
- return settle(waiting.id) !== undefined;
318
+ return false;
478
319
  };
479
- /** Ask `id` as its record on disk has it, taken up by this process: one an earlier process of the run made, whose wait
480
- * this process resumes (pi-browser polls `outcome` again, or reruns `request`). Its time is no longer held (that process
481
- * is gone, and its holds with it). Undefined when there is no such record. */
320
+ /** Ask `id` as the run's journal has it (read into `known` first), taken up by this process: one an earlier process of the
321
+ * run made, whose wait this process resumes (pi-browser polls `outcome` again, or reruns `request`). Its time is no
322
+ * longer held (that process is gone, and its holds with it). Undefined when the journal holds no such ask. */
482
323
  const adopt = (id) => {
483
- const known = open.get(id);
484
- if (known)
485
- return known;
486
- const dir = askDir(options.root);
487
- const kept = dir ? pendingOf(readOwn(dir, `${id}.json`), id) : undefined;
324
+ const taken = open.get(id);
325
+ if (taken)
326
+ return taken;
327
+ const kept = known.get(id);
488
328
  if (!kept)
489
329
  return undefined;
490
330
  const ask = { tag: kept.tag, expiresAt: Date.parse(kept.expires_at), drop() { } };
@@ -509,18 +349,6 @@ export function personHands(options) {
509
349
  }, () => undefined);
510
350
  return ask;
511
351
  };
512
- /** Ask `id`, taken up from an earlier process, whose row that process never committed (it ended between the record and
513
- * the row): the row is committed now, so the run shows the ask and its notice goes out. The nth ask on a session is in
514
- * once the session has n waiting rows, as askShown reads it. An ask answered or expired needs none. */
515
- const reshow = async (id) => {
516
- const dir = askDir(options.root);
517
- const kept = dir && options.waiting ? pendingOf(readOwn(dir, `${id}.json`), id) : undefined;
518
- if (!dir || !kept || settled.has(id) || (journal ? await readJournal(id) : answerOf(readOwn(dir, `${id}.answer.json`))) || Date.parse(kept.expires_at) <= Date.now())
519
- return;
520
- const nth = asksIn(options.root).map(({ ask: each }) => each).filter((each) => each.tag === kept.tag).reverse().findIndex((each) => each.id === id) + 1;
521
- if (nth > 0 && (await options.waiting(kept.tag)) < nth)
522
- await note("agent.handover", waitingEntry(kept));
523
- };
524
352
  /** Ask `id`'s answer, once there is one (the person's, or `expired` once it is due, written here): its hold dropped, any
525
353
  * take-over of its session ended, and its row written, once. An ask this process did not make is taken up first. */
526
354
  const settle = (id) => {
@@ -528,12 +356,11 @@ export function personHands(options) {
528
356
  if (known)
529
357
  return known;
530
358
  const ask = adopt(id);
531
- const dir = askDir(options.root);
532
- if (!ask || !dir)
359
+ if (!ask)
533
360
  return undefined;
534
- // On the runner's path the answer is the journal's, as last read (refresh writes a lapsed ask's expiry there first).
535
- const written = journal ? fromJournal.get(id) : answerOf(readOwn(dir, `${id}.answer.json`));
536
- const answered = written?.outcome ?? (!journal && Date.now() >= ask.expiresAt ? answerOnce(dir, id, "expired", undefined, now()) : undefined);
361
+ // The answer is the journal's, as last read (refresh writes a lapsed ask's expiry there first).
362
+ const written = fromJournal.get(id);
363
+ const answered = written?.outcome;
537
364
  if (!answered)
538
365
  return undefined;
539
366
  // The cap's words, kept with the answer: a process that takes the ask up after a restart tells them too.
@@ -551,10 +378,10 @@ export function personHands(options) {
551
378
  (clearInterval(poll), (poll = undefined));
552
379
  return answered;
553
380
  };
554
- /** On the runner's path, before settle reads ask `id`: its answer read from the journal, or, once it lapsed with none,
555
- * its expiry written there at the expiry's time (the first answer stands, whoever's it is). */
381
+ /** Before settle reads ask `id`: its answer read from the journal, or, once it lapsed with none, its expiry written there
382
+ * at the expiry's time (the first answer stands, whoever's it is). */
556
383
  const refresh = async (id) => {
557
- if (!journal || settled.has(id) || (await readJournal(id)))
384
+ if (settled.has(id) || (await readJournal(id)))
558
385
  return;
559
386
  const ask = adopt(id);
560
387
  if (ask && Date.now() >= ask.expiresAt)
@@ -591,23 +418,30 @@ export function personHands(options) {
591
418
  },
592
419
  end: (why) => {
593
420
  if (ended)
594
- return;
421
+ return Promise.resolve();
595
422
  ended = true;
596
423
  const words = ledgers.get(tag)?.refused;
597
424
  release(tag, TAKE_USER);
598
425
  // Ended before it went live (the agent's call still running): the person never had the browser, and no row says
599
426
  // they took it, so none says how it came back. An answered ask writes its own row.
600
427
  if (!live)
601
- return;
428
+ return Promise.resolve();
602
429
  // Handed back by the person (the viewer's Hand back): their word that they are done, so the agent's open ask on
603
430
  // this session is answered done, as the hand-back route would answer it (first answer wins). Never on any other
604
431
  // end (cap, idle, away, released, answered): the person did not say they were done. The answer's own row
605
432
  // ("You handed the browser back", settle's) is then the hand-back's one row: none is written here as well.
606
- const answeredAsk = why === "given" && givenDone(tag);
433
+ const at = now();
607
434
  if (why === "cap")
608
- void note(HOST_PHASE, { summary: `${CAPPED}${words ? `: ${words}` : ""}`, at: now() });
609
- else if (why !== "answered" && !answeredAsk)
610
- void note(HOST_PHASE, { summary: TAKE_ENDED[why], at: now() });
435
+ return note(HOST_PHASE, { summary: `${CAPPED}${words ? `: ${words}` : ""}`, at });
436
+ if (why === "answered")
437
+ return Promise.resolve();
438
+ if (why !== "given")
439
+ return note(HOST_PHASE, { summary: TAKE_ENDED[why], at });
440
+ // The session's open ask is read from the run's journal first; settled once the hand-back's row is written.
441
+ const given = givenDone(tag, at).then((answeredAsk) => (answeredAsk ? undefined : note(HOST_PHASE, { summary: TAKE_ENDED.given, at })), () => undefined);
442
+ giving.add(given);
443
+ void given.finally(() => giving.delete(given));
444
+ return given;
611
445
  },
612
446
  };
613
447
  },
@@ -620,15 +454,10 @@ export function personHands(options) {
620
454
  const id = askIdOf(ask.sessionTag, ask.requestId);
621
455
  if (settled.has(id) || open.has(id))
622
456
  return { interactionId: id };
623
- const dir = askDir(options.root, true);
624
- if (!dir)
625
- return { refused: "the run's directory for a hand-over is not this server's alone" };
626
- // An ask an earlier process of this run made: waited on again, its time no longer held (that process is gone), and
627
- // its row committed if that process ended before it could.
628
- if (adopt(id)) {
629
- await reshow(id);
457
+ // An ask an earlier process of this run made (its waiting entry is in the journal): waited on again, its time no
458
+ // longer held (that process is gone).
459
+ if ((await recall(id)) && adopt(id))
630
460
  return { interactionId: id };
631
- }
632
461
  // A take-over of the same session holds the person's time already: the ask shares it.
633
462
  const user = `ask:${id}`;
634
463
  const refused = await acquire(ask.sessionTag, user, "handing the browser to you", true, now() + holdMs);
@@ -639,19 +468,11 @@ export function personHands(options) {
639
468
  // Redacted whole, then cut to their bound: a held value the cut would split never leaves its head in the record.
640
469
  const shown = (text) => (options.redact ? options.redact(text) : text).slice(0, MAX_TEXT);
641
470
  const record = { id, tag: ask.sessionTag, instruction: shown(ask.instruction), completion_condition: shown(ask.completionCondition), asked_at: new Date(at).toISOString(), expires_at: new Date(at + holdMs).toISOString() };
642
- try {
643
- writeOwn(dir, `${id}.json`, record, false);
644
- }
645
- catch (error) {
646
- hold.drop();
647
- throw error;
648
- }
649
471
  open.set(id, { tag: ask.sessionTag, expiresAt: at + holdMs, drop: () => hold.drop() });
650
472
  watch();
651
- options.afterRecord?.();
652
- // The record is in place before the row: the row's commit is what makes the server read the run's status again.
653
- // The row is what shows the person the ask (askShown): one that cannot be written fails the request, plainly, and
654
- // leaves nothing behind (its hold, its open entry, its record), so the agent's next request makes it afresh.
473
+ // The ask's waiting entry is its one record and its row: its commit is what shows the person the ask and makes the
474
+ // server read the run's status again. One that cannot be written fails the request, plainly, and leaves nothing
475
+ // behind (its hold, its open entry), so the agent's next request makes it afresh.
655
476
  try {
656
477
  await options.note("agent.handover", waitingEntry(record));
657
478
  }
@@ -661,14 +482,9 @@ export function personHands(options) {
661
482
  open.delete(id);
662
483
  if (!open.size && poll)
663
484
  (clearInterval(poll), (poll = undefined));
664
- try {
665
- unlinkSync(join(dir, `${id}.json`));
666
- }
667
- catch {
668
- // gone already
669
- }
670
485
  return { refused: "the hand-over could not be shown to the person (its request was not written to the run's timeline): nothing is held for it, and it can be asked again" };
671
486
  }
487
+ known.set(id, record);
672
488
  return { interactionId: id };
673
489
  },
674
490
  async outcome(interactionId) {
@@ -676,6 +492,7 @@ export function personHands(options) {
676
492
  // the agent's wait ends (it may ask again), never polled forever or matched to another session's record.
677
493
  if (!ID.test(interactionId))
678
494
  return "expired";
495
+ await recall(interactionId);
679
496
  await refresh(interactionId);
680
497
  const answered = settle(interactionId) || "pending";
681
498
  // Ended at the cap: the agent is told so, in the cap's words.
package/dist/cap.d.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { type Ended } from "@parcha/agentrun-kernel";
3
- import { type EntryLike } from "@parcha/pi-durable-agent/timeline";
3
+ import { type EntryLike } from "./timeline/index.js";
4
4
  import type { Api, AssistantMessage, Context, Model, Models } from "@earendil-works/pi-ai";
5
- /** A run's cap in USD, passed to its process. */
6
- export declare const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
7
5
  /** How a request the cap refused begins its error, which the server ends the run with. */
8
6
  export declare const SPEND_CAP_REACHED = "spend_cap_reached";
9
7
  /** How near two dollar figures are the same figure: a sum a float puts a hair past the cap (0.0028 + 0.3072 is
@@ -27,8 +25,6 @@ export declare const BOUND_FIELD = "boundUsd";
27
25
  * case, so no request can pass it. */
28
26
  export declare const CAP_MODES: readonly ["expected", "strict"];
29
27
  export type CapMode = (typeof CAP_MODES)[number];
30
- /** A run's cap mode, passed to its process; absent is "expected". */
31
- export declare const CAP_MODE_ENV = "AGENTRUN_SERVE_CAP_MODE";
32
28
  /** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
33
29
  * Anthropic's 5 (a cache kept that long from its last use; OpenAI's lasts longer). A request later than that is priced
34
30
  * with nothing cached. */
@@ -265,6 +261,13 @@ export declare function meterFiguresIn(storeFile: string): Meters & {
265
261
  others: number;
266
262
  };
267
263
  };
264
+ /** A browser charge's record on the run's root when the run books its money on the runner's one ledger (browser-cost.ts
265
+ * browserSpend's `paid`): the same record a browser TOOL_COST is, for what the browser's process holds and the seconds
266
+ * it was for, under a kind no cost reads. The charge's money is the ledger's paid step alone, which the cap counts and
267
+ * the run's cost (adapter-run-spec.ts endPatch), its timeline and its meters (store-reads/journal.ts withPaidCosts) read,
268
+ * as every paid tool's on the runner: a TOOL_COST beside it would count the same charge twice. Its seconds are the
269
+ * browser_time meter's (meterFiguresFrom). */
270
+ export declare const BROWSER_CHARGED = "agentrun.browser_charged";
268
271
  /** meterFiguresIn's figures from a run's entries by conversation, in log order: the one computation, shared by
269
272
  * meterFiguresIn (reading a settled run's own database) and the one-store reader (store-reads/cap.ts metersOverStore, over
270
273
  * A's journal). Only where the entries come from changes; the figures do not (the money-parity rule), as spentFrom is to
package/dist/cap.js CHANGED
@@ -50,9 +50,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
50
50
  import { existsSync } from "node:fs";
51
51
  import { providerInputOverhead } from "@parcha/agentrun-kernel/host";
52
52
  import { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "@parcha/agentrun-kernel";
53
- import { CAP_WRAPUP, REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
54
- /** A run's cap in USD, passed to its process. */
55
- export const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
53
+ import { CAP_WRAPUP, REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "./timeline/index.js";
56
54
  /** How a request the cap refused begins its error, which the server ends the run with. */
57
55
  export const SPEND_CAP_REACHED = "spend_cap_reached";
58
56
  /** How near two dollar figures are the same figure: a sum a float puts a hair past the cap (0.0028 + 0.3072 is
@@ -75,8 +73,6 @@ export const BOUND_FIELD = "boundUsd";
75
73
  * only a cache miss can pass the cap, by at most the request's bound; "strict" every input token uncached, the worst
76
74
  * case, so no request can pass it. */
77
75
  export const CAP_MODES = ["expected", "strict"];
78
- /** A run's cap mode, passed to its process; absent is "expected". */
79
- export const CAP_MODE_ENV = "AGENTRUN_SERVE_CAP_MODE";
80
76
  /** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
81
77
  * Anthropic's 5 (a cache kept that long from its last use; OpenAI's lasts longer). A request later than that is priced
82
78
  * with nothing cached. */
@@ -657,6 +653,13 @@ export function meterFiguresIn(storeFile) {
657
653
  return { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
658
654
  return readRunDbSync(storeFile, false, (db) => meterFiguresFrom(db.prepare("SELECT conversation_id AS conversation, record FROM entries ORDER BY rowid").all().map((row) => ({ conversation: Number(row.conversation), entry: JSON.parse(String(row.record)) }))));
659
655
  }
656
+ /** A browser charge's record on the run's root when the run books its money on the runner's one ledger (browser-cost.ts
657
+ * browserSpend's `paid`): the same record a browser TOOL_COST is, for what the browser's process holds and the seconds
658
+ * it was for, under a kind no cost reads. The charge's money is the ledger's paid step alone, which the cap counts and
659
+ * the run's cost (adapter-run-spec.ts endPatch), its timeline and its meters (store-reads/journal.ts withPaidCosts) read,
660
+ * as every paid tool's on the runner: a TOOL_COST beside it would count the same charge twice. Its seconds are the
661
+ * browser_time meter's (meterFiguresFrom). */
662
+ export const BROWSER_CHARGED = "agentrun.browser_charged";
660
663
  /** meterFiguresIn's figures from a run's entries by conversation, in log order: the one computation, shared by
661
664
  * meterFiguresIn (reading a settled run's own database) and the one-store reader (store-reads/cap.ts metersOverStore, over
662
665
  * A's journal). Only where the entries come from changes; the figures do not (the money-parity rule), as spentFrom is to
@@ -673,6 +676,10 @@ export function meterFiguresFrom(rows) {
673
676
  const known = { tokens: 0, browser: 0, others: 0 };
674
677
  for (const { entry } of rows) {
675
678
  const data = (entry.data ?? {});
679
+ // On the runner a browser charge's money reaches here from the run's ledger (a TOOL_COST of tool "browser", with no
680
+ // seconds) and its seconds from its record on the root: each counted once.
681
+ if (entry.kind === BROWSER_CHARGED && data.tool === "browser")
682
+ browser.seconds += figureOf(data.seconds) ?? 0;
676
683
  if (entry.kind === TOOL_STARTED)
677
684
  marks.add(data.call);
678
685
  else if (entry.kind === TOOL_COST)