@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
package/dist/cap.js CHANGED
@@ -44,10 +44,7 @@
44
44
  // on a refusal for room and waits for a raise without its process, a workflow's refused step waits where it stands
45
45
  // (RunSpend.wait, budget.ts): a model node's request before it is sent, a call node's call and a decision before they are
46
46
  // admitted again. A refusal inside a call node's effect is told to the call (capRefusals), never only to the model.
47
- import { readRunDbSync } from "./run-db.js";
48
- import { durableDecisions } from "./workflow/readers.js";
49
47
  import { AsyncLocalStorage } from "node:async_hooks";
50
- import { existsSync } from "node:fs";
51
48
  import { imageInputOf, providerInputOverhead } from "@parcha/agentrun-kernel/host";
52
49
  import { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "@parcha/agentrun-kernel";
53
50
  import { REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "./timeline/index.js";
@@ -514,94 +511,6 @@ export function spentFrom(rows) {
514
511
  return null;
515
512
  return entries.reduce((sum, entry) => sum + costOf(entry), 0);
516
513
  }
517
- /** A workflow decision's charge as the cap counted it (decision-cap.ts): `call` names the request, `usd` what it charged,
518
- * or its hold when it said none. The run's shown cost reads its decisions from their receipts; this is the cap's own
519
- * reading, kept so a later process counts each decision as this one did. costOf counts none, so nothing counts twice. */
520
- export const DECISION_COST = "agentrun.decision_cost";
521
- /** A decision request's hold, kept before it is sent (decision-cap.ts): with no DECISION_COST after it, its process died
522
- * while it was out, and it counts at this figure. */
523
- export const DECISION_HOLD = "agentrun.decision_hold";
524
- /** What a workflow run's decisions cost, in its store: what the next process adds to spentFrom's reading. Per decision
525
- * (its id):
526
- * - booked (DECISION_COST entries, at its charge, its hold, or $0 for nothing charged): the larger of what was booked,
527
- * with any hold no booking ended, and what its receipts say it cost (the costs the timeline's decision rows sum);
528
- * - else, with a receipt that names its charge: that charge (its booking lost after the receipt);
529
- * - else, with a hold (DECISION_HOLD, kept once the driver admitted the request, right before its send): that hold, the
530
- * figure the live process held, since the request may have been out when its process died; never $0;
531
- * - else nothing: no hold is kept before the admission, so a request never sent is never counted.
532
- * A booking with no decision id is counted as it is. */
533
- export function decisionSpentIn(storeFile) {
534
- const booked = new Map();
535
- /** The decisions with any booking, a $0 one included. */
536
- const ended = new Set();
537
- /** Each decision's holds kept and not yet followed by a booking, in order. */
538
- const open = new Map();
539
- let loose = 0;
540
- for (const entry of entriesIn(storeFile)) {
541
- if (entry.kind !== DECISION_COST && entry.kind !== DECISION_HOLD)
542
- continue;
543
- const data = entry.data;
544
- const usd = figureOf(data?.usd);
545
- const id = typeof data?.decision === "string" ? data.decision : undefined;
546
- if (entry.kind === DECISION_HOLD) {
547
- if (id !== undefined && usd !== undefined)
548
- open.set(id, [...(open.get(id) ?? []), usd]);
549
- continue;
550
- }
551
- // A booking ends its decision's oldest hold still open, whatever it charged ($0 for nothing sent).
552
- if (id !== undefined) {
553
- ended.add(id);
554
- open.get(id)?.shift();
555
- }
556
- if (usd === undefined || !(usd > 0))
557
- continue;
558
- if (id !== undefined)
559
- booked.set(id, (booked.get(id) ?? 0) + usd);
560
- else
561
- loose += usd;
562
- }
563
- const receipted = new Map();
564
- let receipts = [];
565
- // Receipts that cannot be read leave the bookings alone to say it.
566
- if (existsSync(storeFile))
567
- try {
568
- receipts = durableDecisions(storeFile, { unlocked: true });
569
- }
570
- catch {
571
- receipts = [];
572
- }
573
- for (const receipt of receipts) {
574
- const usd = figureOf(receipt.cost_usd);
575
- // A stored receipt row names its decision `decision_id` (workflow/decision-recovery.ts rowOf).
576
- const id = typeof receipt.decision_id === "string" ? receipt.decision_id : typeof receipt.id === "string" ? receipt.id : undefined;
577
- if (id !== undefined && usd !== undefined && usd > 0)
578
- receipted.set(id, (receipted.get(id) ?? 0) + usd);
579
- }
580
- let sum = loose;
581
- for (const id of new Set([...ended, ...booked.keys(), ...receipted.keys(), ...open.keys()])) {
582
- const held = (open.get(id) ?? []).reduce((total, usd) => total + (usd > 0 ? usd : 0), 0);
583
- if (ended.has(id))
584
- sum += Math.max((booked.get(id) ?? 0) + held, receipted.get(id) ?? 0);
585
- else if (receipted.has(id))
586
- sum += receipted.get(id);
587
- else
588
- sum += held;
589
- }
590
- return sum;
591
- }
592
- /** The entries of the run's store, in order (none when it has no store yet). */
593
- function entriesIn(storeFile) {
594
- if (!existsSync(storeFile))
595
- return [];
596
- // Fresh, read-only and lock-free (run-db.ts), as the cap's readings did.
597
- const rows = [];
598
- readRunDbSync(storeFile, false, (db) => {
599
- rows.length = 0;
600
- for (const row of db.prepare("SELECT record FROM entries ORDER BY rowid").iterate())
601
- rows.push(JSON.parse(String(row.record)));
602
- });
603
- return rows;
604
- }
605
514
  /** 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
606
515
  * browserSpend's `paid`): the same record a browser TOOL_COST is, for what the browser's process holds and the seconds
607
516
  * 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
package/dist/catalog.d.ts CHANGED
@@ -5,16 +5,5 @@
5
5
  export declare const WIRE_NAME: RegExp;
6
6
  /** A catalog name's wire name: itself when it already is one within the budget, else `:` and `/` to `__`, `.` to `_`,
7
7
  * any other character to `_`, and a `-<8 hex of the catalog name>` suffix (prefix trimmed to fit) when the result is
8
- * too long. The suffix makes a long name unique; a collision between two names is refused at the save (collisions,
9
- * reverseOf), never suffixed away. The reverse is a lookup, never a parse. */
8
+ * too long. The suffix makes a long name unique. */
10
9
  export declare function wireName(catalog: string): string;
11
- /** The reverse of {@link wireName} over `names`: a map from each name's wire name back to the catalog name. A collision
12
- * (two catalog names with one wire name) throws here, so a catalog that would shadow a name never loads; the save path
13
- * reports the same collision as a 422 before it reaches this. */
14
- export declare function reverseOf(names: Iterable<string>): ReadonlyMap<string, string>;
15
- /** The catalog names in `names` whose wire names collide, each paired with the name it clashes with: a definition that
16
- * holds a pair is refused (a 422 on the second one), so {@link reverseOf} never throws for a loaded catalog. */
17
- export declare function collisions(names: readonly string[]): {
18
- name: string;
19
- clashesWith: string;
20
- }[];
package/dist/catalog.js CHANGED
@@ -1,8 +1,8 @@
1
1
  // The tool catalog's names, and the one mapping between a catalog name and the wire name a harness calls. A catalog name
2
2
  // is what a revision writes (`read`, later `monid.discover`, `mcp:<server>/<tool>`); the wire name is what a CLI adapter
3
3
  // registers and the model API sees, and both adapters refuse anything outside /^[A-Za-z0-9_-]{1,64}$/. The map is one
4
- // deterministic, reversible function here, never in an adapter, so every harness gets the same wire name; the journal
5
- // records the wire name (recovery matches a call by it), and a reader maps it back to the catalog name on the way out.
4
+ // deterministic function here, never in an adapter, so every harness gets the same wire name; the journal records the
5
+ // wire name (recovery matches a call by it), and a reader maps it back to the catalog name by a lookup, never a parse.
6
6
  import { createHash } from "node:crypto";
7
7
  /** A wire name: at most 52 characters, not the adapter's 64. One CLI gives the model the name with a 12-character
8
8
  * `mcp__hands__` prefix, and the model API's 64-character limit is on the name the model sees, so 52 is the budget that
@@ -11,8 +11,7 @@ import { createHash } from "node:crypto";
11
11
  export const WIRE_NAME = /^[A-Za-z0-9_-]{1,52}$/;
12
12
  /** A catalog name's wire name: itself when it already is one within the budget, else `:` and `/` to `__`, `.` to `_`,
13
13
  * any other character to `_`, and a `-<8 hex of the catalog name>` suffix (prefix trimmed to fit) when the result is
14
- * too long. The suffix makes a long name unique; a collision between two names is refused at the save (collisions,
15
- * reverseOf), never suffixed away. The reverse is a lookup, never a parse. */
14
+ * too long. The suffix makes a long name unique. */
16
15
  export function wireName(catalog) {
17
16
  if (WIRE_NAME.test(catalog))
18
17
  return catalog;
@@ -22,32 +21,3 @@ export function wireName(catalog) {
22
21
  const tag = `-${createHash("sha256").update(catalog).digest("hex").slice(0, 8)}`;
23
22
  return base.slice(0, 52 - tag.length) + tag;
24
23
  }
25
- /** The reverse of {@link wireName} over `names`: a map from each name's wire name back to the catalog name. A collision
26
- * (two catalog names with one wire name) throws here, so a catalog that would shadow a name never loads; the save path
27
- * reports the same collision as a 422 before it reaches this. */
28
- export function reverseOf(names) {
29
- const reverse = new Map();
30
- for (const name of names) {
31
- const wire = wireName(name);
32
- const had = reverse.get(wire);
33
- if (had !== undefined && had !== name)
34
- throw new Error(`the tools ${had} and ${name} both map to the wire name ${wire}`);
35
- reverse.set(wire, name);
36
- }
37
- return reverse;
38
- }
39
- /** The catalog names in `names` whose wire names collide, each paired with the name it clashes with: a definition that
40
- * holds a pair is refused (a 422 on the second one), so {@link reverseOf} never throws for a loaded catalog. */
41
- export function collisions(names) {
42
- const seen = new Map();
43
- const clashes = [];
44
- for (const name of names) {
45
- const wire = wireName(name);
46
- const had = seen.get(wire);
47
- if (had !== undefined && had !== name)
48
- clashes.push({ name, clashesWith: had });
49
- else
50
- seen.set(wire, name);
51
- }
52
- return clashes;
53
- }
package/dist/cli.js CHANGED
@@ -65,7 +65,9 @@ const USAGE = `usage: agentrun-serve [--data DIR] [--listen ADDR] [--port N] [--
65
65
  more \`agentrun-serve runner --data DIR\` processes on the same data directory to claim and run runs;
66
66
  each holds at most --loops N runs (default AGENTRUN_MAX_RUNS, else as many pi runs as its host's
67
67
  memory holds; the rest wait queued) and on SIGTERM lets each busy run finish its turn for up to
68
- --drain-timeout D (default AGENTRUN_DRAIN_TIMEOUT, else 6s), then hands the rest back to resume
68
+ --drain-timeout D (default AGENTRUN_DRAIN_TIMEOUT, else 6s), then hands the rest back to resume.
69
+ A paired computer (Settings → Computers → Pair a computer) dials the server's process, so only the
70
+ runner beside it can use one: separate runners refuse a run whose agent names one
69
71
 
70
72
  Without --faux, a revision's model ("provider/model-id", or AGENT_MODEL when it names none; a workflow node's tier maps
71
73
  to AGENT_MODEL_FAST or AGENT_MODEL_STRONG, each falling back to AGENT_MODEL) is served by pi-ai's providers with their
@@ -87,6 +89,8 @@ per address (an IPv6 one by its /64) and wrong passwords per server; past the li
87
89
  Behind a proxy, set AGENTRUN_TRUSTED_PROXIES to its addresses or ranges (comma-separated; or loopback, linklocal,
88
90
  uniquelocal) so each visitor counts by the address its X-Forwarded-For names; unset, that header is never read. Forgot the password: \`agentrun-serve reset-password --data DIR\` where the
89
91
  data directory is (inside the container) clears it and signs every browser out, and the next visit sets a new one.
92
+ An MCP server on loopback (a 127.0.0.1 or localhost address) is refused unless AGENTRUN_MCP_ALLOW_LOOPBACK=1 is set at the
93
+ start: set it only on a machine you alone use, since loopback is this machine's other services too.
90
94
 
91
95
  \`agentrun-serve import\` reads the Claude Code, Codex and pi sessions in your own home (~/.claude/projects,
92
96
  ~/.codex/sessions, ~/.pi/agent/sessions) into the data directory, once: each project directory an agent, with its
@@ -354,6 +358,8 @@ try {
354
358
  ...(accounts ? { accounts, openSetup: !publicUrl, countSessions: true } : {}), ...(apiOnly ? { apiOnly } : {}),
355
359
  // The proxies whose X-Forwarded-For the sign-in limit reads (comma-separated); none unless set.
356
360
  ...(trustedProxies.length ? { trustedProxies } : {}),
361
+ // A local install only as its operator says, never inferred: an MCP server on loopback is refused without it.
362
+ ...(process.env.AGENTRUN_MCP_ALLOW_LOOPBACK === "1" ? { mcpLoopback: true } : {}),
357
363
  });
358
364
  }
359
365
  catch (error) {
@@ -375,8 +381,11 @@ if (!values["no-runner"] && askedAt === undefined) {
375
381
  // model up in pi-ai's own catalog and every run fails on its first request. A test switch this process inherited from
376
382
  // its shell is taken out first, as the server's own environment drops it (runner/main.ts besideRunEnv).
377
383
  const { besideRunEnv } = await import("./runner/main.js");
378
- // With the computer janitor: what a crashed runner of this server left is ended (never under --faux).
379
- runnerProc = await runnerBeside(data, { loops, drainMs, env: besideRunEnv(process.env, fauxEnvOf(serveOptions)), janitor: true });
384
+ // With the computer janitor: what a crashed runner of this server left is ended (never under --faux). With the
385
+ // server's AttachHub: a paired computer's socket is in this process, so only this runner takes one (--no-runner's
386
+ // separate runners refuse it in words). Its runs reach an MCP server on loopback only when this server is a local
387
+ // install (Serve.localInstall).
388
+ runnerProc = await runnerBeside(data, { loops, drainMs, env: besideRunEnv(process.env, fauxEnvOf(serveOptions)), janitor: true, hub: serve.attachHub, mcpLoopback: serve.localInstall });
380
389
  }
381
390
  catch (error) {
382
391
  console.error(`agentrun-serve: the runner could not start: ${error.message}`);
@@ -386,7 +395,7 @@ if (!values["no-runner"] && askedAt === undefined) {
386
395
  }
387
396
  // A token from the environment is the operator's already, and the stored one is printed by the start that made it only.
388
397
  const source = given ? "env" : serve.tokenMade ? "made" : "file";
389
- for (const line of banner({ url: serve.url, baseUrl: serve.baseUrl, data, token: serve.token, source, accounts, ...(apiOnly ? { apiOnly } : {}), boxes: serve.boxesLine, ...(values.listen ? { listen: values.listen } : {}), ...(publicUrl ? { publicUrl } : {}) }))
398
+ for (const line of banner({ url: serve.url, baseUrl: serve.baseUrl, data, token: serve.token, source, accounts, ...(apiOnly ? { apiOnly } : {}), ...(serve.launchCode ? { launchCode: serve.launchCode } : {}), boxes: serve.boxesLine, ...(values.listen ? { listen: values.listen } : {}), ...(publicUrl ? { publicUrl } : {}) }))
390
399
  console.log(line);
391
400
  // Open setup (no public address, a loopback listener): the link that sets the password. Any other start printed the
392
401
  // setup link with its code as the code was made (owner.ts).
@@ -0,0 +1,36 @@
1
+ /** Another Composio than the real one, and its fetch: a test's fake (the same seam as `archilControl`). */
2
+ export type ComposioControl = {
3
+ readonly baseUrl?: string;
4
+ readonly fetch?: typeof fetch;
5
+ };
6
+ export type ComposioTool = {
7
+ slug: string;
8
+ name: string;
9
+ description: string;
10
+ };
11
+ /** POST /settings/mcp-servers/composio/tools: a toolkit's actions, for the console's picker, and whether it needs no sign-in. */
12
+ export declare function composioTools(body: unknown, control: ComposioControl, signal?: AbortSignal): Promise<{
13
+ toolkit: string;
14
+ no_auth: boolean;
15
+ tools: ComposioTool[];
16
+ }>;
17
+ /** The address Composio's generate answers, made one this server's client can use: the helper actions that connect an
18
+ * account left off, and the path ended in /mcp (Composio redirects the bare one, which the client refuses on purpose). */
19
+ export declare function composioAddress(generated: string): string;
20
+ /** PUT /settings/mcp-servers/{name}/composio: Composio makes the managed MCP server, `save` keeps it as a saved MCP server
21
+ * (`{url, auth}`: the key a sealed header), and a toolkit that needs the person's account says where to connect it. */
22
+ export declare function composioSave<T extends {
23
+ tools?: readonly {
24
+ name: string;
25
+ }[];
26
+ }>(body: unknown, control: ComposioControl, save: (mcp: {
27
+ url: string;
28
+ auth: {
29
+ type: "headers";
30
+ headers: Record<string, string>;
31
+ };
32
+ }) => Promise<T>, name: string, signal?: AbortSignal, savedUrl?: () => Promise<string | undefined>): Promise<{
33
+ server: T;
34
+ connect_url?: string;
35
+ not_served?: string[];
36
+ }>;
@@ -0,0 +1,179 @@
1
+ // The Composio preset in Settings → MCP servers. Composio is an MCP server like any other: the owner gives an API key, a
2
+ // toolkit and the actions to grant, this file has Composio make a managed MCP server for them (plain fetch, its REST API),
3
+ // and the result is saved through the one MCP save (mcp-servers-store.ts) with the key as a sealed x-api-key header. No
4
+ // adapter, no auth type, no key row of its own: after the save a Composio server is a saved MCP server, gated and
5
+ // metered like every other. The four meta tools Composio adds (serve/src/mcp-meta.ts) stay refused; the helper actions
6
+ // that connect an account are left off the server's address. The key goes only to Composio and into the sealed header: it
7
+ // is never logged, echoed or put in an error.
8
+ import { randomBytes } from "node:crypto";
9
+ import { ApiError, invalid } from "./errors.js";
10
+ import { isObject } from "./validate.js";
11
+ const BASE = "https://backend.composio.dev";
12
+ /** The one Composio user a server's actions run as, unless the owner names another. */
13
+ const USER = "agentrun";
14
+ const TOOLKIT = /^[a-z0-9][a-z0-9_-]{0,63}$/;
15
+ const USER_ID = /^[A-Za-z0-9._@-]{1,128}$/;
16
+ const PAGE = 200;
17
+ const MAX_PAGES = 10;
18
+ const MAX_TOOLS = 500;
19
+ const WAIT_MS = 20_000;
20
+ const text = (value) => (typeof value === "string" ? value : "");
21
+ const issue = (field, reason, message) => ({ field, reason, message });
22
+ /** A Composio call as `key`: its JSON answer, or an error in words that name `step` and never the key. */
23
+ function asking(control, key, signal) {
24
+ const base = (control.baseUrl ?? BASE).replace(/\/+$/, "");
25
+ const send = control.fetch ?? fetch;
26
+ const scrub = (said) => said.split(key).join("[the key]").slice(0, 300);
27
+ return async (step, method, path, body, missing) => {
28
+ let res;
29
+ let raw;
30
+ try {
31
+ // No redirect is followed: it would carry the key to wherever it points.
32
+ res = await send(`${base}${path}`, {
33
+ method, redirect: "error", signal: AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(WAIT_MS)]),
34
+ headers: { "x-api-key": key, accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }) },
35
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
36
+ });
37
+ raw = await res.text();
38
+ }
39
+ catch {
40
+ throw new ApiError("upstream_failed", `Composio did not answer while ${step}: nothing was saved.`);
41
+ }
42
+ let json;
43
+ try {
44
+ json = JSON.parse(raw);
45
+ }
46
+ catch { /* not JSON: said below */ }
47
+ if (res.ok) {
48
+ if (isObject(json))
49
+ return json;
50
+ throw new ApiError("upstream_failed", `Composio's answer while ${step} was not JSON: nothing was saved.`);
51
+ }
52
+ const said = isObject(json) && isObject(json.error) ? text(json.error.message) : isObject(json) ? text(json.message) : "";
53
+ if (res.status === 401 || res.status === 403)
54
+ throw invalid([issue("api_key", "refused", `Composio refused the API key while ${step}: check it in Composio's dashboard.`)]);
55
+ if (res.status === 404 && missing)
56
+ throw invalid([issue("toolkit", "not_found", missing)]);
57
+ if (res.status >= 400 && res.status < 500)
58
+ throw invalid([issue("body", "refused", `Composio refused the request while ${step} (${res.status})${said ? `: ${scrub(said)}` : ""}.`)]);
59
+ throw new ApiError("upstream_failed", `Composio failed while ${step} (${res.status}): nothing was saved.`);
60
+ };
61
+ }
62
+ /** The key and toolkit of a body, checked. */
63
+ function head(body) {
64
+ if (!isObject(body))
65
+ throw invalid([issue("body", "invalid", "The body is {api_key, toolkit}.")]);
66
+ const key = typeof body.api_key === "string" ? body.api_key.trim() : "";
67
+ const toolkit = typeof body.toolkit === "string" ? body.toolkit.trim().toLowerCase() : "";
68
+ const issues = [];
69
+ if (!key || key.length > 8192)
70
+ issues.push(issue("api_key", "missing", "Send your Composio API key."));
71
+ if (!TOOLKIT.test(toolkit))
72
+ issues.push(issue("toolkit", "invalid", "Send the toolkit's slug as Composio names it (github, slack, gmail...)."));
73
+ if (issues.length)
74
+ throw invalid(issues);
75
+ return { key, toolkit, rest: body };
76
+ }
77
+ /** Whether a toolkit needs no sign-in. Composio's answer for one toolkit has no `no_auth` field (only its toolkit list
78
+ * does): it says so as every auth mode in `auth_config_details` being NO_AUTH. */
79
+ function needsNoAuth(kit) {
80
+ if (kit.no_auth === true)
81
+ return true;
82
+ const modes = Array.isArray(kit.auth_config_details) ? kit.auth_config_details.map((d) => (isObject(d) ? text(d.mode) : "")) : [];
83
+ return modes.length > 0 && modes.every((mode) => mode === "NO_AUTH");
84
+ }
85
+ const notFound = (toolkit) => `Composio has no toolkit ${toolkit}: use its slug (github, slack, gmail...).`;
86
+ /** POST /settings/mcp-servers/composio/tools: a toolkit's actions, for the console's picker, and whether it needs no sign-in. */
87
+ export async function composioTools(body, control, signal) {
88
+ const { key, toolkit } = head(body);
89
+ const ask = asking(control, key, signal);
90
+ const kit = await ask("reading the toolkit", "GET", `/api/v3/toolkits/${encodeURIComponent(toolkit)}`, undefined, notFound(toolkit));
91
+ const tools = [];
92
+ let cursor;
93
+ for (let page = 0; page < MAX_PAGES; page++) {
94
+ const listed = await ask("listing the toolkit's actions", "GET", `/api/v3/tools?toolkit_slug=${encodeURIComponent(toolkit)}&limit=${PAGE}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`, undefined, notFound(toolkit));
95
+ for (const item of Array.isArray(listed.items) ? listed.items : [])
96
+ if (isObject(item) && text(item.slug))
97
+ tools.push({ slug: text(item.slug), name: text(item.name) || text(item.slug), description: text(item.description) });
98
+ cursor = text(listed.next_cursor) || undefined;
99
+ if (!cursor)
100
+ break;
101
+ }
102
+ return { toolkit, no_auth: needsNoAuth(kit), tools };
103
+ }
104
+ /** The address Composio's generate answers, made one this server's client can use: the helper actions that connect an
105
+ * account left off, and the path ended in /mcp (Composio redirects the bare one, which the client refuses on purpose). */
106
+ export function composioAddress(generated) {
107
+ const url = new URL(generated);
108
+ url.searchParams.delete("include_composio_helper_actions");
109
+ const path = url.pathname.replace(/\/+$/, "");
110
+ url.pathname = path.endsWith("/mcp") ? path : `${path}/mcp`;
111
+ return url.href;
112
+ }
113
+ /** PUT /settings/mcp-servers/{name}/composio: Composio makes the managed MCP server, `save` keeps it as a saved MCP server
114
+ * (`{url, auth}`: the key a sealed header), and a toolkit that needs the person's account says where to connect it. */
115
+ export async function composioSave(body, control, save, name, signal, savedUrl) {
116
+ const { key, toolkit, rest } = head(body);
117
+ const tools = Array.isArray(rest.tools) ? rest.tools : [];
118
+ const user = rest.user_id === undefined ? USER : typeof rest.user_id === "string" ? rest.user_id : "";
119
+ const issues = [];
120
+ if (!tools.length || tools.length > MAX_TOOLS || !tools.every((t) => typeof t === "string" && t))
121
+ issues.push(issue("tools", "invalid", `Send the slugs of the actions to grant: 1 to ${MAX_TOOLS} of them.`));
122
+ if (!USER_ID.test(user))
123
+ issues.push(issue("user_id", "invalid", "A user_id is letters, digits and . _ @ - (at most 128)."));
124
+ if (issues.length)
125
+ throw invalid(issues);
126
+ const ask = asking(control, key, signal);
127
+ const kit = await ask("reading the toolkit", "GET", `/api/v3/toolkits/${encodeURIComponent(toolkit)}`, undefined, notFound(toolkit));
128
+ const noAuth = needsNoAuth(kit);
129
+ let authConfig;
130
+ if (!noAuth) {
131
+ const configs = await ask("finding the toolkit's auth config", "GET", `/api/v3/auth_configs?toolkit_slug=${encodeURIComponent(toolkit)}`);
132
+ const managed = (Array.isArray(configs.items) ? configs.items : []).find((c) => isObject(c) && c.is_composio_managed === true && c.status !== "DISABLED" && text(c.id));
133
+ authConfig = managed ? text(managed.id) : undefined;
134
+ if (!authConfig) {
135
+ const made = await ask("making the toolkit's auth config", "POST", "/api/v3/auth_configs", { toolkit: { slug: toolkit }, auth_config: { type: "use_composio_managed_auth" } });
136
+ authConfig = isObject(made.auth_config) ? text(made.auth_config.id) : "";
137
+ if (!authConfig)
138
+ throw new ApiError("upstream_failed", "Composio made no auth config: nothing was saved.");
139
+ }
140
+ }
141
+ const made = await ask("making the MCP server", "POST", "/api/v3.1/mcp/servers/custom", {
142
+ name: `ar-${name.slice(0, 18)}-${randomBytes(3).toString("hex")}`, toolkits: [toolkit], ...(authConfig ? { auth_config_ids: [authConfig] } : {}), allowed_tools: tools, managed_auth_via_composio: true,
143
+ });
144
+ const id = text(made.id);
145
+ if (!id)
146
+ throw new ApiError("upstream_failed", "Composio made no MCP server: nothing was saved.");
147
+ // From here a failure deletes the server Composio just made, so a failed save leaves nothing in the person's account
148
+ // (best effort: the save's own error is the one answered). Not when the local entry was written before the save failed
149
+ // (its flush, say): `savedUrl` reads the name's saved address, and one that is this server's keeps it.
150
+ let url;
151
+ try {
152
+ const generated = await ask("making the MCP server's address", "POST", "/api/v3.1/mcp/servers/generate", { mcp_server_id: id, user_ids: [user], managed_auth_by_composio: true });
153
+ const address = Array.isArray(generated.user_ids_url) ? text(generated.user_ids_url[0]) : "";
154
+ if (!address)
155
+ throw new ApiError("upstream_failed", "Composio gave no address for the MCP server: nothing was saved.");
156
+ let connect;
157
+ if (authConfig) {
158
+ // Only an account under this server's auth config serves it: one ACTIVE under another config (a custom one) doesn't.
159
+ const accounts = await ask("checking the connected account", "GET", `/api/v3/connected_accounts?user_ids=${encodeURIComponent(user)}&toolkit_slugs=${encodeURIComponent(toolkit)}&auth_config_ids=${encodeURIComponent(authConfig)}`);
160
+ if (!(Array.isArray(accounts.items) ? accounts.items : []).some((a) => isObject(a) && a.status === "ACTIVE" && isObject(a.auth_config) && a.auth_config.id === authConfig)) {
161
+ const link = await ask("making the connect link", "POST", "/api/v3/connected_accounts/link", { auth_config_id: authConfig, user_id: user });
162
+ connect = text(link.redirect_url) || undefined;
163
+ }
164
+ }
165
+ url = composioAddress(address);
166
+ const server = await save({ url, auth: { type: "headers", headers: { "x-api-key": key } } });
167
+ // Composio's server can leave out an action it was allowed (HACKERNEWS_GET_FRONTPAGE, live 11-13): say which, so a grant
168
+ // doesn't vanish without a word. A toolkit with no account yet still lists its actions, so this holds before the connect.
169
+ const listed = new Set((server.tools ?? []).map((tool) => tool.name));
170
+ const missing = tools.filter((slug) => !listed.has(slug));
171
+ return { server, ...(connect ? { connect_url: connect } : {}), ...(missing.length ? { not_served: missing } : {}) };
172
+ }
173
+ catch (error) {
174
+ if (url && savedUrl && (await savedUrl().catch(() => undefined)) === url)
175
+ throw error;
176
+ await ask("deleting the MCP server it made", "DELETE", `/api/v3.1/mcp/${encodeURIComponent(id)}`).catch(() => undefined);
177
+ throw error;
178
+ }
179
+ }
@@ -0,0 +1,125 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import { type AttachHub, type AttachSocket, type HelloResult } from "@parcha/agentrun-computer";
4
+ import { type WebSocket } from "ws";
5
+ import type { PairedComputerRow, PairedComputers } from "./store/index.js";
6
+ /** The characters of a pairing code: no 0, O, 1 or I, so a person reads it off a screen without a doubt. */
7
+ export declare const PAIRING_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
8
+ /** A computer's token starts with this, so a secret scanner knows one. */
9
+ export declare const ATTACH_TOKEN_PREFIX = "art_";
10
+ /** Pair tries a source address makes in a minute; the next waits. */
11
+ export declare const PAIR_TRIES_PER_MINUTE = 10;
12
+ /** The longest name a person gives a computer, in characters. */
13
+ export declare const PAIRED_NAME_MAX = 100;
14
+ /** What the store keeps of a secret: its SHA-256, in hex. */
15
+ export declare const sha256Hex: (value: string) => string;
16
+ /** A new pairing code: eight characters of PAIRING_ALPHABET in two groups of four ("K7PD-W3QX"). */
17
+ export declare function newPairingCode(pick?: (below: number) => number): string;
18
+ /** A code as a person typed it, in its one form ("k7pd w3qx" is "K7PD-W3QX"), or undefined when it is not one. */
19
+ export declare function pairingCodeOf(typed: unknown): string | undefined;
20
+ /** A new paired computer's id: PAIRED_ID_PREFIX and 16 lowercase letters and digits. */
21
+ export declare const newPairedId: (pick?: (below: number) => number) => string;
22
+ /** A new computer token: ATTACH_TOKEN_PREFIX and 32 random bytes. */
23
+ export declare const newAttachToken: () => string;
24
+ /** `reason` cut to what a close frame holds (123 bytes of UTF-8), never inside a character. */
25
+ export declare function closeReason(reason: string): string;
26
+ /** The pair route's limit: PAIR_TRIES_PER_MINUTE tries a minute by source address (peerKey: an IPv6 one by its /64). */
27
+ export declare class PairTries {
28
+ #private;
29
+ private readonly now;
30
+ private readonly peers;
31
+ constructor(now?: () => number, peers?: number);
32
+ /** Counts a try from `address`: ok, or how long until the next is let in. */
33
+ allow(address: string): {
34
+ ok: true;
35
+ } | {
36
+ ok: false;
37
+ retryAfterMs: number;
38
+ };
39
+ }
40
+ /** POST /v2/computers/pair's body checked: its code in its one form, the name, and the driver's hello; or input_invalid
41
+ * naming each field that is wrong. The protocol version is the caller's next check (pairRefusal), not this one's. */
42
+ export declare function pairBodyOf(body: unknown): {
43
+ code: string;
44
+ name: string;
45
+ hello: HelloResult;
46
+ };
47
+ /** Why a driver's hello may not pair here, in the version rule's words (attach.ts helloMismatch), or undefined: its
48
+ * protocol version must be this server's. The code stays good, for the driver once it is updated. */
49
+ export declare function pairRefusal(name: string, hello: HelloResult): string | undefined;
50
+ /** A paired computer as GET /v2/computers lists it under `paired`: whatever its hello says it is (its os and version, its
51
+ * device, its screen, its groups and features: the live hello's while it is attached, else its last one), the
52
+ * setting kinds it serves and why it serves none, whether it is attached now, its driver's build, and the run that holds it and until when.
53
+ * Nothing here is any one OS's: a driver on any OS is shown by the same fields. */
54
+ export type PairedView = {
55
+ id: string;
56
+ name: string;
57
+ kind: string;
58
+ serves: string[];
59
+ /** When it serves no kind, why, naming what its driver lacks (servesNoKind); null when it serves one. */
60
+ unserved: string | null;
61
+ os: string;
62
+ os_version: string | null;
63
+ device: {
64
+ maker: string;
65
+ model: string;
66
+ } | null;
67
+ arch: string;
68
+ screen: {
69
+ width: number;
70
+ height: number;
71
+ scale: number;
72
+ } | null;
73
+ groups: string[];
74
+ features: Record<string, true | {
75
+ off: string;
76
+ }>;
77
+ driver: string;
78
+ online: boolean;
79
+ held_by_run: string | null;
80
+ held_until: string | null;
81
+ /** The pairing (createPairing's id) whose code paired it. */
82
+ pairing: string;
83
+ created_at: string;
84
+ seen_at: string | null;
85
+ };
86
+ export declare function pairedView(row: PairedComputerRow, hub: Pick<AttachHub, "online" | "hello" | "claimed" | "deadline">, serves: readonly string[]): PairedView;
87
+ /** How the socket's liveness is timed: ATTACH_HEARTBEAT_MS and ATTACH_IDLE_MS, unless a test gives its own. */
88
+ export type AttachTiming = {
89
+ readonly heartbeatMs: number;
90
+ readonly idleMs: number;
91
+ };
92
+ /** One WebSocket as the hub takes it (attach.ts AttachSocket): text frames in and out; a ping each heartbeat; closed
93
+ * with ATTACH_CLOSE.idle once nothing (no frame, ping or pong) is heard for idleMs, and with ATTACH_CLOSE.binary on a
94
+ * binary frame. A frame over MAX_LINE_BYTES is the server's maxPayload, which closes it with 1009 itself. */
95
+ export declare function attachSocketOf(ws: WebSocket, timing?: AttachTiming): AttachSocket;
96
+ export interface AttachRoutesOptions {
97
+ readonly store: {
98
+ readonly pairedComputers: PairedComputers;
99
+ };
100
+ readonly hub: AttachHub;
101
+ /** Told each event worth a line: a computer paired, attached, refused at its hello, removed. Never a code or a token. */
102
+ readonly log?: (event: string, fields: Record<string, string>) => void;
103
+ /** The socket's liveness timing: the protocol's unless a test gives its own. */
104
+ readonly timing?: AttachTiming;
105
+ readonly now?: () => number;
106
+ /** Told each socket taken, with its computer, before its hello: the binding's conformance run (attach-conformance.ts)
107
+ * watches the raw socket to see how a driver answers a close, a drop and a frame it must refuse. */
108
+ readonly onSocket?: (computer: string, ws: WebSocket) => void;
109
+ }
110
+ /** The pairing routes and the attach socket over one store and one hub. */
111
+ export declare function createAttachRoutes(options: AttachRoutesOptions): {
112
+ createPairing: () => Promise<{
113
+ id: string;
114
+ code: string;
115
+ expires_at: string;
116
+ }>;
117
+ pair: (body: unknown, address: string) => Promise<{
118
+ computer: string;
119
+ token: string;
120
+ }>;
121
+ remove: (id: string) => Promise<void>;
122
+ upgrade: (req: IncomingMessage, socket: Duplex, head: Buffer, deny: (status: string, words?: string, headers?: Record<string, string>) => void) => void;
123
+ close: () => Promise<void>;
124
+ };
125
+ export type AttachRoutes = ReturnType<typeof createAttachRoutes>;