@parcha/agentrun-serve 0.0.0-bootstrap.0 → 0.1.0-beta.29

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 (229) hide show
  1. package/CHANGELOG.md +560 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +1724 -0
  5. package/dist/adapters.d.ts +205 -0
  6. package/dist/adapters.js +459 -0
  7. package/dist/agents.d.ts +124 -0
  8. package/dist/agents.js +302 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +324 -0
  11. package/dist/bound-files.d.ts +4 -0
  12. package/dist/bound-files.js +164 -0
  13. package/dist/box/record.d.ts +6 -0
  14. package/dist/box/record.js +41 -0
  15. package/dist/box/sweep.d.ts +53 -0
  16. package/dist/box/sweep.js +193 -0
  17. package/dist/box-image.d.ts +98 -0
  18. package/dist/box-image.js +283 -0
  19. package/dist/box-relay.d.ts +42 -0
  20. package/dist/box-relay.js +222 -0
  21. package/dist/boxes.d.ts +54 -0
  22. package/dist/boxes.js +182 -0
  23. package/dist/cap.d.ts +224 -0
  24. package/dist/cap.js +721 -0
  25. package/dist/catalog.d.ts +20 -0
  26. package/dist/catalog.js +53 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +167 -0
  29. package/dist/coding-tools.d.ts +31 -0
  30. package/dist/coding-tools.js +81 -0
  31. package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
  32. package/dist/console/assets/index-BN7oVcO4.js +445 -0
  33. package/dist/console/assets/index-By-jkqki.css +1 -0
  34. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  35. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  36. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  37. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  38. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  39. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  40. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  41. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  42. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  53. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  54. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  57. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  58. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  59. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  60. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  61. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  62. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  63. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  64. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  65. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  66. package/dist/console/index.html +15 -0
  67. package/dist/daytona-api.d.ts +21 -0
  68. package/dist/daytona-api.js +101 -0
  69. package/dist/decision-rows.d.ts +11 -0
  70. package/dist/decision-rows.js +116 -0
  71. package/dist/decisions.d.ts +94 -0
  72. package/dist/decisions.js +184 -0
  73. package/dist/effort-guidance.d.ts +5 -0
  74. package/dist/effort-guidance.js +14 -0
  75. package/dist/environment.d.ts +5 -0
  76. package/dist/environment.js +11 -0
  77. package/dist/errors.d.ts +72 -0
  78. package/dist/errors.js +66 -0
  79. package/dist/exa-keyless.d.ts +35 -0
  80. package/dist/exa-keyless.js +202 -0
  81. package/dist/fetch-page.d.ts +114 -0
  82. package/dist/fetch-page.js +182 -0
  83. package/dist/files.d.ts +60 -0
  84. package/dist/files.js +153 -0
  85. package/dist/grade.d.ts +96 -0
  86. package/dist/grade.js +348 -0
  87. package/dist/graph-view.d.ts +100 -0
  88. package/dist/graph-view.js +212 -0
  89. package/dist/harness-app.d.ts +38 -0
  90. package/dist/harness-app.js +626 -0
  91. package/dist/harness.d.ts +53 -0
  92. package/dist/harness.js +74 -0
  93. package/dist/home-path.d.ts +27 -0
  94. package/dist/home-path.js +78 -0
  95. package/dist/host-tools.d.ts +20 -0
  96. package/dist/host-tools.js +140 -0
  97. package/dist/host.d.ts +39 -0
  98. package/dist/host.js +81 -0
  99. package/dist/hosted-search.d.ts +27 -0
  100. package/dist/hosted-search.js +129 -0
  101. package/dist/import-sources.d.ts +104 -0
  102. package/dist/import-sources.js +629 -0
  103. package/dist/import-summary.d.ts +25 -0
  104. package/dist/import-summary.js +75 -0
  105. package/dist/import-worker.d.ts +26 -0
  106. package/dist/import-worker.js +41 -0
  107. package/dist/import.d.ts +145 -0
  108. package/dist/import.js +1221 -0
  109. package/dist/index.d.ts +7 -0
  110. package/dist/index.js +6 -0
  111. package/dist/key-check.d.ts +36 -0
  112. package/dist/key-check.js +108 -0
  113. package/dist/key-refusal.d.ts +51 -0
  114. package/dist/key-refusal.js +187 -0
  115. package/dist/learn/check.d.ts +99 -0
  116. package/dist/learn/check.js +259 -0
  117. package/dist/learn/grade.d.ts +79 -0
  118. package/dist/learn/grade.js +433 -0
  119. package/dist/learn/index.d.ts +7 -0
  120. package/dist/learn/index.js +11 -0
  121. package/dist/learn/invisible.d.ts +5 -0
  122. package/dist/learn/invisible.js +42 -0
  123. package/dist/learn/notes.d.ts +59 -0
  124. package/dist/learn/notes.js +146 -0
  125. package/dist/learn/reflect.d.ts +49 -0
  126. package/dist/learn/reflect.js +167 -0
  127. package/dist/learn/secrets.d.ts +18 -0
  128. package/dist/learn/secrets.js +111 -0
  129. package/dist/learn/skills.d.ts +84 -0
  130. package/dist/learn/skills.js +198 -0
  131. package/dist/learning-routes.d.ts +196 -0
  132. package/dist/learning-routes.js +609 -0
  133. package/dist/learning-run.d.ts +304 -0
  134. package/dist/learning-run.js +797 -0
  135. package/dist/learning-words.d.ts +73 -0
  136. package/dist/learning-words.js +171 -0
  137. package/dist/learning.d.ts +377 -0
  138. package/dist/learning.js +801 -0
  139. package/dist/llm.d.ts +40 -0
  140. package/dist/llm.js +37 -0
  141. package/dist/llms.txt +37 -0
  142. package/dist/mcp-servers.d.ts +115 -0
  143. package/dist/mcp-servers.js +445 -0
  144. package/dist/mcp.d.ts +51 -0
  145. package/dist/mcp.js +392 -0
  146. package/dist/model.d.ts +184 -0
  147. package/dist/model.js +484 -0
  148. package/dist/monid.d.ts +74 -0
  149. package/dist/monid.js +277 -0
  150. package/dist/openapi/agentrun-v2.openapi.json +4805 -0
  151. package/dist/openapi.d.ts +10 -0
  152. package/dist/openapi.js +1417 -0
  153. package/dist/owner.d.ts +55 -0
  154. package/dist/owner.js +222 -0
  155. package/dist/packs.d.ts +71 -0
  156. package/dist/packs.js +180 -0
  157. package/dist/page.d.ts +32 -0
  158. package/dist/page.js +133 -0
  159. package/dist/paid-calls.d.ts +46 -0
  160. package/dist/paid-calls.js +110 -0
  161. package/dist/pause.d.ts +68 -0
  162. package/dist/pause.js +97 -0
  163. package/dist/pdf-pages.d.ts +44 -0
  164. package/dist/pdf-pages.js +147 -0
  165. package/dist/place.d.ts +46 -0
  166. package/dist/place.js +105 -0
  167. package/dist/print.d.ts +20 -0
  168. package/dist/print.js +29 -0
  169. package/dist/propose.d.ts +38 -0
  170. package/dist/propose.js +82 -0
  171. package/dist/quiet-sqlite-warning.d.ts +1 -0
  172. package/dist/quiet-sqlite-warning.js +14 -0
  173. package/dist/request-start.d.ts +14 -0
  174. package/dist/request-start.js +226 -0
  175. package/dist/result.d.ts +3 -0
  176. package/dist/result.js +5 -0
  177. package/dist/rows.d.ts +46 -0
  178. package/dist/rows.js +121 -0
  179. package/dist/run-box.d.ts +134 -0
  180. package/dist/run-box.js +440 -0
  181. package/dist/run-manifest.d.ts +27 -0
  182. package/dist/run-manifest.js +60 -0
  183. package/dist/runnable.d.ts +80 -0
  184. package/dist/runnable.js +162 -0
  185. package/dist/runs.d.ts +840 -0
  186. package/dist/runs.js +2279 -0
  187. package/dist/secret-cut.d.ts +27 -0
  188. package/dist/secret-cut.js +109 -0
  189. package/dist/secrets.d.ts +50 -0
  190. package/dist/secrets.js +140 -0
  191. package/dist/server-lock.d.ts +44 -0
  192. package/dist/server-lock.js +140 -0
  193. package/dist/server.d.ts +626 -0
  194. package/dist/server.js +1756 -0
  195. package/dist/sessions.d.ts +4 -0
  196. package/dist/sessions.js +105 -0
  197. package/dist/skills.d.ts +31 -0
  198. package/dist/skills.js +68 -0
  199. package/dist/stats.d.ts +101 -0
  200. package/dist/stats.js +82 -0
  201. package/dist/tool-keys.d.ts +151 -0
  202. package/dist/tool-keys.js +273 -0
  203. package/dist/tool-plane.d.ts +143 -0
  204. package/dist/tool-plane.js +242 -0
  205. package/dist/tools.d.ts +147 -0
  206. package/dist/tools.js +253 -0
  207. package/dist/turn-end.d.ts +23 -0
  208. package/dist/turn-end.js +14 -0
  209. package/dist/turns.d.ts +34 -0
  210. package/dist/turns.js +202 -0
  211. package/dist/uploads.d.ts +104 -0
  212. package/dist/uploads.js +474 -0
  213. package/dist/usage.d.ts +29 -0
  214. package/dist/usage.js +58 -0
  215. package/dist/validate.d.ts +55 -0
  216. package/dist/validate.js +175 -0
  217. package/dist/web-fetch.d.ts +64 -0
  218. package/dist/web-fetch.js +262 -0
  219. package/dist/web-search.d.ts +54 -0
  220. package/dist/web-search.js +136 -0
  221. package/dist/webhooks.d.ts +182 -0
  222. package/dist/webhooks.js +487 -0
  223. package/dist/workspace-paths.d.ts +33 -0
  224. package/dist/workspace-paths.js +104 -0
  225. package/dist/workspace.d.ts +88 -0
  226. package/dist/workspace.js +369 -0
  227. package/launcher/agentrun-serve +109 -0
  228. package/package.json +96 -1
  229. package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/boxes.js ADDED
