@parcha/agentrun-serve 0.1.0-beta.36 → 0.1.0-beta.37

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 (325) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +158 -52
  3. package/dist/attach-conformance-cli.d.ts +1 -0
  4. package/dist/attach-conformance-cli.js +18 -0
  5. package/dist/attach-conformance.d.ts +25 -0
  6. package/dist/attach-conformance.js +343 -0
  7. package/dist/browser-cost.d.ts +1 -1
  8. package/dist/browser-live.d.ts +20 -8
  9. package/dist/browser-live.js +50 -27
  10. package/dist/cap.d.ts +0 -17
  11. package/dist/cap.js +0 -91
  12. package/dist/catalog.d.ts +1 -12
  13. package/dist/catalog.js +3 -33
  14. package/dist/cli.js +13 -4
  15. package/dist/composio-preset.d.ts +36 -0
  16. package/dist/composio-preset.js +179 -0
  17. package/dist/computer-attach.d.ts +125 -0
  18. package/dist/computer-attach.js +330 -0
  19. package/dist/computer-calls.d.ts +48 -0
  20. package/dist/computer-calls.js +126 -0
  21. package/dist/computer-channel.d.ts +57 -0
  22. package/dist/computer-channel.js +115 -0
  23. package/dist/computer-commands.d.ts +1 -1
  24. package/dist/computer-held-routes.d.ts +35 -0
  25. package/dist/computer-held-routes.js +106 -0
  26. package/dist/computer-held.d.ts +48 -0
  27. package/dist/computer-held.js +87 -0
  28. package/dist/computer-keys.d.ts +21 -1
  29. package/dist/computer-keys.js +53 -11
  30. package/dist/computer-live.d.ts +160 -0
  31. package/dist/computer-live.js +643 -0
  32. package/dist/computer-view.d.ts +13 -0
  33. package/dist/computer-view.js +50 -3
  34. package/dist/computer-viewer.d.ts +6 -0
  35. package/dist/computer-viewer.js +297 -0
  36. package/dist/computers.d.ts +33 -7
  37. package/dist/computers.js +50 -8
  38. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  39. package/dist/console/assets/index-DRN62V5v.css +1 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/faux-computers.d.ts +9 -20
  42. package/dist/faux-computers.js +53 -25
  43. package/dist/github-connection.d.ts +10 -2
  44. package/dist/github-connection.js +65 -2
  45. package/dist/github-faux.js +1 -1
  46. package/dist/graph-view.d.ts +1 -1
  47. package/dist/harness.d.ts +1 -0
  48. package/dist/harness.js +35 -1
  49. package/dist/host-tools.d.ts +1 -1
  50. package/dist/hosted-search.d.ts +5 -4
  51. package/dist/hosted-search.js +2 -7
  52. package/dist/import-sources.d.ts +10 -0
  53. package/dist/import-sources.js +44 -2
  54. package/dist/import.d.ts +3 -3
  55. package/dist/import.js +37 -6
  56. package/dist/learn/check.d.ts +4 -1
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +4 -2
  59. package/dist/learn/commit.js +5 -5
  60. package/dist/learn/folder.d.ts +6 -0
  61. package/dist/learn/folder.js +4 -1
  62. package/dist/learn/general.d.ts +66 -0
  63. package/dist/learn/general.js +73 -0
  64. package/dist/learn/grade.d.ts +4 -0
  65. package/dist/learn/grade.js +22 -1
  66. package/dist/learn/reflect.d.ts +10 -1
  67. package/dist/learn/reflect.js +14 -4
  68. package/dist/learn/skills.d.ts +33 -5
  69. package/dist/learn/skills.js +53 -7
  70. package/dist/learned-workflow.d.ts +24 -0
  71. package/dist/learned-workflow.js +66 -3
  72. package/dist/learning-batch.d.ts +283 -0
  73. package/dist/learning-batch.js +574 -0
  74. package/dist/learning-evals.d.ts +33 -0
  75. package/dist/learning-evals.js +98 -0
  76. package/dist/learning-routes.d.ts +25 -2
  77. package/dist/learning-routes.js +39 -6
  78. package/dist/learning-words.d.ts +6 -0
  79. package/dist/learning-words.js +6 -0
  80. package/dist/learning.d.ts +28 -15
  81. package/dist/learning.js +84 -44
  82. package/dist/live/stream.js +6 -3
  83. package/dist/live/translate.d.ts +4 -3
  84. package/dist/live/translate.js +8 -4
  85. package/dist/live-reach.d.ts +37 -0
  86. package/dist/live-reach.js +62 -0
  87. package/dist/mcp-gateway.d.ts +9 -0
  88. package/dist/mcp-gateway.js +60 -11
  89. package/dist/mcp-oauth.d.ts +57 -7
  90. package/dist/mcp-oauth.js +133 -18
  91. package/dist/mcp-private-hosts.d.ts +4 -4
  92. package/dist/mcp-private-hosts.js +20 -12
  93. package/dist/mcp-probe.d.ts +19 -2
  94. package/dist/mcp-probe.js +44 -9
  95. package/dist/mcp-secret-writes.js +4 -0
  96. package/dist/mcp-servers-store.d.ts +38 -15
  97. package/dist/mcp-servers-store.js +112 -20
  98. package/dist/mcp-store.d.ts +10 -4
  99. package/dist/mcp-store.js +17 -6
  100. package/dist/model-form.d.ts +26 -0
  101. package/dist/model-form.js +80 -0
  102. package/dist/model.js +23 -10
  103. package/dist/openapi.js +386 -21
  104. package/dist/page.d.ts +18 -0
  105. package/dist/page.js +48 -20
  106. package/dist/paid-calls.d.ts +1 -1
  107. package/dist/place-offers.d.ts +2 -3
  108. package/dist/place-offers.js +3 -7
  109. package/dist/place.js +1 -2
  110. package/dist/print.d.ts +15 -1
  111. package/dist/print.js +14 -3
  112. package/dist/propose.d.ts +3 -0
  113. package/dist/propose.js +13 -5
  114. package/dist/provider.js +3 -2
  115. package/dist/reflect-range.d.ts +8 -1
  116. package/dist/reflect-range.js +1 -1
  117. package/dist/run-launch.d.ts +14 -2
  118. package/dist/run-launch.js +9 -4
  119. package/dist/run-learning-served.d.ts +2 -2
  120. package/dist/run-reads-over-store.d.ts +1 -1
  121. package/dist/run-repo.d.ts +20 -0
  122. package/dist/run-repo.js +63 -0
  123. package/dist/run-timeline-served.d.ts +1 -1
  124. package/dist/run-view.d.ts +3 -3
  125. package/dist/run-view.js +14 -7
  126. package/dist/runner/adapter-loop.d.ts +23 -7
  127. package/dist/runner/adapter-loop.js +648 -62
  128. package/dist/runner/adapter-run-spec.d.ts +11 -3
  129. package/dist/runner/adapter-run-spec.js +77 -22
  130. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  131. package/dist/runner/adapters/pi-computer.js +43 -0
  132. package/dist/runner/adapters/pi.d.ts +9 -4
  133. package/dist/runner/adapters/pi.js +76 -14
  134. package/dist/runner/beside.d.ts +7 -3
  135. package/dist/runner/beside.js +21 -11
  136. package/dist/runner/claim-secrets.d.ts +4 -0
  137. package/dist/runner/claim-secrets.js +6 -1
  138. package/dist/runner/cli-run-spec.d.ts +20 -3
  139. package/dist/runner/cli-run-spec.js +113 -43
  140. package/dist/runner/commands.d.ts +3 -1
  141. package/dist/runner/commands.js +28 -3
  142. package/dist/runner/computer-channel.d.ts +34 -0
  143. package/dist/runner/computer-channel.js +61 -0
  144. package/dist/runner/conformance/harness.js +80 -14
  145. package/dist/runner/conformance/subject.d.ts +1 -1
  146. package/dist/runner/dispatch.js +3 -0
  147. package/dist/runner/end-of-run.d.ts +22 -12
  148. package/dist/runner/end-of-run.js +38 -16
  149. package/dist/runner/github-app.d.ts +2 -1
  150. package/dist/runner/github-app.js +4 -2
  151. package/dist/runner/harness-loops.js +15 -1
  152. package/dist/runner/held-run.d.ts +65 -0
  153. package/dist/runner/held-run.js +158 -0
  154. package/dist/runner/journal-kinds.d.ts +20 -1
  155. package/dist/runner/journal-kinds.js +14 -0
  156. package/dist/runner/journal-reader.d.ts +5 -4
  157. package/dist/runner/journal-reader.js +12 -10
  158. package/dist/runner/learning-ask.d.ts +7 -1
  159. package/dist/runner/learning-ask.js +21 -6
  160. package/dist/runner/learning-dispatch.d.ts +22 -0
  161. package/dist/runner/learning-dispatch.js +77 -10
  162. package/dist/runner/learning-end.d.ts +22 -1
  163. package/dist/runner/learning-end.js +92 -12
  164. package/dist/runner/learning-factory.d.ts +1 -1
  165. package/dist/runner/learning-factory.js +11 -5
  166. package/dist/runner/learning-loop.d.ts +67 -7
  167. package/dist/runner/learning-loop.js +173 -21
  168. package/dist/runner/learning-seed.d.ts +7 -0
  169. package/dist/runner/learning-seed.js +13 -0
  170. package/dist/runner/live-ticker.js +1 -0
  171. package/dist/runner/loop-contract.d.ts +8 -1
  172. package/dist/runner/loop.d.ts +5 -1
  173. package/dist/runner/loop.js +2 -1
  174. package/dist/runner/main.d.ts +13 -1
  175. package/dist/runner/main.js +27 -5
  176. package/dist/runner/mcp-claim.d.ts +10 -7
  177. package/dist/runner/mcp-claim.js +113 -24
  178. package/dist/runner/mcp-github.js +1 -1
  179. package/dist/runner/mcp-run.d.ts +5 -5
  180. package/dist/runner/mcp-run.js +15 -3
  181. package/dist/runner/metrics.d.ts +11 -2
  182. package/dist/runner/metrics.js +12 -2
  183. package/dist/runner/pr-checkout.d.ts +1 -0
  184. package/dist/runner/pr-checkout.js +1 -1
  185. package/dist/runner/reflect-hook.d.ts +18 -0
  186. package/dist/runner/reflect-hook.js +20 -8
  187. package/dist/runner/runner.d.ts +26 -0
  188. package/dist/runner/runner.js +184 -15
  189. package/dist/runner/scratch-sweep.d.ts +13 -0
  190. package/dist/runner/scratch-sweep.js +62 -0
  191. package/dist/runner/sessions.d.ts +1 -1
  192. package/dist/runner/store-port.d.ts +4 -2
  193. package/dist/runner/store-secrets.js +4 -3
  194. package/dist/runner/subagent.js +3 -1
  195. package/dist/runner/workflow-host.d.ts +6 -1
  196. package/dist/runner/workflow-host.js +1 -1
  197. package/dist/runner/workflow-loop.d.ts +1 -1
  198. package/dist/runner/workflow-spec.d.ts +14 -2
  199. package/dist/runner/workflow-spec.js +56 -20
  200. package/dist/runs-over-store.d.ts +6 -1
  201. package/dist/runs-over-store.js +38 -9
  202. package/dist/seal-key.js +3 -3
  203. package/dist/sealed-settings-store.d.ts +5 -2
  204. package/dist/sealed-settings-store.js +10 -4
  205. package/dist/secret-writes.d.ts +5 -4
  206. package/dist/secret-writes.js +5 -4
  207. package/dist/server-secrets-store.d.ts +4 -3
  208. package/dist/server-secrets-store.js +15 -9
  209. package/dist/server-secrets.js +3 -2
  210. package/dist/server.d.ts +43 -14
  211. package/dist/server.js +472 -126
  212. package/dist/settings-wake.d.ts +21 -0
  213. package/dist/settings-wake.js +59 -0
  214. package/dist/standard-webhooks.d.ts +4 -1
  215. package/dist/standard-webhooks.js +8 -4
  216. package/dist/store/command-wake.d.ts +12 -0
  217. package/dist/store/command-wake.js +37 -0
  218. package/dist/store/dialect.d.ts +6 -0
  219. package/dist/store/dialect.js +5 -0
  220. package/dist/store/index.d.ts +1 -1
  221. package/dist/store/journal/storage.d.ts +3 -2
  222. package/dist/store/journal/storage.js +13 -5
  223. package/dist/store/postgres/dialect.js +4 -0
  224. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  225. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  226. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  227. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  228. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  229. package/dist/store/schema.d.ts +1 -1
  230. package/dist/store/schema.js +77 -8
  231. package/dist/store/sqlite/run-patch.d.ts +7 -5
  232. package/dist/store/sqlite/run-patch.js +28 -13
  233. package/dist/store/sqlite/store.js +272 -54
  234. package/dist/store/store.d.ts +268 -9
  235. package/dist/store/store.js +12 -1
  236. package/dist/store-reads/cap.d.ts +1 -1
  237. package/dist/store-reads/cap.js +8 -1
  238. package/dist/store-reads/decisions.d.ts +2 -2
  239. package/dist/store-reads/decisions.js +1 -1
  240. package/dist/store-reads/import-summary.d.ts +1 -1
  241. package/dist/store-reads/journal.d.ts +5 -4
  242. package/dist/store-reads/journal.js +73 -15
  243. package/dist/store-reads/learning.d.ts +20 -4
  244. package/dist/store-reads/learning.js +74 -18
  245. package/dist/store-reads/runs.d.ts +1 -1
  246. package/dist/store-reads/workflow.d.ts +1 -1
  247. package/dist/store-view.d.ts +5 -0
  248. package/dist/store-view.js +26 -11
  249. package/dist/template-eval.js +6 -4
  250. package/dist/template-github-permissions.d.ts +22 -8
  251. package/dist/template-github-permissions.js +35 -15
  252. package/dist/timeline/timeline.d.ts +27 -0
  253. package/dist/timeline/timeline.js +10 -9
  254. package/dist/timeline/util.d.ts +4 -0
  255. package/dist/timeline/util.js +14 -0
  256. package/dist/tool-budget.d.ts +19 -7
  257. package/dist/tool-budget.js +14 -8
  258. package/dist/tool-gate.d.ts +16 -9
  259. package/dist/tool-gate.js +53 -42
  260. package/dist/tool-plane.d.ts +16 -12
  261. package/dist/tool-plane.js +9 -4
  262. package/dist/tools.d.ts +13 -4
  263. package/dist/tools.js +13 -4
  264. package/dist/trigger-adapter.d.ts +4 -0
  265. package/dist/trigger-secrets-shown.d.ts +2 -2
  266. package/dist/trigger-secrets-shown.js +1 -1
  267. package/dist/trigger-signatures.d.ts +25 -6
  268. package/dist/trigger-signatures.js +41 -7
  269. package/dist/trigger-targets.d.ts +2 -0
  270. package/dist/trigger-targets.js +1 -0
  271. package/dist/trigger-webhook.js +5 -2
  272. package/dist/triggers.d.ts +7 -3
  273. package/dist/triggers.js +35 -5
  274. package/dist/turns.js +16 -1
  275. package/dist/validate.js +11 -1
  276. package/dist/web-fetch.d.ts +1 -1
  277. package/dist/web-search.d.ts +10 -5
  278. package/dist/web-search.js +7 -6
  279. package/dist/webhooks.d.ts +145 -102
  280. package/dist/webhooks.js +559 -322
  281. package/dist/workflow/decisions.d.ts +1 -1
  282. package/dist/workflow/node-runner.d.ts +2 -1
  283. package/dist/workflow/node.d.ts +2 -1
  284. package/dist/workflow/node.js +3 -1
  285. package/dist/workflow/pi-versions.d.ts +23 -0
  286. package/dist/workflow/pi-versions.js +57 -0
  287. package/dist/workflow/record-tool.d.ts +2 -1
  288. package/dist/workflow/store.d.ts +1 -1
  289. package/dist/workflow/task.js +3 -2
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/attached-computers.d.ts +41 -0
  292. package/dist/workspace/attached-computers.js +114 -0
  293. package/dist/workspace/computer-deps.d.ts +16 -9
  294. package/dist/workspace/computer-deps.js +19 -7
  295. package/dist/workspace/computer-for-claim.d.ts +17 -8
  296. package/dist/workspace/computer-for-claim.js +62 -21
  297. package/dist/workspace/computer-hold.d.ts +11 -27
  298. package/dist/workspace/computer-hold.js +36 -56
  299. package/dist/workspace/computer-ledger.d.ts +3 -1
  300. package/dist/workspace/computer-ledger.js +4 -0
  301. package/dist/workspace/computer-mcp.d.ts +25 -0
  302. package/dist/workspace/computer-mcp.js +41 -0
  303. package/dist/workspace/computer-ports.d.ts +4 -13
  304. package/dist/workspace/computer-ports.js +4 -107
  305. package/dist/workspace/computer-script.d.ts +37 -0
  306. package/dist/workspace/computer-script.js +138 -0
  307. package/dist/workspace/executors.d.ts +1 -1
  308. package/dist/workspace/index.d.ts +4 -2
  309. package/dist/workspace/index.js +3 -1
  310. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  311. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  312. package/dist/workspace/resolve-computer.d.ts +3 -0
  313. package/dist/workspace/resolve-computer.js +8 -2
  314. package/dist/workspace/run-tools.d.ts +32 -15
  315. package/dist/workspace/run-tools.js +23 -30
  316. package/package.json +19 -16
  317. package/templates/market-monitor/agent.md +1 -1
  318. package/dist/console/assets/index-BI4Byidu.js +0 -550
  319. package/dist/console/assets/index-C19gUF2n.css +0 -1
  320. package/dist/run-db.d.ts +0 -53
  321. package/dist/run-db.js +0 -116
  322. package/dist/workflow/readers.d.ts +0 -36
  323. package/dist/workflow/readers.js +0 -145
  324. package/dist/workflow/wal.d.ts +0 -11
  325. package/dist/workflow/wal.js +0 -106
