@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30

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 (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,72 @@
1
+ import type { BoxProvider } from "@parcha/pi-transport";
2
+ /** Why the VM box has no network, said in capabilities whenever the server's host list is set: its provider's SDK takes
3
+ * a domain list at a sandbox's create, but has no read of a sandbox's network back, so the server could not check that
4
+ * a box holds the list it asked for (as it does Daytona's), and it never leaves the provider's open default either. */
5
+ export declare const VM_NO_LIST = "the Modal sandbox takes a host list, but this server cannot read a sandbox's list back to check that it holds, so the Modal sandbox has no network";
6
+ /** The VM provider: its box id, which is also its SDK's npm name, the SDK's client class and the token's names. */
7
+ export declare const VM_PROVIDER: {
8
+ readonly id: "modal";
9
+ readonly client: "ModalClient";
10
+ readonly keys: readonly ["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"];
11
+ };
12
+ /** Every box a place may name, in the order capabilities lists them. */
13
+ export declare const BOX_IDS: readonly ["bwrap", "docker", "modal", "daytona"];
14
+ export type BoxId = (typeof BOX_IDS)[number];
15
+ /** One box: whether this server has it, and why when not (or how it was checked). `state`, set where the server knows
16
+ * more than the probe did (box-image.ts): `preparing` is available, its image still coming. */
17
+ /** A box as capabilities show it. `network`: what an available box reaches (BOX_NETWORKS), with `network_reason` when
18
+ * it is available and has none for a cause of its own (a Docker in a VM, a daemon elsewhere; a Daytona that could not
19
+ * keep its domain list). */
20
+ export type BoxOffer = {
21
+ id: BoxId;
22
+ available: boolean;
23
+ state?: BoxState;
24
+ reason?: string;
25
+ network?: BoxNetwork;
26
+ network_reason?: string;
27
+ };
28
+ /** What an available box reaches: the hosts of `places.allow` (`allowlist`), or nothing (`none`). */
29
+ export declare const BOX_NETWORKS: readonly ["allowlist", "none"];
30
+ export type BoxNetwork = (typeof BOX_NETWORKS)[number];
31
+ /** A box's state in capabilities: ready, preparing (available; a run's first box waits for its image), or unavailable. */
32
+ export declare const BOX_STATES: readonly ["ready", "preparing", "unavailable"];
33
+ export type BoxState = (typeof BOX_STATES)[number];
34
+ /** The boxes this server set up at its start. */
35
+ export type BoxRegistry = {
36
+ /** Every box, in BOX_IDS order. */
37
+ offers(): BoxOffer[];
38
+ /** An available box's provider; undefined for any other. */
39
+ provider(id: BoxId): BoxProvider | undefined;
40
+ /** The VM box's SDK client, when it is available: the box relay makes a run's calls with it (box-relay-vm.ts). */
41
+ vmClient(): unknown;
42
+ };
43
+ /** What boxRegistry takes beyond the environment: the probes' bound, and, for tests only, the module that stands in for
44
+ * the VM provider's SDK (startServe's `fauxVm`, under --faux). */
45
+ export type BoxRegistryOptions = {
46
+ timeoutMs?: number;
47
+ vmSdk?: () => Promise<Record<string, unknown>>;
48
+ };
49
+ /** The setting that lists the boxes to set up: a comma list of box ids. */
50
+ export declare const BOXES_ENV = "AGENTRUN_BOXES";
51
+ /** The VM provider's app, which its sandboxes live in (made when missing). */
52
+ export declare const BOX_APP_ENV = "AGENTRUN_BOX_APP";
53
+ /** Daytona's API when DAYTONA_API_URL names none: pi-transport's own default. */
54
+ export declare const DAYTONA_API_URL = "https://app.daytona.io/api";
55
+ /** Daytona's API and this server's key for it, from its environment (its secrets readable); undefined without a key. The
56
+ * key goes to the server's Daytona provider and its box relay, never further (box-relay.ts). */
57
+ export declare function daytonaApi(env: NodeJS.ProcessEnv): {
58
+ apiKey: string;
59
+ apiUrl: string;
60
+ } | undefined;
61
+ /** The boxes' keys: secrets the server holds and the probes read, which no run's process is handed (runs.ts). */
62
+ export declare const BOX_KEYS: readonly string[];
63
+ /** How long one box's probe may take; the probes run at once, so this bounds them all. */
64
+ export declare const PROBE_TIMEOUT_MS = 5000;
65
+ /** The boxes `env` lists in AGENTRUN_BOXES; a name that is no box throws, naming it. */
66
+ export declare function enabledBoxes(env: NodeJS.ProcessEnv): Set<BoxId>;
67
+ /** The boxes `env` (the server's environment, its secrets readable) lists, each probed once, all at once, each within
68
+ * `timeoutMs`. Rejects only for a name that is no box: a probe that fails, throws or takes too long leaves its box
69
+ * unavailable, with a short reason that holds no key and no answer's body. */
70
+ export declare function boxRegistry(env: NodeJS.ProcessEnv, options?: BoxRegistryOptions): Promise<BoxRegistry>;
71
+ /** The start's log line: the boxes available, the rest, and why each box AGENTRUN_BOXES lists (`listed`) is not available. */
72
+ export declare function boxesLog(offers: readonly BoxOffer[], listed: ReadonlySet<BoxId>): Record<string, string>;
package/dist/boxes.js ADDED
@@ -0,0 +1,189 @@
1
+ // The boxes this server can give a run: Docker, Daytona and a VM provider, each a pi-transport provider built from the
2
+ // server's settings and probed once at its start. bwrap comes later. The registry says which boxes this server has, why
3
+ // it lacks the others, and hands out an available box's provider (and the VM box's client, for the box relay).
4
+ //
5
+ // AGENTRUN_BOXES lists the boxes to set up. A box it does not list is never probed and is unavailable, its reason naming
6
+ // the setting that lists it; a name in it that is no box refuses the start. Every reason says what to do next.
7
+ // pi-transport is an optional peer of this package and the VM provider's SDK is the host's, so each is loaded by the
8
+ // probe that needs it, and a box whose module is not installed says what to install. The keys are the server's own: the
9
+ // launcher hands them over with its other secrets (secrets.ts), the probes read them here, and no run's process is
10
+ // handed one (SERVER_ONLY in runs.ts).
11
+ import { execFile } from "node:child_process";
12
+ import { randomUUID } from "node:crypto";
13
+ import { BACKGROUND_CONTEXT, withAbortSignal } from "@earendil-works/chord/context";
14
+ import { withoutSecrets } from "./secrets.js";
15
+ /** Why the VM box has no network, said in capabilities whenever the server's host list is set: its provider's SDK takes
16
+ * a domain list at a sandbox's create, but has no read of a sandbox's network back, so the server could not check that
17
+ * a box holds the list it asked for (as it does Daytona's), and it never leaves the provider's open default either. */
18
+ export const VM_NO_LIST = "the Modal sandbox takes a host list, but this server cannot read a sandbox's list back to check that it holds, so the Modal sandbox has no network";
19
+ /** The VM provider: its box id, which is also its SDK's npm name, the SDK's client class and the token's names. */
20
+ export const VM_PROVIDER = { id: "modal", client: "ModalClient", keys: ["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"] };
21
+ const VM = VM_PROVIDER.id;
22
+ /** Every box a place may name, in the order capabilities lists them. */
23
+ export const BOX_IDS = ["bwrap", "docker", VM, "daytona"];
24
+ /** What an available box reaches: the hosts of `places.allow` (`allowlist`), or nothing (`none`). */
25
+ export const BOX_NETWORKS = ["allowlist", "none"];
26
+ /** A box's state in capabilities: ready, preparing (available; a run's first box waits for its image), or unavailable. */
27
+ export const BOX_STATES = ["ready", "preparing", "unavailable"];
28
+ /** The setting that lists the boxes to set up: a comma list of box ids. */
29
+ export const BOXES_ENV = "AGENTRUN_BOXES";
30
+ /** The VM provider's app, which its sandboxes live in (made when missing). */
31
+ export const BOX_APP_ENV = "AGENTRUN_BOX_APP";
32
+ const DEFAULT_BOX_APP = "agentrun";
33
+ const DAYTONA_KEY = "DAYTONA_API_KEY";
34
+ /** Daytona's API when DAYTONA_API_URL names none: pi-transport's own default. */
35
+ export const DAYTONA_API_URL = "https://app.daytona.io/api";
36
+ /** Daytona's API and this server's key for it, from its environment (its secrets readable); undefined without a key. The
37
+ * key goes to the server's Daytona provider and its box relay, never further (box-relay.ts). */
38
+ export function daytonaApi(env) {
39
+ const apiKey = env[DAYTONA_KEY];
40
+ return apiKey ? { apiKey, apiUrl: env.DAYTONA_API_URL || DAYTONA_API_URL } : undefined;
41
+ }
42
+ /** The boxes' keys: secrets the server holds and the probes read, which no run's process is handed (runs.ts). */
43
+ export const BOX_KEYS = [DAYTONA_KEY, ...VM_PROVIDER.keys];
44
+ /** How long one box's probe may take; the probes run at once, so this bounds them all. */
45
+ export const PROBE_TIMEOUT_MS = 5_000;
46
+ /** Why box `id` is unavailable when AGENTRUN_BOXES does not list it: the setting that does, keeping what it lists now. */
47
+ const notEnabled = (id, enabled) => `not enabled on this server: start AgentRun with ${BOXES_ENV}=${BOX_IDS.filter((box) => box === id || enabled.has(box)).join(",")}`;
48
+ const NOT_YET = "the bwrap box is not in this release yet: use the docker box";
49
+ const NOT_PROBED = "configured; not probed at start";
50
+ const TRANSPORT = "@parcha/pi-transport";
51
+ const unavailable = (id, reason) => ({ offer: { id, available: false, reason } });
52
+ const available = (id, provider, reason, client) => ({ offer: { id, available: true, ...(reason ? { reason } : {}) }, provider, ...(client === undefined ? {} : { client }) });
53
+ /** The boxes `env` lists in AGENTRUN_BOXES; a name that is no box throws, naming it. */
54
+ export function enabledBoxes(env) {
55
+ const names = (env[BOXES_ENV] ?? "").split(",").map((name) => name.trim()).filter(Boolean);
56
+ const unknown = names.filter((name) => !BOX_IDS.includes(name));
57
+ if (unknown.length)
58
+ throw new Error(`${BOXES_ENV} names ${unknown.join(", ")}, which ${unknown.length === 1 ? "is not a box" : "are not boxes"}: list any of ${BOX_IDS.join(", ")}`);
59
+ return new Set(names);
60
+ }
61
+ /** The boxes `env` (the server's environment, its secrets readable) lists, each probed once, all at once, each within
62
+ * `timeoutMs`. Rejects only for a name that is no box: a probe that fails, throws or takes too long leaves its box
63
+ * unavailable, with a short reason that holds no key and no answer's body. */
64
+ export async function boxRegistry(env, options = {}) {
65
+ const enabled = enabledBoxes(env);
66
+ const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
67
+ const probed = await Promise.all(BOX_IDS.map((id) => {
68
+ if (id === "bwrap")
69
+ return unavailable(id, NOT_YET);
70
+ if (!enabled.has(id))
71
+ return unavailable(id, notEnabled(id, enabled));
72
+ return bounded(id, timeoutMs, (signal) => PROBES[id](env, signal, options));
73
+ }));
74
+ return {
75
+ offers: () => probed.map(({ offer }) => ({ ...offer })),
76
+ provider: (id) => probed.find(({ offer }) => offer.id === id && offer.available)?.provider,
77
+ vmClient: () => probed.find(({ offer }) => offer.id === VM && offer.available)?.client,
78
+ };
79
+ }
80
+ /** The start's log line: the boxes available, the rest, and why each box AGENTRUN_BOXES lists (`listed`) is not available. */
81
+ export function boxesLog(offers, listed) {
82
+ const ids = (yes) => offers.filter((offer) => offer.available === yes).map((offer) => offer.id).join(",") || "none";
83
+ const why = offers.filter((offer) => !offer.available && listed.has(offer.id));
84
+ return { available: ids(true), unavailable: ids(false), ...Object.fromEntries(why.map((offer) => [offer.id, offer.reason ?? ""])) };
85
+ }
86
+ /** `probe`, aborted after `timeoutMs`. Never rejects. */
87
+ async function bounded(id, timeoutMs, probe) {
88
+ const controller = new AbortController();
89
+ let timer;
90
+ const late = new Promise((resolve) => {
91
+ timer = setTimeout(() => {
92
+ controller.abort();
93
+ resolve(unavailable(id, `its probe did not finish within ${timeoutMs} ms`));
94
+ }, timeoutMs);
95
+ });
96
+ try {
97
+ return await Promise.race([probe(controller.signal).catch((error) => unavailable(id, `its probe failed (${errorName(error)})`)), late]);
98
+ }
99
+ finally {
100
+ clearTimeout(timer);
101
+ }
102
+ }
103
+ /** What kind of error, never its message: a message can hold an answer's body, a path or a key. */
104
+ function errorName(error) {
105
+ const code = error?.code;
106
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code))
107
+ return code;
108
+ return error instanceof Error ? error.name : "not an error";
109
+ }
110
+ /** A module of package `name`, which may not be installed: then the box says to install it. */
111
+ async function load(name, importer) {
112
+ try {
113
+ return { ok: true, value: await importer() };
114
+ }
115
+ catch (error) {
116
+ const missing = error?.code === "ERR_MODULE_NOT_FOUND" && String(error.message).includes(`'${name}'`);
117
+ return { ok: false, reason: missing ? `install ${name} to use this box` : `${name} did not load (${errorName(error)})` };
118
+ }
119
+ }
120
+ const PROBES = {
121
+ /** `docker version` names the daemon's version: the CLI is on PATH and its daemon answers this user. */
122
+ async docker(env, signal) {
123
+ const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/docker").then((module) => module.dockerBoxes));
124
+ if (!boxes.ok)
125
+ return unavailable("docker", boxes.reason);
126
+ // Its environment is the server's through the cut a run's takes (withoutSecrets): no box key, no other secret, no
127
+ // name shaped like a key.
128
+ const dockerEnv = withoutSecrets(env);
129
+ const answer = await new Promise((resolve) => execFile("docker", ["version", "--format", "{{.Server.Version}}"], { env: dockerEnv, signal, maxBuffer: 64 * 1024 }, (error, stdout) => {
130
+ const code = error?.code;
131
+ resolve({ ...(error ? { failed: typeof code === "number" ? `exit ${code}` : errorName(error) } : {}), out: String(stdout) });
132
+ }));
133
+ // The probe runs once, at the start: each fix takes a restart.
134
+ if (answer.failed === "ENOENT")
135
+ return unavailable("docker", "no docker command on this server's PATH: install Docker, then restart this server");
136
+ if (answer.failed)
137
+ return unavailable("docker", `docker version failed (${answer.failed}): start Docker, or add this server's user to the docker group, then restart this server`);
138
+ if (!answer.out.trim())
139
+ return unavailable("docker", "docker version named no Docker daemon: start Docker, then restart this server");
140
+ return available("docker", boxes.value());
141
+ },
142
+ /** One authenticated read the provider makes anyway: the box with a name no box has (lowercase letters, digits and
143
+ * dashes). An answer of no such box (404) means Daytona took the key; 401 or 403 means it refused it. */
144
+ async daytona(env, signal) {
145
+ const apiKey = env[DAYTONA_KEY];
146
+ if (!apiKey)
147
+ return unavailable("daytona", `needs ${DAYTONA_KEY}`);
148
+ const apiUrl = env.DAYTONA_API_URL || undefined;
149
+ if (apiUrl !== undefined && !URL.canParse(apiUrl))
150
+ return unavailable("daytona", "DAYTONA_API_URL is not a URL");
151
+ const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/daytona").then((module) => module.daytonaBoxes));
152
+ if (!boxes.ok)
153
+ return unavailable("daytona", boxes.reason);
154
+ const provider = boxes.value({ apiKey, ...(apiUrl ? { apiUrl } : {}), ...(env.DAYTONA_TARGET ? { target: env.DAYTONA_TARGET } : {}) });
155
+ const found = await provider.attach(`agentrun-probe-${randomUUID()}`, withAbortSignal(signal, BACKGROUND_CONTEXT));
156
+ if (found.ok)
157
+ return available("daytona", provider);
158
+ if (found.error.code === "unauthorized")
159
+ return unavailable("daytona", `Daytona refused ${DAYTONA_KEY}`);
160
+ return unavailable("daytona", `Daytona did not answer the probe (${found.error.code})`);
161
+ },
162
+ /** The SDK is installed and the token is set; nothing is asked of the provider at start. The client gets the token as
163
+ * arguments: the server's environment does not hold it (secrets.ts). */
164
+ async [VM](env, _signal, options) {
165
+ const missing = VM_PROVIDER.keys.filter((name) => !env[name]);
166
+ if (missing.length)
167
+ return unavailable(VM, `needs ${missing.join(" and ")}`);
168
+ const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/modal").then((module) => module.modalBoxes));
169
+ if (!boxes.ok)
170
+ return unavailable(VM, boxes.reason);
171
+ const vmBoxes = boxes.value;
172
+ // The SDK is not a dependency of this package (the host installs it), so its name is a value here, not a literal import.
173
+ const sdk = await load(VM, options.vmSdk ?? (() => import(VM)));
174
+ if (!sdk.ok)
175
+ return unavailable(VM, sdk.reason);
176
+ const Client = sdk.value[VM_PROVIDER.client];
177
+ if (typeof Client !== "function")
178
+ return unavailable(VM, `the installed ${VM} package has no ${VM_PROVIDER.client}`);
179
+ const [tokenId, tokenSecret] = VM_PROVIDER.keys.map((name) => env[name]);
180
+ let client;
181
+ try {
182
+ client = new Client({ tokenId, tokenSecret });
183
+ }
184
+ catch (error) {
185
+ return unavailable(VM, `its SDK's client did not start (${errorName(error)})`);
186
+ }
187
+ return available(VM, vmBoxes(client, { appName: env[BOX_APP_ENV] || DEFAULT_BOX_APP }), NOT_PROBED, client);
188
+ },
189
+ };
@@ -0,0 +1,41 @@
1
+ import type { Context } from "@earendil-works/chord";
2
+ import { type Conversation, type Session, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
3
+ import type { SessionCharge } from "@parcha/pi-browser";
4
+ /** List prices by pi-browser provider name (`provider.name`): Browserbase's (pi-browser's LIST_PRICES), $0.12 an hour with
5
+ * a one-minute minimum; Kernel's headless browser, about $0.06 an hour billed by the second; a local Chrome (`cdp`), free. */
6
+ export declare const BROWSER_PRICES: Readonly<Record<string, {
7
+ usdPerHour: number;
8
+ minimumS: number;
9
+ }>>;
10
+ /** An operator's price for a provider, in USD an hour: this prefix and the provider's name in capitals
11
+ * (AGENTRUN_BROWSER_USD_PER_HOUR_BROWSERBASE, _KERNEL, _CDP). */
12
+ export declare const BROWSER_PRICE_ENV = "AGENTRUN_BROWSER_USD_PER_HOUR_";
13
+ /** What a release may take to be confirmed at the provider once it is asked (pi-browser's confirm polls back off 0.5 to 4 s). */
14
+ export declare const RELEASE_ALLOWANCE_S = 30;
15
+ /** How long pi-browser leaves a create whose answer was lost before it releases it by its tag (its create deadline; serve
16
+ * keeps the default). */
17
+ export declare const CREATE_DEADLINE_S = 60;
18
+ export declare const priceEnvOf: (provider: string) => string;
19
+ /** `provider`'s session price: the operator's (a non-negative decimal), else the list's; `usdPerHour` null when neither
20
+ * names one or the operator's cannot be read, which is no price, never $0. */
21
+ export declare function browserPrice(provider: string, env: NodeJS.ProcessEnv): {
22
+ usdPerHour: number | null;
23
+ minimumS: number;
24
+ };
25
+ /** One run's browser bookings, for its one provider at `price` with pi-browser's idle window `idleS`. `release` lets go of
26
+ * a conversation's session (pi-browser's release, "close"). */
27
+ export declare function browserSpend(provider: string, price: {
28
+ usdPerHour: number | null;
29
+ minimumS: number;
30
+ }, idleS: number, release: (conversation: Pick<Conversation, "id" | "commit">, context: Context) => Promise<void>): {
31
+ onCharge: (charge: SessionCharge, tx: Tx, call?: {
32
+ callId: string;
33
+ }) => Promise<void>;
34
+ watch: (harness: Pick<Session, "subscribeCommits">, inventory?: string) => void;
35
+ reopened: (harness: Pick<Session, "snapshot">, docs: {
36
+ Inventory: unknown;
37
+ Sessions: unknown;
38
+ }, context: Context) => Promise<void>;
39
+ capped: (tool: ToolRegistration) => ToolRegistration;
40
+ stretch: number;
41
+ };
@@ -0,0 +1,158 @@
1
+ import { ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
2
+ import { TOOL_COST } from "@parcha/pi-durable-agent/timeline";
3
+ import { addSpend, keepHold, paidCall, runCap, SPEND_CAP_REACHED } from "./cap.js";
4
+ import { forModel } from "./result.js";
5
+ /** List prices by pi-browser provider name (`provider.name`): Browserbase's (pi-browser's LIST_PRICES), $0.12 an hour with
6
+ * a one-minute minimum; Kernel's headless browser, about $0.06 an hour billed by the second; a local Chrome (`cdp`), free. */
7
+ export const BROWSER_PRICES = Object.freeze({
8
+ browserbase: { usdPerHour: 0.12, minimumS: 60 },
9
+ kernel: { usdPerHour: 0.06, minimumS: 0 },
10
+ cdp: { usdPerHour: 0, minimumS: 0 },
11
+ });
12
+ /** An operator's price for a provider, in USD an hour: this prefix and the provider's name in capitals
13
+ * (AGENTRUN_BROWSER_USD_PER_HOUR_BROWSERBASE, _KERNEL, _CDP). */
14
+ export const BROWSER_PRICE_ENV = "AGENTRUN_BROWSER_USD_PER_HOUR_";
15
+ /** What a release may take to be confirmed at the provider once it is asked (pi-browser's confirm polls back off 0.5 to 4 s). */
16
+ export const RELEASE_ALLOWANCE_S = 30;
17
+ /** How long pi-browser leaves a create whose answer was lost before it releases it by its tag (its create deadline; serve
18
+ * keeps the default). */
19
+ export const CREATE_DEADLINE_S = 60;
20
+ export const priceEnvOf = (provider) => `${BROWSER_PRICE_ENV}${provider.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
21
+ /** `provider`'s session price: the operator's (a non-negative decimal), else the list's; `usdPerHour` null when neither
22
+ * names one or the operator's cannot be read, which is no price, never $0. */
23
+ export function browserPrice(provider, env) {
24
+ const listed = Object.hasOwn(BROWSER_PRICES, provider) ? BROWSER_PRICES[provider] : undefined;
25
+ const text = env[priceEnvOf(provider)]?.trim();
26
+ const given = text ? (/^(\d+(\.\d*)?|\.\d+)$/.test(text) ? Number(text) : NaN) : undefined;
27
+ return { usdPerHour: given === undefined ? (listed?.usdPerHour ?? null) : Number.isFinite(given) ? given : null, minimumS: listed?.minimumS ?? 0 };
28
+ }
29
+ /** One run's browser bookings, for its one provider at `price` with pi-browser's idle window `idleS`. `release` lets go of
30
+ * a conversation's session (pi-browser's release, "close"). */
31
+ export function browserSpend(provider, price, idleS, release) {
32
+ const rate = price.usdPerHour;
33
+ const usdOf = (seconds) => ((rate ?? 0) * seconds) / 3600;
34
+ const stretchS = price.minimumS + idleS + RELEASE_ALLOWANCE_S;
35
+ const stretch = usdOf(stretchS);
36
+ const sessions = new Map();
37
+ /** Each call under way, by its id: its conversation and its hold. */
38
+ const calls = new Map();
39
+ const take = (hold, usd) => void (hold && (hold.usd = Math.max(0, hold.usd - usd)));
40
+ /** Booked in the commit that bills it: a TOOL_COST under the call that ran it (a release's, under its session's last
41
+ * call), what it cost or null when its time has no price, and the seconds it was for, with what `booked` needs. A free
42
+ * provider's time books nothing and holds nothing. */
43
+ async function onCharge(charge, tx, call) {
44
+ if (rate === 0)
45
+ return;
46
+ const usd = charge.state === "priced" ? charge.usd : null;
47
+ const data = { tool: "browser", charged_by: charge.provider, call: call?.callId ?? sessions.get(charge.tag)?.call ?? null, usd, seconds: charge.seconds, tag: charge.tag, conversation: charge.conversationId, at: charge.at, final: charge.final };
48
+ await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: TOOL_COST, data });
49
+ }
50
+ /** A charge whose commit is in (watch): it joins what the run's process counts as spent, and moves the holds. Never
51
+ * inside the commit, so one that fails changes neither. */
52
+ function booked(data) {
53
+ const usd = data.usd ?? 0;
54
+ const session = sessions.get(data.tag);
55
+ addSpend(data.usd);
56
+ if (data.final) {
57
+ // A session the provider ended before its first charge has no reserve: its release comes out of its call's hold.
58
+ take(session?.reserve ?? [...calls.values()].find((c) => c.cid === data.conversation)?.hold, usd);
59
+ session?.reserve.drop();
60
+ sessions.delete(data.tag);
61
+ }
62
+ else if (session) {
63
+ take(data.call === null ? undefined : calls.get(data.call)?.hold, usd);
64
+ // Its reserve is one stretch again: a kept session's held what it ran before this charge, which booked it.
65
+ session.reserve.usd = stretch;
66
+ Object.assign(session, { at: Date.parse(data.at), call: data.call ?? session.call });
67
+ }
68
+ else {
69
+ take(data.call === null ? undefined : calls.get(data.call)?.hold, usd + stretch);
70
+ sessions.set(data.tag, { cid: data.conversation, reserve: keepHold(stretch), at: Date.parse(data.at), call: data.call });
71
+ }
72
+ }
73
+ /** At a reopen, after pi-browser's reconcile: every session its custody still tracks (each row of its inventory: kept,
74
+ * unreached, still releasing, lost) is held from here as if opened in this process, at a stretch beside what it ran
75
+ * since its last charge, the time the process was down included; that is already spent at the provider, so it is
76
+ * held, never refused. Its final charge, or its leaving the inventory, lets it go. One billed in full is not held. */
77
+ async function reopened(harness, docs, context) {
78
+ if (rate === 0)
79
+ return;
80
+ const rows = Object.values((await harness.snapshot(docs.Inventory, context))?.rows ?? {});
81
+ for (const row of rows.filter((r) => !sessions.has(r.tag))) {
82
+ const record = (await harness.snapshot(docs.Sessions, row.conversationId, context))?.sessions?.find((s) => s.tag === row.tag);
83
+ const at = Date.parse(record?.spent.chargedThrough ?? "");
84
+ // Billed in full already (its release's charge landed since reconcile): nothing is left to hold, nor to drop it.
85
+ if (!Number.isFinite(at) || record?.spent.final)
86
+ continue;
87
+ // Its reserve carries the down time, so its calls count what it runs from here (`at` now), not the down time again.
88
+ const now = Date.now();
89
+ sessions.set(row.tag, { cid: row.conversationId, reserve: keepHold(stretch + usdOf(Math.max(0, now - at) / 1000)), at: now, call: null });
90
+ }
91
+ }
92
+ /** The open-session inventory as committed: a session it no longer holds lets go of its reserve (released, billed or
93
+ * not); one whose create's answer was lost, left to a release after the create deadline (releasing, no id), is held
94
+ * for that deadline and a stretch, out of its call's hold (two stretches, never less), until its release is billed or
95
+ * ends it. */
96
+ function tracked(rows) {
97
+ for (const [tag, open] of sessions)
98
+ if (!Object.hasOwn(rows, tag))
99
+ (open.reserve.drop(), sessions.delete(tag));
100
+ for (const row of Object.values(rows)) {
101
+ if (rate === 0 || row.state !== "releasing" || row.resourceId !== null || sessions.has(row.tag))
102
+ continue;
103
+ const usd = usdOf(CREATE_DEADLINE_S + stretchS);
104
+ take([...calls.values()].find((c) => c.cid === row.conversationId)?.hold, usd);
105
+ sessions.set(row.tag, { cid: row.conversationId, reserve: keepHold(usd), at: Date.now(), call: null });
106
+ }
107
+ }
108
+ /** Applies each browser charge `harness` commits, and each change of pi-browser's inventory (the document of kind
109
+ * `inventory`), once the commit is in: the charges first, so a release billed and ended in one commit is billed from
110
+ * its reserve before it goes. */
111
+ function watch(harness, inventory = "browser.inventory") {
112
+ harness.subscribeCommits((publication) => {
113
+ for (const change of publication.changes) {
114
+ const data = change.type === "entry" && change.value.kind === TOOL_COST ? change.value.data : undefined;
115
+ if (data?.tool === "browser" && typeof data.tag === "string")
116
+ booked(data);
117
+ }
118
+ for (const change of publication.changes) {
119
+ if (change.type === "document" && change.record.kind === inventory && change.value)
120
+ tracked((change.value.rows) ?? {});
121
+ }
122
+ });
123
+ }
124
+ /** `tool` held under the run's cap before each call. */
125
+ function capped(tool) {
126
+ return {
127
+ ...tool,
128
+ execute: async (args, api, context) => {
129
+ const cap = runCap();
130
+ if (cap !== undefined && rate === null)
131
+ return refuse(`${SPEND_CAP_REACHED}: This browser call was not sent. ${provider}'s session time has no price here (${priceEnvOf(provider)} gives one), so the run's cap of $${cap} cannot be kept: the run is out of budget.`, api, context);
132
+ const now = Date.now();
133
+ const ranS = [...sessions.values()].filter((s) => s.cid === api.conversationId).reduce((sum, s) => sum + Math.max(0, now - s.at) / 1000, 0);
134
+ // Up to the millionth of a dollar, so the cap's words name a figure never below the hold.
135
+ const usd = Math.ceil(Math.round((usdOf(ranS) + 2 * stretch) * 1e12) / 1e6) / 1e6;
136
+ const basis = `${provider}'s session time at $${rate} an hour: the ${Math.round(ranS)} s its session ran since its last charge, and twice the next stretch of ${stretchS} s (its ${price.minimumS} s minimum, the ${idleS} s idle window and ${RELEASE_ALLOWANCE_S} s for its release)`;
137
+ const paid = await paidCall("this browser call", async () => keepHold(usd), () => undefined, { usd, basis });
138
+ if ("refused" in paid)
139
+ return refuse(paid.refused, api, context);
140
+ const hold = paid.result;
141
+ calls.set(api.callId, { cid: api.conversationId, hold });
142
+ try {
143
+ return await tool.execute(args, api, context);
144
+ }
145
+ finally {
146
+ calls.delete(api.callId);
147
+ hold.drop();
148
+ }
149
+ },
150
+ };
151
+ }
152
+ /** The cap's refusal as the call's error, and the conversation's session let go, so it runs no longer. */
153
+ async function refuse(why, api, context) {
154
+ await release({ id: api.conversationId, commit: api.commit.bind(api) }, context).catch(() => undefined);
155
+ return forModel(JSON.stringify({ error: why }), { isError: true });
156
+ }
157
+ return { onCharge, watch, reopened, capped, stretch };
158
+ }