@@ -0,0 +1,182 @@
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. No run uses a box yet: the registry says which boxes
3
+ // this server has, why it lacks the others, and hands out an available box's provider.
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
+ /** The VM provider: its box id, which is also its SDK's npm name, the SDK's client class and the token's names. */
16
+ export const VM_PROVIDER = { id: "modal", client: "ModalClient", keys: ["MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET"] };
17
+ const VM = VM_PROVIDER.id;
18
+ /** Every box a place may name, in the order capabilities lists them. */
19
+ export const BOX_IDS = ["bwrap", "docker", VM, "daytona"];
20
+ /** A box's state in capabilities: ready, preparing (available; a run's first box waits for its image), or unavailable. */
21
+ export const BOX_STATES = ["ready", "preparing", "unavailable"];
22
+ /** The setting that lists the boxes to set up: a comma list of box ids. */
23
+ export const BOXES_ENV = "AGENTRUN_BOXES";
24
+ /** The VM provider's app, which its sandboxes live in (made when missing). */
25
+ export const BOX_APP_ENV = "AGENTRUN_BOX_APP";
26
+ const DEFAULT_BOX_APP = "agentrun";
27
+ const DAYTONA_KEY = "DAYTONA_API_KEY";
28
+ /** Daytona's API when DAYTONA_API_URL names none: pi-transport's own default. */
29
+ export const DAYTONA_API_URL = "https://app.daytona.io/api";
30
+ /** Daytona's API and this server's key for it, from its environment (its secrets readable); undefined without a key. The
31
+ * key goes to the server's Daytona provider and its box relay, never further (box-relay.ts). */
32
+ export function daytonaApi(env) {
33
+ const apiKey = env[DAYTONA_KEY];
34
+ return apiKey ? { apiKey, apiUrl: env.DAYTONA_API_URL || DAYTONA_API_URL } : undefined;
35
+ }
36
+ /** The boxes' keys: secrets the server holds and the probes read, which no run's process is handed (runs.ts). */
37
+ export const BOX_KEYS = [DAYTONA_KEY, ...VM_PROVIDER.keys];
38
+ /** How long one box's probe may take; the probes run at once, so this bounds them all. */
39
+ export const PROBE_TIMEOUT_MS = 5_000;
40
+ /** Why box `id` is unavailable when AGENTRUN_BOXES does not list it: the setting that does, keeping what it lists now. */
41
+ const notEnabled = (id, enabled) => `not enabled on this server: start AgentRun with ${BOXES_ENV}=${BOX_IDS.filter((box) => box === id || enabled.has(box)).join(",")}`;
42
+ const NOT_YET = "the bwrap box is not in this release yet: use the docker box";
43
+ const NOT_PROBED = "configured; not probed at start";
44
+ const TRANSPORT = "@parcha/pi-transport";
45
+ const unavailable = (id, reason) => ({ offer: { id, available: false, reason } });
46
+ const available = (id, provider, reason) => ({ offer: { id, available: true, ...(reason ? { reason } : {}) }, provider });
47
+ /** The boxes `env` lists in AGENTRUN_BOXES; a name that is no box throws, naming it. */
48
+ export function enabledBoxes(env) {
49
+ const names = (env[BOXES_ENV] ?? "").split(",").map((name) => name.trim()).filter(Boolean);
50
+ const unknown = names.filter((name) => !BOX_IDS.includes(name));
51
+ if (unknown.length)
52
+ 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(", ")}`);
53
+ return new Set(names);
54
+ }
55
+ /** The boxes `env` (the server's environment, its secrets readable) lists, each probed once, all at once, each within
56
+ * `timeoutMs`. Rejects only for a name that is no box: a probe that fails, throws or takes too long leaves its box
57
+ * unavailable, with a short reason that holds no key and no answer's body. */
58
+ export async function boxRegistry(env, options = {}) {
59
+ const enabled = enabledBoxes(env);
60
+ const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
61
+ const probed = await Promise.all(BOX_IDS.map((id) => {
62
+ if (id === "bwrap")
63
+ return unavailable(id, NOT_YET);
64
+ if (!enabled.has(id))
65
+ return unavailable(id, notEnabled(id, enabled));
66
+ return bounded(id, timeoutMs, (signal) => PROBES[id](env, signal));
67
+ }));
68
+ return {
69
+ offers: () => probed.map(({ offer }) => ({ ...offer })),
70
+ provider: (id) => probed.find(({ offer }) => offer.id === id && offer.available)?.provider,
71
+ };
72
+ }
73
+ /** The start's log line: the boxes available, the rest, and why each box AGENTRUN_BOXES lists (`listed`) is not available. */
74
+ export function boxesLog(offers, listed) {
75
+ const ids = (yes) => offers.filter((offer) => offer.available === yes).map((offer) => offer.id).join(",") || "none";
76
+ const why = offers.filter((offer) => !offer.available && listed.has(offer.id));
77
+ return { available: ids(true), unavailable: ids(false), ...Object.fromEntries(why.map((offer) => [offer.id, offer.reason ?? ""])) };
78
+ }
79
+ /** `probe`, aborted after `timeoutMs`. Never rejects. */
80
+ async function bounded(id, timeoutMs, probe) {
81
+ const controller = new AbortController();
82
+ let timer;
83
+ const late = new Promise((resolve) => {
84
+ timer = setTimeout(() => {
85
+ controller.abort();
86
+ resolve(unavailable(id, `its probe did not finish within ${timeoutMs} ms`));
87
+ }, timeoutMs);
88
+ });
89
+ try {
90
+ return await Promise.race([probe(controller.signal).catch((error) => unavailable(id, `its probe failed (${errorName(error)})`)), late]);
91
+ }
92
+ finally {
93
+ clearTimeout(timer);
94
+ }
95
+ }
96
+ /** What kind of error, never its message: a message can hold an answer's body, a path or a key. */
97
+ function errorName(error) {
98
+ const code = error?.code;
99
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code))
100
+ return code;
101
+ return error instanceof Error ? error.name : "not an error";
102
+ }
103
+ /** A module of package `name`, which may not be installed: then the box says to install it. */
104
+ async function load(name, importer) {
105
+ try {
106
+ return { ok: true, value: await importer() };
107
+ }
108
+ catch (error) {
109
+ const missing = error?.code === "ERR_MODULE_NOT_FOUND" && String(error.message).includes(`'${name}'`);
110
+ return { ok: false, reason: missing ? `install ${name} to use this box` : `${name} did not load (${errorName(error)})` };
111
+ }
112
+ }
113
+ const PROBES = {
114
+ /** `docker version` names the daemon's version: the CLI is on PATH and its daemon answers this user. */
115
+ async docker(env, signal) {
116
+ const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/docker").then((module) => module.dockerBoxes));
117
+ if (!boxes.ok)
118
+ return unavailable("docker", boxes.reason);
119
+ // Its environment is the server's through the cut a run's takes (withoutSecrets): no box key, no other secret, no
120
+ // name shaped like a key.
121
+ const dockerEnv = withoutSecrets(env);
122
+ const answer = await new Promise((resolve) => execFile("docker", ["version", "--format", "{{.Server.Version}}"], { env: dockerEnv, signal, maxBuffer: 64 * 1024 }, (error, stdout) => {
123
+ const code = error?.code;
124
+ resolve({ ...(error ? { failed: typeof code === "number" ? `exit ${code}` : errorName(error) } : {}), out: String(stdout) });
125
+ }));
126
+ // The probe runs once, at the start: each fix takes a restart.
127
+ if (answer.failed === "ENOENT")
128
+ return unavailable("docker", "no docker command on this server's PATH: install Docker, then restart this server");
129
+ if (answer.failed)
130
+ return unavailable("docker", `docker version failed (${answer.failed}): start Docker, or add this server's user to the docker group, then restart this server`);
131
+ if (!answer.out.trim())
132
+ return unavailable("docker", "docker version named no Docker daemon: start Docker, then restart this server");
133
+ return available("docker", boxes.value());
134
+ },
135
+ /** One authenticated read the provider makes anyway: the box with a name no box has (lowercase letters, digits and
136
+ * dashes). An answer of no such box (404) means Daytona took the key; 401 or 403 means it refused it. */
137
+ async daytona(env, signal) {
138
+ const apiKey = env[DAYTONA_KEY];
139
+ if (!apiKey)
140
+ return unavailable("daytona", `needs ${DAYTONA_KEY}`);
141
+ const apiUrl = env.DAYTONA_API_URL || undefined;
142
+ if (apiUrl !== undefined && !URL.canParse(apiUrl))
143
+ return unavailable("daytona", "DAYTONA_API_URL is not a URL");
144
+ const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/daytona").then((module) => module.daytonaBoxes));
145
+ if (!boxes.ok)
146
+ return unavailable("daytona", boxes.reason);
147
+ const provider = boxes.value({ apiKey, ...(apiUrl ? { apiUrl } : {}), ...(env.DAYTONA_TARGET ? { target: env.DAYTONA_TARGET } : {}) });
148
+ const found = await provider.attach(`agentrun-probe-${randomUUID()}`, withAbortSignal(signal, BACKGROUND_CONTEXT));
149
+ if (found.ok)
150
+ return available("daytona", provider);
151
+ if (found.error.code === "unauthorized")
152
+ return unavailable("daytona", `Daytona refused ${DAYTONA_KEY}`);
153
+ return unavailable("daytona", `Daytona did not answer the probe (${found.error.code})`);
154
+ },
155
+ /** The SDK is installed and the token is set; nothing is asked of the provider at start. The client gets the token as
156
+ * arguments: the server's environment does not hold it (secrets.ts). */
157
+ async [VM](env) {
158
+ const missing = VM_PROVIDER.keys.filter((name) => !env[name]);
159
+ if (missing.length)
160
+ return unavailable(VM, `needs ${missing.join(" and ")}`);
161
+ const boxes = await load(TRANSPORT, () => import("@parcha/pi-transport/box/modal").then((module) => module.modalBoxes));
162
+ if (!boxes.ok)
163
+ return unavailable(VM, boxes.reason);
164
+ const vmBoxes = boxes.value;
165
+ // The SDK is not a dependency of this package (the host installs it), so its name is a value here, not a literal import.
166
+ const sdk = await load(VM, () => import(VM));
167
+ if (!sdk.ok)
168
+ return unavailable(VM, sdk.reason);
169
+ const Client = sdk.value[VM_PROVIDER.client];
170
+ if (typeof Client !== "function")
171
+ return unavailable(VM, `the installed ${VM} package has no ${VM_PROVIDER.client}`);
172
+ const [tokenId, tokenSecret] = VM_PROVIDER.keys.map((name) => env[name]);
173
+ let client;
174
+ try {
175
+ client = new Client({ tokenId, tokenSecret });
176
+ }
177
+ catch (error) {
178
+ return unavailable(VM, `its SDK's client did not start (${errorName(error)})`);
179
+ }
180
+ return available(VM, vmBoxes(client, { appName: env[BOX_APP_ENV] || DEFAULT_BOX_APP }), NOT_PROBED);
181
+ },
182
+ };
package/dist/cap.d.ts ADDED
@@ -0,0 +1,224 @@
1
+ import { type EntryLike } from "@parcha/pi-durable-agent/timeline";
2
+ import type { Api, AssistantMessage, Context, Model, Models } from "@earendil-works/pi-ai";
3
+ /** A run's cap in USD, passed to its process. */
4
+ export declare const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
5
+ /** How a request the cap refused begins its error, which the server ends the run with. */
6
+ export declare const SPEND_CAP_REACHED = "spend_cap_reached";
7
+ /** The option a request's worst case rides on from the cap to its marks (request-start.ts): what the cap held for it. A
8
+ * symbol, so no provider ever sends it. */
9
+ export declare const HELD_USD: unique symbol;
10
+ /** Records that `message` ended on an error after its response began. */
11
+ export declare const markResponseBegan: (message: AssistantMessage) => void;
12
+ /** The field of a request's end mark (REQUEST_ENDED) that says what the cap held for it, when its stream ended aborted
13
+ * or its summary failed: the request counts at that figure. Optional: an end with none (an older store, a run with no
14
+ * cap) leaves the request cut, at an unknown cost. */
15
+ export declare const HELD_FIELD = "heldUsd";
16
+ /** The field of the start mark (REQUEST_STARTED) written for a request this cap refused: it never left, and pi's error
17
+ * entry for it answers this mark, never an earlier request's. */
18
+ export declare const CAP_REFUSED_FIELD = "capRefused";
19
+ /** The option a request the cap limited rides on to its start mark (request-start.ts, as `clamp`): the output tokens it was
20
+ * limited to, what was left of the cap for it, and the cap, so a reply cut short there says so. */
21
+ export declare const CLAMP: unique symbol;
22
+ /** The tokens a limited request keeps for its answer (pi-ai's MIN_ANSWER_TOKENS): a request is refused, never sent, when
23
+ * what is left of its cap cannot buy them (or what it asked for, when it asked for fewer). */
24
+ export declare const ANSWER_TOKENS_LEAST = 1024;
25
+ /** The least thinking budget Anthropic takes: a request that thinks on an API whose thinking takes a budget keeps it
26
+ * beside its answer, the budget squeezed to it at the least. */
27
+ export declare const THINKING_BUDGET_LEAST = 1024;
28
+ /** The output tokens a request the person stopped counts beyond what it streamed: what the provider may have produced after
29
+ * the last word read, before it saw the stop. A stopped request counts its input, each byte it streamed as a token, and
30
+ * these, never more than it was held at (stoppedFigure). A stated bound, as NATIVE_SEARCH_ALLOWANCE_TOKENS is. */
31
+ export declare const STOP_ALLOWANCE_TOKENS = 1024;
32
+ /** The option a request's stopped figure rides on to its end mark (request-start.ts): what it counts at, given the answer
33
+ * it streamed, when it is stopped before its end. A symbol, so no provider ever sends it. */
34
+ export declare const STOPPED_USD: unique symbol;
35
+ /** What a model answer streamed, in bytes: its text, its thinking, and each tool call's name and arguments as JSON. Each
36
+ * byte counts as a token (a byte-level tokenizer never makes a token of less than one byte), as inputBound counts input. */
37
+ export declare function streamedBytes(message: {
38
+ content?: unknown;
39
+ } | undefined): number;
40
+ /** A request's figure if it is stopped before its end, given the answer it had streamed. */
41
+ export type Stopped = (message: {
42
+ content?: unknown;
43
+ }) => number;
44
+ /** What a request stopped before its end counts at: its input and `streamed` tokens plus STOP_ALLOWANCE_TOKENS of output,
45
+ * at most the output it was sent with (`limit`), at `cost`'s price; never more than `worst`, what it was held at. */
46
+ export declare const stoppedFigure: (cost: (output: number) => number, limit: number, worst: number, streamed: number) => number;
47
+ /** How pi's error for a request whose start mark could not be written begins (request-start.ts builds it from this): the
48
+ * request never left, so the entry answers none, and spentIn leaves it out by this. */
49
+ export declare const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
50
+ /** The input a request carrying claude-agent's native web search may read in beyond its body, added to its input bound
51
+ * by its adapter (adapters.ts hands it over): Claude's CLI asks for at most 8 searches a request (max_uses 8), and each
52
+ * search's results are billed as input, about 25,000 tokens a search as a working estimate. */
53
+ export declare const NATIVE_SEARCH_ALLOWANCE_TOKENS: number;
54
+ /** A tool's own request through the run's models (`completeSimple`), by its context: the label its marks carry, the
55
+ * input its hosted tool may add beyond its context (results billed as input) and the most fee it can run up, which the
56
+ * cap holds (cap.ts), and the fee its tokens do not show (its searches), read once it ended. */
57
+ export type SideRequest = {
58
+ label: string;
59
+ extraInputTokens: number;
60
+ maxFeeUsd: number;
61
+ feeUsd(): number;
62
+ };
63
+ export declare const sideRequests: WeakMap<object, SideRequest>;
64
+ /** The run's cap from its process's environment; absent for a run without one. */
65
+ export declare function capOf(env: NodeJS.ProcessEnv): number | undefined;
66
+ /** The code a cap's refusal begins with: `spend_cap_reached: `, or with a note after it, as a request it limited refuses
67
+ * in (CAP_REFUSAL_CODE, "spend_cap_reached (out of budget): "). Every reader of a refusal's text (a run's end, its
68
+ * learning, the spend read back) reads the code through this, never a bare prefix. */
69
+ export declare const CAP_REFUSAL_PREFIX: RegExp;
70
+ /** What the run's store says its model requests cost, across every conversation in it: known or not as the run's own
71
+ * timeline says (pi-durable-agent's timelineOf), read as a settled run, since the process that wrote it is gone, and
72
+ * then the full amount, never the timeline's total rounded for display. Every response, and each cost written apart
73
+ * from one (a compaction summary's; a harness request's that came in after its answer). A cost that is not a number, or
74
+ * one still pending, leaves it unknown, as the timeline says. These readings are the cap's own, on its copy of the
75
+ * entries (the run's shown cost is the timeline's, unchanged): a request stopped before its end counts at the figure its
76
+ * end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the figure its start mark
77
+ * holds (openFigures), each the worst case the cap held for it; without that figure either stays cut, at an unknown
78
+ * cost. A paid call settled at a charge it did not say, like one a crash cut, counts at the figure its mark holds. And
79
+ * this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. */
80
+ export declare function spentIn(storeFile: string): number | null;
81
+ /** /usage's meters for a run that ended, from its store: `tools`, each TOOL_COST's `usd`, unknown (null) when one is,
82
+ * or when a call was cut (marked, never settled: what it charged no one knows); and `tokens`, the rest of its root
83
+ * conversation as its settled timeline prices it. A mark is never a charge here (the cap's alone). Never for a live
84
+ * run: its process holds the store exclusively. */
85
+ export declare function metersIn(storeFile: string): {
86
+ tools: number | null;
87
+ tokens: number | null;
88
+ };
89
+ /** What the paid tools of `entries` (TOOL_STARTED and TOOL_COST) spent, as the cap counts it: each charge, and a call
90
+ * settled at a charge it did not say, or a crash cut (marked, never settled), at its held figure, as spentIn counts it;
91
+ * null when one has no figure. The run's reported cost reads such a call unknown instead (the timeline). */
92
+ export declare function capToolSpend(entries: readonly EntryLike[]): number | null;
93
+ /** The worst case of each model request a cap admitted and whose cost is not booked yet, by its turn, for a paid tool's
94
+ * check on a harness whose booking counts a request only once its cost is in (harness-app.ts): `admitted` takes what
95
+ * the guard held, `started` gives it the turn that request leaves as (admissions run one at a time), `ended` drops it. */
96
+ export declare function holdsInFlight(): {
97
+ admitted: (usd: number | undefined) => undefined;
98
+ started: (turn: number) => undefined;
99
+ ended: (turn: number) => undefined;
100
+ total: () => number;
101
+ };
102
+ /** The run's spend as its process counts it, for a paid tool: what it has spent (`spent`, model requests in flight held
103
+ * at their worst case; null when unknown) and the charge a call adds (`add`). Set by the run's cap, on pi (capModels)
104
+ * and on another harness (harness-app.ts); none without a cap. A run is one process, so one is set per process. */
105
+ export type RunSpend = {
106
+ cap: number;
107
+ spent(): number | null | Promise<number | null>;
108
+ add(usd: number | null): void;
109
+ };
110
+ export declare const useSpend: (spend: RunSpend | undefined) => void;
111
+ /** What the paid calls under way are held at, together (0 when none is): the one figure every check of the run's cap
112
+ * adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). */
113
+ export declare const paidHolds: () => number;
114
+ /** `call`, a paid tool's (`name`), under the run's cap, by the rule a model request keeps: refused, in words that name
115
+ * its price and the cap and never calling it, unless what the run has spent plus what the call is held at (`hold`: its
116
+ * quote, else an allowance, `basis` saying which) fits the cap, and whenever the spend is unknown; else run, one paid
117
+ * call at a time, so each check sees the charge before it, and held at that figure (paidHolds) until the charge it
118
+ * reports (`charge` of its result, undefined for none) joins the spend. A charge it does not say (null), or a call that
119
+ * fails, counts at its held figure, as its mark does from the store (spentIn), since it may have charged that much.
120
+ * With no cap it just runs. */
121
+ export declare function paidCall<T>(name: string, call: () => Promise<T>, charge: (result: T) => number | null | undefined, hold: {
122
+ usd: number;
123
+ basis: string;
124
+ }): Promise<{
125
+ refused: string;
126
+ } | {
127
+ result: T;
128
+ }>;
129
+ /** The most output tokens one request may take: the model's ceiling, else its context window. A thinking budget can
130
+ * raise a request's ceiling up to the model's, whatever maxTokens it asked for. */
131
+ export declare const ceilingTokens: (model: Pick<Model<Api>, "maxTokens" | "contextWindow">) => number;
132
+ /** A request's input tokens, bounded above: one per UTF-8 byte of what is sent (a byte-level tokenizer never takes
133
+ * fewer than one byte a token, and an image's base64 is far more bytes than its tokens), plus `overhead`, what the
134
+ * provider adds server-side that the body does not hold. The same bound on every harness. */
135
+ export declare const inputBound: (sent: string, overhead?: number) => number;
136
+ /** What pi's provider adds server-side to a request of `context`, the same table the model proxy uses, by the model's API
137
+ * kind: undefined for a kind whose additions are not known. The context does not say how the request chooses a tool,
138
+ * so the dearer choice is taken. */
139
+ export declare function piOverhead(model: Pick<Model<Api>, "api">, context: Context): number | undefined;
140
+ /** An amount in words: two decimals, or as many as it takes (up to eight) to show it whole ($0.50, $0.105, $0.0005). */
141
+ export declare function money(usd: number): string;
142
+ /** The code a cap's refusal begins with: `spend_cap_reached`, which the server ends the run with, and "out of budget",
143
+ * which pi-ai's retry (isRetryableAssistantError, which reads only an error's text) takes as final whatever digits the
144
+ * words after it hold. The words after it are the ones a person reads. */
145
+ export declare const CAP_REFUSAL_CODE = "spend_cap_reached (out of budget): ";
146
+ /** A model's name as the words say it: the catalog's, without a vendor's prefix ("Anthropic: Claude Sonnet 5.5" reads
147
+ * "Claude Sonnet 5.5"), else its id. */
148
+ export declare const nameOf: (model: Pick<Model<Api>, "name" | "id">) => string;
149
+ /** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
150
+ export declare const leastMoney: (usd: number) => string;
151
+ /** The least output a pi request may be limited to and still answer: the answer's 1,024 tokens, and when it thinks,
152
+ * the least budget on an API whose thinking takes one (squeezed to it), else its thinking level's budget, since its
153
+ * reasoning then shares the limit. */
154
+ export declare function leastOutput(model: Pick<Model<Api>, "api" | "reasoning">, thinking: string | undefined, budgetOf: (level: string) => number): number;
155
+ /** The cap of a run on another harness, before each of its requests: the runner's booking says what the run has spent
156
+ * (its session, across processes) and which of its requests are still in flight, each with the output limit it was
157
+ * admitted with, and the model proxy each request's input bound (`inputTokensMax`, inputBound of its body; undefined
158
+ * when the body could not be measured), the output it asks for, and the least it may be limited to. */
159
+ export interface CapGuard {
160
+ beforeRequest(request: GuardRequest): undefined | {
161
+ refuse: string;
162
+ } | {
163
+ outputTokensMax: number;
164
+ };
165
+ /** The worst case a request this guard admitted is held at (its input bound, and the output limit it was admitted with
166
+ * or else its output ceiling, at the model's price): what the runner records for it, and counts it at when its own cost
167
+ * never comes in (cut short, or by a crash). */
168
+ worstOf?(request: {
169
+ inputTokensMax?: number;
170
+ outputTokensMax?: number;
171
+ }): number | undefined;
172
+ /** What a request this guard admitted counts at if its client stops it part way, having streamed `streamed` tokens (one
173
+ * a byte): its input bound and those tokens plus STOP_ALLOWANCE_TOKENS of output, at most its output limit, at the
174
+ * model's price. The runner counts it at no more than its hold. Undefined when its input was not measured. */
175
+ stoppedOf?(request: {
176
+ inputTokensMax?: number;
177
+ outputTokensMax?: number;
178
+ }, streamed: number): number | undefined;
179
+ }
180
+ export type GuardRequest = {
181
+ spentUsd: number | null;
182
+ inFlight: readonly {
183
+ inputTokensMax?: number;
184
+ outputTokensMax?: number;
185
+ }[];
186
+ inputTokensMax?: number;
187
+ outputTokensAsked?: number;
188
+ outputTokensLeast?: number;
189
+ };
190
+ /** A run on another harness: before each request, what the run has spent, plus the worst case of each request still in
191
+ * flight (at the output limit it was admitted with), must leave room for this request at its least output (1,024 tokens,
192
+ * or what its body says it needs to think and answer; what it asks for when that is fewer), else the request is refused
193
+ * with spend_cap_reached. Admitted, it is limited to the most output what is left buys (`outputTokensMax`, at most what
194
+ * it asks for and its model's ceiling), which the model proxy writes into its body: what it is held at is then what the
195
+ * provider can bill for it. A request's worst case is at the run model's
196
+ * price, as on pi (a request on a cheaper model is held at that price too, which only refuses sooner). What cannot be
197
+ * kept within a cap is refused under one: a spend that is unknown (a request a crash cut), an input that could not be
198
+ * measured, a model serve has no price for (`listed: false`, or none at all), and a model whose output is priced and
199
+ * that has no output ceiling. With no cap, nothing is refused. */
200
+ export declare function capBefore(cap: number | undefined, model: Model<Api> | undefined, { listed }?: {
201
+ listed?: boolean;
202
+ }): Promise<CapGuard | undefined>;
203
+ /** A request's input bound (inputBound of its context, plus `overhead(model, context)`, what its provider adds
204
+ * server-side) and the most fee it can run up: a tool's own request adds what its hosted tool may read
205
+ * (hosted-search.ts), and its most fee. Undefined when its input cannot be measured. */
206
+ export declare function requestParts(overhead?: (model: Model<Api>, context: Context) => number | undefined): (model: Model<Api>, context: Context) => {
207
+ input: number;
208
+ feeUsd: number;
209
+ } | undefined;
210
+ /** `models`, each request limited to the output tokens what is left of `cap` after `spent` USD (and what requests in flight
211
+ * hold) can buy, at most what it asks for, thinking included (CLAMP on its marks when that is less), and refused when that
212
+ * cannot buy its least (`leastOutput`: 1,024 tokens for the answer, and its thinking's least), saying so in plain words;
213
+ * and, under the cap,
214
+ * each request to a model in `unpriced` (one serve has no price for) or whose output is priced and that has no output
215
+ * ceiling, each whose input cannot be bounded, and every request once what the run has spent is unknown: `spent` null
216
+ * (spentIn), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
217
+ * `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. Each
218
+ * request sent carries its worst case (HELD_USD) to the marks below, and one stopped before its end counts at it.
219
+ * `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry. */
220
+ export declare function capModels<M extends Models>(models: M, cap: number, spent: number | null, { unpriced, overhead, refused: markRefused }?: {
221
+ unpriced?: ReadonlySet<string>;
222
+ overhead?: (model: Model<Api>, context: Context) => number | undefined;
223
+ refused?: () => Promise<void>;
224
+ }): Promise<M>;