@@ -0,0 +1,330 @@
1
+ // A person's own computer paired with this server, the attach binding's server side (spec/computer/attach.md): the
2
+ // owner's pairing code (POST /v2/computers/pairings), the driver's trade of that code for its computer's token (POST
3
+ // /v2/computers/pair, which needs no token of the server's: the code is the credential), the attach socket the driver
4
+ // dials with that token (GET /v2/computers/attach, a WebSocket), the paired computers as GET /v2/computers lists them,
5
+ // and their removal (DELETE /v2/computers/{id}). The computer package's AttachHub holds each computer's live socket; this
6
+ // module checks who dials, wraps the WebSocket as the AttachSocket the hub takes, and keeps the store's rows.
7
+ //
8
+ // A code is good once for PAIRING_CODE_TTL_MS, and a token until its computer is removed: the store keeps the SHA-256 of
9
+ // each, never the value. A wrong, used or expired code is one answer, 404 with no word about which, and each source
10
+ // address gets PAIR_TRIES_PER_MINUTE tries a minute.
11
+ //
12
+ // One process: the hub is this process's memory, so a run takes a paired computer only from a runner in the process
13
+ // that holds its socket (the CLI's start, with its runner beside the server). A runner of its own process refuses one in
14
+ // words (workspace/attached-computers.ts ONE_PROCESS_WORDS); a second server on the same store is refused at its start.
15
+ import { createHash, randomBytes, randomInt } from "node:crypto";
16
+ import { ATTACH_CLOSE, ATTACH_HEARTBEAT_MS, ATTACH_IDLE_MS, ATTACH_SUBPROTOCOL, MAX_LINE_BYTES, PAIRING_CODE_PATTERN, PAIRING_CODE_TTL_MS, PROTOCOL_VERSION, RUN_LABEL } from "@parcha/agentrun-computer";
17
+ import { WebSocketServer } from "ws";
18
+ import { ApiError, invalid } from "./errors.js";
19
+ import { peerKey } from "./owner.js";
20
+ import { registerNotSecretWrite } from "./secret-writes.js";
21
+ import { pairedOf, PAIRED_ID_PREFIX, servesNoKind } from "./workspace/attached-computers.js";
22
+ // Routes under /computers, where a provider's keys are a secret write (computers.ts): these three write none of the
23
+ // owner's secrets, so the API token may call them as the console's session does.
24
+ registerNotSecretWrite("createPairing", "A pairing code is shown once and kept as its hash: it is a one-time code, not a secret of the owner's.");
25
+ registerNotSecretWrite("pairComputer", "The driver trades a pairing code for its own computer's token; nothing of the owner's is written.");
26
+ registerNotSecretWrite("deleteComputer", "Removing a paired computer revokes its token and writes nothing.");
27
+ /** The characters of a pairing code: no 0, O, 1 or I, so a person reads it off a screen without a doubt. */
28
+ export const PAIRING_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
29
+ /** A computer's token starts with this, so a secret scanner knows one. */
30
+ export const ATTACH_TOKEN_PREFIX = "art_";
31
+ /** Pair tries a source address makes in a minute; the next waits. */
32
+ export const PAIR_TRIES_PER_MINUTE = 10;
33
+ const PAIR_WINDOW_MS = 60_000;
34
+ /** The most source addresses the pair limit keeps at once; past it, those with no try in the window go first. */
35
+ const PAIR_PEERS = 10_000;
36
+ /** The one key the addresses the full table has no room for are counted under (no address's key has a space). */
37
+ const OVERFLOW_PEER = "every address past the table";
38
+ /** The longest name a person gives a computer, in characters. */
39
+ export const PAIRED_NAME_MAX = 100;
40
+ /** A WebSocket close frame's reason holds at most this many bytes of UTF-8. */
41
+ const CLOSE_REASON_BYTES = 123;
42
+ /** What the store keeps of a secret: its SHA-256, in hex. */
43
+ export const sha256Hex = (value) => createHash("sha256").update(value).digest("hex");
44
+ /** A new pairing code: eight characters of PAIRING_ALPHABET in two groups of four ("K7PD-W3QX"). */
45
+ export function newPairingCode(pick = randomInt) {
46
+ const chars = Array.from({ length: 8 }, () => PAIRING_ALPHABET[pick(PAIRING_ALPHABET.length)]);
47
+ return `${chars.slice(0, 4).join("")}-${chars.slice(4).join("")}`;
48
+ }
49
+ /** A code as a person typed it, in its one form ("k7pd w3qx" is "K7PD-W3QX"), or undefined when it is not one. */
50
+ export function pairingCodeOf(typed) {
51
+ if (typeof typed !== "string")
52
+ return undefined;
53
+ const bare = typed.toUpperCase().replace(/[\s-]+/g, "");
54
+ const code = `${bare.slice(0, 4)}-${bare.slice(4)}`;
55
+ return bare.length === 8 && PAIRING_CODE_PATTERN.test(code) ? code : undefined;
56
+ }
57
+ /** A new paired computer's id: PAIRED_ID_PREFIX and 16 lowercase letters and digits. */
58
+ export const newPairedId = (pick = randomInt) => `${PAIRED_ID_PREFIX}${Array.from({ length: 16 }, () => "abcdefghijkmnpqrstuvwxyz23456789"[pick(32)]).join("")}`;
59
+ /** A new computer token: ATTACH_TOKEN_PREFIX and 32 random bytes. */
60
+ export const newAttachToken = () => `${ATTACH_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
61
+ /** `reason` cut to what a close frame holds (123 bytes of UTF-8), never inside a character. */
62
+ export function closeReason(reason) {
63
+ if (Buffer.byteLength(reason) <= CLOSE_REASON_BYTES)
64
+ return reason;
65
+ let cut = "";
66
+ for (const char of reason) {
67
+ if (Buffer.byteLength(cut + char) > CLOSE_REASON_BYTES - 3)
68
+ break;
69
+ cut += char;
70
+ }
71
+ return `${cut}...`;
72
+ }
73
+ /** The pair route's limit: PAIR_TRIES_PER_MINUTE tries a minute by source address (peerKey: an IPv6 one by its /64). */
74
+ export class PairTries {
75
+ now;
76
+ peers;
77
+ #tries = new Map();
78
+ constructor(now = Date.now, peers = PAIR_PEERS) {
79
+ this.now = now;
80
+ this.peers = peers;
81
+ }
82
+ /** Counts a try from `address`: ok, or how long until the next is let in. */
83
+ allow(address) {
84
+ const now = this.now();
85
+ let key = peerKey(address);
86
+ if (!this.#tries.has(key) && this.#tries.size >= this.peers) {
87
+ for (const [known, at] of this.#tries)
88
+ if (!at.some((one) => now - one < PAIR_WINDOW_MS))
89
+ this.#tries.delete(known);
90
+ // A table still full of addresses trying now counts every address it has no room for as one: the table never grows
91
+ // past its bound, and no address goes uncounted.
92
+ if (this.#tries.size >= this.peers)
93
+ key = OVERFLOW_PEER;
94
+ }
95
+ const recent = (this.#tries.get(key) ?? []).filter((at) => now - at < PAIR_WINDOW_MS);
96
+ if (recent.length >= PAIR_TRIES_PER_MINUTE)
97
+ return { ok: false, retryAfterMs: recent[0] + PAIR_WINDOW_MS - now };
98
+ this.#tries.set(key, [...recent, now]);
99
+ return { ok: true };
100
+ }
101
+ }
102
+ const KINDS = new Set(["linux", "desktop", "android", "ios", "browser"]);
103
+ const OSES = new Set(["linux", "windows", "macos", "android", "ios"]);
104
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
105
+ /** POST /v2/computers/pair's body checked: its code in its one form, the name, and the driver's hello; or input_invalid
106
+ * naming each field that is wrong. The protocol version is the caller's next check (pairRefusal), not this one's. */
107
+ export function pairBodyOf(body) {
108
+ const issues = [];
109
+ const said = isObject(body) ? body : {};
110
+ if (!isObject(body))
111
+ issues.push({ field: "body", reason: "wrong_type", message: "the body is {code, name, hello}: the pairing code the console showed, the computer's name, and its driver's hello" });
112
+ const code = pairingCodeOf(said.code);
113
+ if (isObject(body) && code === undefined)
114
+ issues.push({ field: "code", reason: "invalid", message: "code is the pairing code the console showed: eight letters and digits, such as K7PD-W3QX" });
115
+ const name = typeof said.name === "string" ? said.name.trim() : "";
116
+ if (isObject(body) && (name === "" || Array.from(name).length > PAIRED_NAME_MAX || /\p{Cc}/u.test(name))) {
117
+ issues.push({ field: "name", reason: "invalid", message: `name is what you call the computer, 1 to ${PAIRED_NAME_MAX} characters on one line` });
118
+ }
119
+ const hello = said.hello;
120
+ if (isObject(body)) {
121
+ if (!isObject(hello))
122
+ issues.push({ field: "hello", reason: "wrong_type", message: "hello is the driver's own answer to hello: {protocol, version, os, kind, arch, groups}" });
123
+ else {
124
+ for (const field of ["protocol", "version", "arch"]) {
125
+ if (typeof hello[field] !== "string" || hello[field] === "")
126
+ issues.push({ field: `hello.${field}`, reason: "missing", message: `hello.${field} is a string, as the driver's hello answers it` });
127
+ }
128
+ if (typeof hello.os !== "string" || !OSES.has(hello.os))
129
+ issues.push({ field: "hello.os", reason: "invalid", message: `hello.os is one of ${[...OSES].join(", ")}` });
130
+ if (typeof hello.kind !== "string" || !KINDS.has(hello.kind))
131
+ issues.push({ field: "hello.kind", reason: "invalid", message: `hello.kind is one of ${[...KINDS].join(", ")}` });
132
+ if (!Array.isArray(hello.groups) || !hello.groups.every((group) => typeof group === "string"))
133
+ issues.push({ field: "hello.groups", reason: "wrong_type", message: "hello.groups is a list of the driver's capability groups" });
134
+ }
135
+ }
136
+ if (issues.length > 0)
137
+ throw invalid(issues);
138
+ return { code: code, name, hello: hello };
139
+ }
140
+ /** Why a driver's hello may not pair here, in the version rule's words (attach.ts helloMismatch), or undefined: its
141
+ * protocol version must be this server's. The code stays good, for the driver once it is updated. */
142
+ export function pairRefusal(name, hello) {
143
+ if (hello.protocol === PROTOCOL_VERSION)
144
+ return undefined;
145
+ return `${name}'s driver ${hello.version} speaks protocol ${hello.protocol}, and this server ${PROTOCOL_VERSION}: update whichever is older (the driver on that computer, or this server, which whoever runs it updates), then pair with the same code`;
146
+ }
147
+ /** A hello's features as the list shows them: each that is on (true) or off with why ({off: words}); anything else a
148
+ * driver sent is left out, so a malformed hello never reaches the console as a shape it does not know. */
149
+ function featuresOf(features) {
150
+ if (!isObject(features))
151
+ return {};
152
+ return Object.fromEntries(Object.entries(features).flatMap(([name, value]) => (value === true ? [[name, true]] : isObject(value) && typeof value.off === "string" ? [[name, { off: value.off }]] : [])));
153
+ }
154
+ export function pairedView(row, hub, serves) {
155
+ const paired = row.hello;
156
+ // Kind and os stay what it paired as (another is refused at hello); the rest follows its driver's live hello.
157
+ const hello = hub.hello(row.id) ?? paired;
158
+ const holder = hub.claimed(row.id)?.[RUN_LABEL] ?? null;
159
+ const until = holder === null ? undefined : hub.deadline(row.id);
160
+ return {
161
+ id: row.id,
162
+ name: row.name,
163
+ kind: String(paired.kind ?? ""),
164
+ serves: [...serves],
165
+ unserved: serves.length === 0 ? (servesNoKind(row.name, paired) ?? null) : null,
166
+ os: String(paired.os ?? ""),
167
+ os_version: typeof hello.osVersion === "string" ? hello.osVersion : null,
168
+ device: hello.device && typeof hello.device.maker === "string" && typeof hello.device.model === "string" ? { maker: hello.device.maker, model: hello.device.model } : null,
169
+ arch: String(hello.arch ?? paired.arch ?? ""),
170
+ screen: hello.screen && [hello.screen.width, hello.screen.height, hello.screen.scale].every((n) => typeof n === "number") ? { width: hello.screen.width, height: hello.screen.height, scale: hello.screen.scale } : null,
171
+ groups: Array.isArray(hello.groups) ? hello.groups.map(String) : [],
172
+ features: featuresOf(hello.features),
173
+ driver: hub.hello(row.id)?.version ?? row.driver,
174
+ online: hub.online(row.id),
175
+ held_by_run: holder,
176
+ held_until: until === undefined ? null : until.toISOString(),
177
+ pairing: row.pairingId,
178
+ created_at: new Date(row.createdAt).toISOString(),
179
+ seen_at: row.seenAt === null ? null : new Date(row.seenAt).toISOString(),
180
+ };
181
+ }
182
+ /** One WebSocket as the hub takes it (attach.ts AttachSocket): text frames in and out; a ping each heartbeat; closed
183
+ * with ATTACH_CLOSE.idle once nothing (no frame, ping or pong) is heard for idleMs, and with ATTACH_CLOSE.binary on a
184
+ * binary frame. A frame over MAX_LINE_BYTES is the server's maxPayload, which closes it with 1009 itself. */
185
+ export function attachSocketOf(ws, timing = { heartbeatMs: ATTACH_HEARTBEAT_MS, idleMs: ATTACH_IDLE_MS }) {
186
+ const texts = [];
187
+ const closes = [];
188
+ let ended;
189
+ let heard = Date.now();
190
+ const hear = () => void (heard = Date.now());
191
+ const close = (code, reason) => {
192
+ if (ws.readyState === ws.CLOSING || ws.readyState === ws.CLOSED)
193
+ return;
194
+ ws.close(code, closeReason(reason));
195
+ };
196
+ const beat = setInterval(() => {
197
+ if (Date.now() - heard >= timing.idleMs)
198
+ return close(ATTACH_CLOSE.idle, `nothing heard for ${Math.round(timing.idleMs / 1000)} s`);
199
+ if (ws.readyState === ws.OPEN)
200
+ ws.ping();
201
+ }, Math.min(timing.heartbeatMs, timing.idleMs));
202
+ beat.unref();
203
+ ws.on("ping", hear);
204
+ ws.on("pong", hear);
205
+ ws.on("message", (data, binary) => {
206
+ hear();
207
+ if (binary)
208
+ return close(ATTACH_CLOSE.binary, "the attach binding takes text frames only");
209
+ // The server's binaryType is nodebuffer: a message, fragmented or not, is one Buffer.
210
+ const text = data.toString("utf8");
211
+ for (const listener of texts)
212
+ listener(text);
213
+ });
214
+ // A socket that errs (a frame over maxPayload, a broken frame) is closed by ws, which then emits close.
215
+ ws.on("error", () => undefined);
216
+ ws.on("close", (code, reason) => {
217
+ clearInterval(beat);
218
+ ended = { code, reason: reason.toString("utf8") };
219
+ for (const listener of closes.splice(0))
220
+ listener(ended.code, ended.reason);
221
+ });
222
+ return {
223
+ send: (text) => void (ws.readyState === ws.OPEN ? ws.send(text) : undefined),
224
+ close,
225
+ onText: (listener) => void texts.push(listener),
226
+ onClose: (listener) => (ended ? listener(ended.code, ended.reason) : void closes.push(listener)),
227
+ };
228
+ }
229
+ /** The pairing routes and the attach socket over one store and one hub. */
230
+ export function createAttachRoutes(options) {
231
+ const { store, hub, log = () => { }, now = Date.now } = options;
232
+ const paired = store.pairedComputers;
233
+ const tries = new PairTries(now);
234
+ const sockets = new Set();
235
+ let closing = false;
236
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_LINE_BYTES, clientTracking: false, handleProtocols: () => ATTACH_SUBPROTOCOL });
237
+ /** POST /v2/computers/pairings: a new code, good once until it expires. The store keeps its hash. */
238
+ async function createPairing() {
239
+ const code = newPairingCode();
240
+ const id = `pairing-${randomBytes(9).toString("base64url")}`;
241
+ const expiresAt = now() + PAIRING_CODE_TTL_MS;
242
+ await paired.addCode(id, sha256Hex(code), expiresAt);
243
+ return { id, code, expires_at: new Date(expiresAt).toISOString() };
244
+ }
245
+ /** POST /v2/computers/pair: the code traded for the computer's id and token, once; `address` the try's source. */
246
+ async function pair(body, address) {
247
+ const allowed = tries.allow(address);
248
+ if (!allowed.ok) {
249
+ const seconds = Math.max(1, Math.ceil(allowed.retryAfterMs / 1000));
250
+ throw new ApiError("rate_limited", `too many pairing tries from this address; try again in ${seconds} s`, { retry_after_ms: allowed.retryAfterMs }, { "retry-after": String(seconds) });
251
+ }
252
+ const { code, name, hello } = pairBodyOf(body);
253
+ const refused = pairRefusal(name, hello);
254
+ if (refused)
255
+ throw invalid([{ field: "hello.protocol", reason: "invalid", message: refused }]);
256
+ // A hello that serves no kind pairs a computer no agent could pick: refused, the code kept for the updated driver.
257
+ const unserved = servesNoKind(name, hello);
258
+ if (unserved)
259
+ throw invalid([{ field: "hello.groups", reason: "invalid", message: unserved }]);
260
+ const id = newPairedId();
261
+ const token = newAttachToken();
262
+ const made = await paired.pair(sha256Hex(code), { id, name, hello: hello, labels: {}, tokenSha256: sha256Hex(token) });
263
+ if (!made)
264
+ throw new ApiError("not_found", "no such pairing code: make a new one on the console's Computers page");
265
+ log("computer_paired", { computer: id, kind: hello.kind, os: hello.os, driver: hello.version });
266
+ return { computer: id, token };
267
+ }
268
+ /** DELETE /v2/computers/{id}: its token revoked, a run's hold on it ended, its socket closed with 4401. */
269
+ async function remove(id) {
270
+ const row = await paired.get(id);
271
+ if (row === undefined || row.revokedAt !== null || !(await paired.revoke(id)))
272
+ throw new ApiError("not_found", `no paired computer ${id}: GET /v2/computers lists them under paired`);
273
+ hub.revoke(id, `${row.name} was removed from this server's console: pair it again to use it`);
274
+ log("computer_removed", { computer: id });
275
+ }
276
+ /** GET /v2/computers/attach's upgrade: the token's computer, then the protocol, then the hub's hello. A refusal is an
277
+ * HTTP answer before the upgrade (401 for a token no paired computer has, 426 for another protocol version). */
278
+ function upgrade(req, socket, head, deny) {
279
+ void (async () => {
280
+ if (closing)
281
+ return deny("503 Service Unavailable", "this server is stopping");
282
+ const bearer = /^Bearer (\S+)$/.exec(String(req.headers.authorization ?? ""))?.[1];
283
+ const row = bearer?.startsWith(ATTACH_TOKEN_PREFIX) ? await paired.byToken(sha256Hex(bearer)) : undefined;
284
+ if (row === undefined)
285
+ return deny("401 Unauthorized", "no paired computer has this token: pair the computer again from the console's Computers page", { "www-authenticate": "Bearer" });
286
+ const asked = String(req.headers["sec-websocket-protocol"] ?? "").split(",").map((one) => one.trim()).filter(Boolean);
287
+ if (!asked.includes(ATTACH_SUBPROTOCOL)) {
288
+ return deny("426 Upgrade Required", `this server speaks ${ATTACH_SUBPROTOCOL}, and the driver asked for ${asked.join(", ") || "no subprotocol"}: update whichever is older`, { "sec-websocket-protocol": ATTACH_SUBPROTOCOL });
289
+ }
290
+ if (socket.destroyed || closing)
291
+ return void socket.destroy();
292
+ wss.handleUpgrade(req, socket, head, (ws) => {
293
+ sockets.add(ws);
294
+ ws.once("close", () => sockets.delete(ws));
295
+ const attach = attachSocketOf(ws, options.timing);
296
+ options.onSocket?.(row.id, ws);
297
+ void hub.accept(pairedOf(row), attach).then(async (said) => {
298
+ if (!said.ok)
299
+ return log("computer_refused", { computer: row.id, code: said.error.code, why: said.error.message });
300
+ // The row read for the token may be older than a removal that committed, and its hub.revoke, while this socket
301
+ // was still being accepted (a Postgres read and write are separate connections): read the row again, now that the
302
+ // socket is the hub's. A removal committing after this read revokes the hub's socket after this accept, closing it.
303
+ const now = await paired.get(row.id);
304
+ if (now === undefined || now.revokedAt !== null) {
305
+ hub.revoke(row.id, `${row.name} was removed from this server's console: pair it again to use it`);
306
+ return log("computer_refused", { computer: row.id, why: "removed while it attached" });
307
+ }
308
+ await paired.seen(row.id, said.value);
309
+ log("computer_attached", { computer: row.id, driver: said.value.version });
310
+ }).catch((error) => {
311
+ log("computer_refused", { computer: row.id, why: error instanceof Error ? error.message : String(error) });
312
+ attach.close(ATTACH_CLOSE.going, "the server could not take this socket");
313
+ });
314
+ });
315
+ })().catch(() => deny("500 Internal Server Error"));
316
+ }
317
+ /** Every attach socket closed with 1001 (the server is going), and no new one taken; resolves once each has ended. A
318
+ * peer that does not answer the close within a second is cut, so the server's own close never waits on it. */
319
+ async function close() {
320
+ closing = true;
321
+ const ended = [...sockets].map((ws) => new Promise((done) => (ws.readyState === ws.CLOSED ? done() : ws.once("close", () => done()))));
322
+ for (const ws of sockets)
323
+ ws.close(ATTACH_CLOSE.going, "the server is stopping");
324
+ const cut = setTimeout(() => { for (const ws of sockets)
325
+ ws.terminate(); }, 1000);
326
+ await Promise.all(ended);
327
+ clearTimeout(cut);
328
+ }
329
+ return { createPairing, pair, remove, upgrade, close };
330
+ }
@@ -0,0 +1,48 @@
1
+ import type { ComputerClient } from "@parcha/agentrun-computer";
2
+ /** One step of a ui.act call: its kind (press, set, click, type, key, ...), and how it ran (its route, and whether a
3
+ * readback showed it took) or the kind of error that refused it. */
4
+ export type ComputerStepRecord = {
5
+ readonly do: string;
6
+ readonly route?: string;
7
+ readonly verified?: boolean;
8
+ readonly error?: string;
9
+ };
10
+ /** One computer call, as a run's record keeps it. */
11
+ export type ComputerCallRecord = {
12
+ readonly method: string;
13
+ readonly ok: boolean;
14
+ readonly ms: number;
15
+ /** The error's code, when the call failed. */
16
+ readonly code?: string;
17
+ /** ui.act: its steps, in order. */
18
+ readonly steps?: readonly ComputerStepRecord[];
19
+ /** ui.act: whether its expect held. */
20
+ readonly expect?: "met" | "unmet";
21
+ };
22
+ /** The most calls one tool call's record keeps (a code-mode script may make many); past it, `dropped` counts the rest. */
23
+ export declare const MAX_RECORDED_CALLS = 200;
24
+ /** The journal entry kind of one tool call's computer calls, kept beside the call on the run's root: `{ call, calls,
25
+ * dropped? }`, `call` the tool call's id. */
26
+ export declare const COMPUTER_CALLS = "computer.calls";
27
+ /** Each tool call's computer calls, by the call's id, from a run's COMPUTER_CALLS entries: its records, and how many it
28
+ * dropped. */
29
+ export declare function computerCallsOf(entries: readonly {
30
+ readonly kind: string;
31
+ readonly data?: unknown;
32
+ }[]): Map<string, {
33
+ readonly calls: readonly ComputerCallRecord[];
34
+ readonly dropped: number;
35
+ }>;
36
+ /** The record of a call of `method` with `params` that answered `answer` (`{ ok, value }` or `{ ok: false, error }`)
37
+ * after `ms`. Reads the params only for a ui.act's step kinds; keeps none of their values. */
38
+ export declare function callRecordOf(method: string, params: unknown, answer: unknown, ms: number): ComputerCallRecord;
39
+ /** Runs `work` with every call a recordedClient makes inside it recorded, in the order the calls were made, and hands
40
+ * the records (with how many past MAX_RECORDED_CALLS were dropped) to `keep` once it settled, thrown or not, when it
41
+ * made any. `keep` is waited for and never fails the work. A scope inside another records into the inner one only. */
42
+ export declare function recordingCalls<T>(work: () => Promise<T>, keep: (calls: readonly ComputerCallRecord[], dropped: number) => Promise<void>): Promise<T>;
43
+ /** Runs `work` outside any recordingCalls scope: its calls are recorded on no tool call (the owner's, through the
44
+ * channel, which the runner writes a record of its own for). */
45
+ export declare function unrecorded<T>(work: () => T): T;
46
+ /** `client`, with each call made inside a recordingCalls scope recorded there when it settles. A call outside any scope
47
+ * (the owner's, through the channel, or the runner's own) is recorded nowhere and costs nothing more. */
48
+ export declare function recordedClient(client: ComputerClient): ComputerClient;
@@ -0,0 +1,126 @@
1
+ // A computer protocol call as a run's record keeps it: its method, whether it answered, how long it took, its error's
2
+ // code, and for ui.act each step's kind, the route it ran by and whether a readback showed it took. Never a param's value
3
+ // and never an answer's bytes: no screenshot is in it, and no text a step set or typed (a secure field's included).
4
+ //
5
+ // The record has two homes. The owner's calls (the computer call channel, computer-channel.ts) are `computer.call`
6
+ // entries on the run's journal. The agent's calls are the `computer_calls` of the tool call that made them, on its
7
+ // tool_result row (timeline/timeline.ts): the adapter loop runs each tool call inside recordingCalls, and the run's
8
+ // computer client (recordedClient, made at the claim) records each call made inside one.
9
+ import { AsyncLocalStorage } from "node:async_hooks";
10
+ /** The most calls one tool call's record keeps (a code-mode script may make many); past it, `dropped` counts the rest. */
11
+ export const MAX_RECORDED_CALLS = 200;
12
+ /** The journal entry kind of one tool call's computer calls, kept beside the call on the run's root: `{ call, calls,
13
+ * dropped? }`, `call` the tool call's id. */
14
+ export const COMPUTER_CALLS = "computer.calls";
15
+ const obj = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : undefined);
16
+ /** A record as an entry kept it, or undefined when it is not one (an entry another build wrote). */
17
+ function recordOf(value) {
18
+ const one = obj(value);
19
+ if (!one || typeof one.method !== "string" || typeof one.ok !== "boolean" || typeof one.ms !== "number")
20
+ return undefined;
21
+ const steps = Array.isArray(one.steps) ? one.steps.flatMap((step) => {
22
+ const s = obj(step);
23
+ if (!s || typeof s.do !== "string")
24
+ return [];
25
+ return [{ do: s.do, ...(typeof s.route === "string" ? { route: s.route } : {}), ...(typeof s.verified === "boolean" ? { verified: s.verified } : {}), ...(typeof s.error === "string" ? { error: s.error } : {}) }];
26
+ }) : undefined;
27
+ return {
28
+ method: one.method, ok: one.ok, ms: one.ms,
29
+ ...(typeof one.code === "string" ? { code: one.code } : {}),
30
+ ...(steps ? { steps } : {}),
31
+ ...(one.expect === "met" || one.expect === "unmet" ? { expect: one.expect } : {}),
32
+ };
33
+ }
34
+ /** Each tool call's computer calls, by the call's id, from a run's COMPUTER_CALLS entries: its records, and how many it
35
+ * dropped. */
36
+ export function computerCallsOf(entries) {
37
+ const out = new Map();
38
+ for (const entry of entries) {
39
+ if (entry.kind !== COMPUTER_CALLS)
40
+ continue;
41
+ const data = obj(entry.data);
42
+ if (typeof data?.call !== "string" || !Array.isArray(data.calls))
43
+ continue;
44
+ const calls = data.calls.flatMap((call) => recordOf(call) ?? []);
45
+ out.set(data.call, { calls, dropped: typeof data.dropped === "number" ? data.dropped : 0 });
46
+ }
47
+ return out;
48
+ }
49
+ /** The step kinds a ui.act step may name (the protocol's UiStep keys). */
50
+ const STEP_KINDS = ["press", "set", "perform", "click", "type", "key", "nav", "scroll", "drag"];
51
+ /** A ui.act step's record: its kind from its params, how it ran from its result. */
52
+ function stepRecord(step, result) {
53
+ const given = obj(step) ?? {};
54
+ const kind = STEP_KINDS.find((name) => name in given) ?? "step";
55
+ const ran = obj(result);
56
+ const error = obj(ran?.error);
57
+ if (error)
58
+ return { do: kind, error: typeof error.kind === "string" ? error.kind : "error" };
59
+ return { do: kind, ...(typeof ran?.route === "string" ? { route: ran.route } : {}), ...(typeof ran?.verified === "boolean" ? { verified: ran.verified } : {}) };
60
+ }
61
+ /** The record of a call of `method` with `params` that answered `answer` (`{ ok, value }` or `{ ok: false, error }`)
62
+ * after `ms`. Reads the params only for a ui.act's step kinds; keeps none of their values. */
63
+ export function callRecordOf(method, params, answer, ms) {
64
+ const said = obj(answer);
65
+ const ok = said?.ok === true;
66
+ const base = { method, ok, ms: Math.max(0, Math.round(ms)) };
67
+ if (!ok) {
68
+ const code = obj(said?.error)?.code;
69
+ return { ...base, code: typeof code === "string" ? code : "error" };
70
+ }
71
+ if (method !== "ui.act")
72
+ return base;
73
+ const value = obj(said?.value);
74
+ const results = Array.isArray(value?.steps) ? value.steps : [];
75
+ const asked = Array.isArray(obj(params)?.steps) ? obj(params).steps : [];
76
+ return {
77
+ ...base,
78
+ steps: results.map((result, index) => stepRecord(asked[index], result)),
79
+ ...(value?.expect === "met" || value?.expect === "unmet" ? { expect: value.expect } : {}),
80
+ };
81
+ }
82
+ const scope = new AsyncLocalStorage();
83
+ /** Runs `work` with every call a recordedClient makes inside it recorded, in the order the calls were made, and hands
84
+ * the records (with how many past MAX_RECORDED_CALLS were dropped) to `keep` once it settled, thrown or not, when it
85
+ * made any. `keep` is waited for and never fails the work. A scope inside another records into the inner one only. */
86
+ export async function recordingCalls(work, keep) {
87
+ const mine = { calls: [], dropped: 0 };
88
+ try {
89
+ return await scope.run(mine, work);
90
+ }
91
+ finally {
92
+ if (mine.calls.length > 0)
93
+ await keep(mine.calls, mine.dropped).catch(() => undefined);
94
+ }
95
+ }
96
+ /** Runs `work` outside any recordingCalls scope: its calls are recorded on no tool call (the owner's, through the
97
+ * channel, which the runner writes a record of its own for). */
98
+ export function unrecorded(work) {
99
+ return scope.exit(work);
100
+ }
101
+ /** `client`, with each call made inside a recordingCalls scope recorded there when it settles. A call outside any scope
102
+ * (the owner's, through the channel, or the runner's own) is recorded nowhere and costs nothing more. */
103
+ export function recordedClient(client) {
104
+ return {
105
+ call: (async (method, params, options) => {
106
+ const into = scope.getStore();
107
+ if (!into)
108
+ return client.call(method, params, options);
109
+ // Its place is kept when it starts, so calls made together read in the order they were made, and the bound keeps
110
+ // the first ones made. A call still going when its tool call ended reads unfinished.
111
+ const slot = into.calls.length < MAX_RECORDED_CALLS ? into.calls.push({ method, ok: false, ms: 0, code: "unfinished" }) - 1 : undefined;
112
+ if (slot === undefined)
113
+ into.dropped += 1;
114
+ const started = performance.now();
115
+ const answer = await client.call(method, params, options).catch((error) => {
116
+ if (slot !== undefined)
117
+ into.calls[slot] = { method, ok: false, ms: Math.round(performance.now() - started), code: "gone" };
118
+ throw error;
119
+ });
120
+ if (slot !== undefined)
121
+ into.calls[slot] = callRecordOf(method, params, answer, performance.now() - started);
122
+ return answer;
123
+ }),
124
+ close: () => client.close(),
125
+ };
126
+ }
@@ -0,0 +1,57 @@
1
+ import type { InputIssue } from "./errors.js";
2
+ import { type Store } from "./store/index.js";
3
+ /** The command row kind the server writes. */
4
+ export declare const COMPUTER_CALL = "computer_call";
5
+ /** The journal entry kind the runner commits for each call. */
6
+ export declare const CALL_KIND = "computer.call";
7
+ /** The longest one call runs on the computer, a wait for a person's hand-back included, before the runner ends it. */
8
+ export declare const CALL_MS = 120000;
9
+ /** How long the server waits for a runner to take a call's row, on top of the call's own time. */
10
+ export declare const TAKE_MS = 60000;
11
+ /** How often the server reads a call's row when no wake comes (a runner in another process). */
12
+ export declare const CHANNEL_POLL_MS = 250;
13
+ /** The computer protocol's methods (spec/computer/protocol.json; a test keeps the two equal). A call names one of them. */
14
+ export declare const PROTOCOL_METHODS: readonly string[];
15
+ /** A call's answer, the computer's own: the method's result, or its error as the protocol gives it. */
16
+ export type ComputerAnswer = {
17
+ readonly ok: true;
18
+ readonly value: unknown;
19
+ } | {
20
+ readonly ok: false;
21
+ readonly error: {
22
+ readonly code: string;
23
+ readonly message: string;
24
+ readonly data?: unknown;
25
+ };
26
+ };
27
+ /** One call: a protocol method and its params. */
28
+ export type ComputerCall = {
29
+ readonly method: string;
30
+ readonly params: Record<string, unknown>;
31
+ };
32
+ /** A call body's issues: `method` one of PROTOCOL_METHODS, `params` an object when given, no other field. */
33
+ export declare function callIssues(body: Record<string, unknown>): InputIssue[];
34
+ /** The slice of the store the channel reads and writes. */
35
+ export type ChannelStore = Pick<Store, "command" | "commands" | "runs" | "answerOf" | "watchCommands">;
36
+ /** A test's own waits: how often the server reads the row with no wake, and how long it waits for a runner to take it. */
37
+ export type ChannelOptions = {
38
+ readonly pollMs?: number;
39
+ readonly takeMs?: number;
40
+ };
41
+ /**
42
+ * Writes row `command` for run `runId` and waits for its runner to deal with it: taken (with the row's id, so its answer
43
+ * can be read), or refused in the runner's words (409 computer_not_live). 409 too when the run ended before the write;
44
+ * 503 when no runner dealt with it within `waitMs`. The channel's write, and a held computer's start and release
45
+ * (computer-held-routes.ts).
46
+ */
47
+ export declare function sendRow(store: ChannelStore, runId: string, command: {
48
+ kind: string;
49
+ body: unknown;
50
+ }, waitMs: number, pollMs?: number): Promise<number>;
51
+ /**
52
+ * Sends run `runId`'s computer one call and answers what the computer answered. 404 for no such run; 409
53
+ * computer_not_live when the run is not running (queued, parked, over) or its runner refused the call (no computer that
54
+ * takes calls, its computer let go), in the runner's words; 503 when no runner took the row in time. A call that fails
55
+ * on the computer is still an answer: `{ ok: false, error }`.
56
+ */
57
+ export declare function callComputer(store: ChannelStore, runId: string, call: ComputerCall, options?: ChannelOptions): Promise<ComputerAnswer>;