@parcha/agentrun-serve 0.1.0-beta.46 → 0.1.0-beta.48

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 (292) hide show
  1. package/CHANGELOG.md +211 -1
  2. package/NOTICE +4 -0
  3. package/README.md +350 -53
  4. package/dist/acp-package.d.ts +53 -6
  5. package/dist/acp-package.js +3 -3
  6. package/dist/adapter-facts.d.ts +3 -4
  7. package/dist/adapter-facts.js +4 -4
  8. package/dist/adapters.d.ts +3 -5
  9. package/dist/adapters.js +1 -31
  10. package/dist/agents-store.d.ts +5 -3
  11. package/dist/agents-store.js +13 -8
  12. package/dist/answer-json.d.ts +10 -0
  13. package/dist/answer-json.js +24 -0
  14. package/dist/api-only.d.ts +11 -11
  15. package/dist/api-only.js +16 -11
  16. package/dist/archil-routes.js +2 -1
  17. package/dist/browser-live.d.ts +9 -4
  18. package/dist/browser-live.js +18 -5
  19. package/dist/cap.js +10 -2
  20. package/dist/chatgpt-plan.js +2 -1
  21. package/dist/cli.js +109 -41
  22. package/dist/composio-made.d.ts +19 -2
  23. package/dist/composio-made.js +17 -5
  24. package/dist/composio-preset.d.ts +42 -7
  25. package/dist/composio-preset.js +106 -70
  26. package/dist/composio-triggers.d.ts +9 -4
  27. package/dist/composio-triggers.js +20 -13
  28. package/dist/computer-attach.d.ts +11 -10
  29. package/dist/computer-attach.js +13 -14
  30. package/dist/computer-commands.d.ts +3 -0
  31. package/dist/computer-commands.js +3 -2
  32. package/dist/computer-lost.d.ts +4 -0
  33. package/dist/computer-lost.js +8 -3
  34. package/dist/computer-routes.d.ts +8 -5
  35. package/dist/computer-routes.js +7 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +2 -0
  38. package/dist/computers.d.ts +14 -76
  39. package/dist/computers.js +24 -68
  40. package/dist/conformance.d.ts +4 -0
  41. package/dist/conformance.js +6 -0
  42. package/dist/console/assets/index-CTGegcKt.css +1 -0
  43. package/dist/console/assets/index-D1Se6mgG.js +715 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/cost-heal.d.ts +13 -0
  46. package/dist/cost-heal.js +27 -0
  47. package/dist/dial-relay.d.ts +6 -2
  48. package/dist/dial-relay.js +9 -12
  49. package/dist/email/routes.js +2 -1
  50. package/dist/errors.d.ts +2 -0
  51. package/dist/errors.js +5 -0
  52. package/dist/exa-keyless.d.ts +1 -1
  53. package/dist/exa-keyless.js +1 -1
  54. package/dist/faux-computers.d.ts +2 -3
  55. package/dist/faux-computers.js +9 -31
  56. package/dist/github-connection.js +2 -1
  57. package/dist/harness-archive.d.ts +19 -2
  58. package/dist/harness-archive.js +49 -15
  59. package/dist/harness-check.d.ts +75 -0
  60. package/dist/harness-check.js +518 -0
  61. package/dist/harness-cursor.d.ts +28 -0
  62. package/dist/harness-cursor.js +42 -0
  63. package/dist/harness-goose.d.ts +4 -29
  64. package/dist/harness-goose.js +6 -86
  65. package/dist/harness-module.d.ts +4 -0
  66. package/dist/harness-module.js +1 -0
  67. package/dist/harness-owned.d.ts +52 -0
  68. package/dist/harness-owned.js +92 -0
  69. package/dist/harness-recipe.d.ts +127 -0
  70. package/dist/harness-recipe.js +335 -0
  71. package/dist/harness-table.d.ts +120 -5
  72. package/dist/harness-table.js +280 -6
  73. package/dist/harness.d.ts +2 -0
  74. package/dist/harness.js +5 -4
  75. package/dist/host-check.d.ts +6 -0
  76. package/dist/host-check.js +14 -0
  77. package/dist/host.d.ts +10 -3
  78. package/dist/host.js +17 -3
  79. package/dist/import-sources.d.ts +2 -0
  80. package/dist/import-sources.js +2 -0
  81. package/dist/import-summary.d.ts +15 -5
  82. package/dist/import-summary.js +24 -8
  83. package/dist/import.d.ts +24 -4
  84. package/dist/import.js +108 -26
  85. package/dist/key-refusal.d.ts +3 -1
  86. package/dist/key-refusal.js +26 -5
  87. package/dist/key-words.d.ts +1 -1
  88. package/dist/key-words.js +4 -4
  89. package/dist/learn/check.d.ts +3 -0
  90. package/dist/learn/check.js +31 -20
  91. package/dist/learn/compile.js +12 -5
  92. package/dist/learn/promote.d.ts +80 -2
  93. package/dist/learn/promote.js +95 -3
  94. package/dist/learn/secrets.d.ts +4 -0
  95. package/dist/learn/secrets.js +23 -0
  96. package/dist/learned-nodes.d.ts +4 -3
  97. package/dist/learned-workflow.js +4 -1
  98. package/dist/learning-cost.d.ts +6 -16
  99. package/dist/learning-cost.js +6 -12
  100. package/dist/learning-model.d.ts +18 -0
  101. package/dist/learning-model.js +77 -0
  102. package/dist/learning-words.d.ts +2 -0
  103. package/dist/learning-words.js +1 -1
  104. package/dist/listen-first.d.ts +10 -0
  105. package/dist/listen-first.js +25 -1
  106. package/dist/llms.txt +2 -1
  107. package/dist/mcp-gateway.d.ts +2 -1
  108. package/dist/mcp-gateway.js +31 -15
  109. package/dist/mcp-probe.d.ts +18 -6
  110. package/dist/mcp-probe.js +41 -8
  111. package/dist/mcp-secret-writes.d.ts +8 -0
  112. package/dist/mcp-secret-writes.js +104 -4
  113. package/dist/mcp-servers-store.d.ts +11 -5
  114. package/dist/mcp-servers-store.js +46 -20
  115. package/dist/model-form.d.ts +2 -1
  116. package/dist/model-form.js +30 -16
  117. package/dist/model-gateway.d.ts +113 -0
  118. package/dist/model-gateway.js +433 -0
  119. package/dist/model.d.ts +5 -3
  120. package/dist/model.js +26 -18
  121. package/dist/monid.js +1 -1
  122. package/dist/native/binding.d.ts +4 -0
  123. package/dist/native/binding.js +9 -0
  124. package/dist/native/cli.d.ts +3 -2
  125. package/dist/native/cli.js +6 -5
  126. package/dist/openapi.d.ts +2 -0
  127. package/dist/openapi.js +356 -43
  128. package/dist/owner.d.ts +4 -2
  129. package/dist/owner.js +10 -4
  130. package/dist/page.d.ts +9 -0
  131. package/dist/page.js +10 -2
  132. package/dist/port-models.js +17 -10
  133. package/dist/provider.d.ts +3 -3
  134. package/dist/provider.js +12 -3
  135. package/dist/public-address.d.ts +28 -0
  136. package/dist/public-address.js +62 -0
  137. package/dist/run-launch.d.ts +1 -1
  138. package/dist/run-launch.js +1 -1
  139. package/dist/run-secrets.d.ts +3 -2
  140. package/dist/run-secrets.js +7 -4
  141. package/dist/run-trace.js +6 -3
  142. package/dist/runner/adapter-loop.d.ts +14 -8
  143. package/dist/runner/adapter-loop.js +58 -24
  144. package/dist/runner/adapter-run-spec.d.ts +15 -2
  145. package/dist/runner/adapter-run-spec.js +48 -10
  146. package/dist/runner/adapters/index.d.ts +4 -2
  147. package/dist/runner/adapters/index.js +6 -26
  148. package/dist/runner/adapters/pi.d.ts +5 -2
  149. package/dist/runner/adapters/pi.js +7 -4
  150. package/dist/runner/audit.d.ts +7 -0
  151. package/dist/runner/audit.js +15 -6
  152. package/dist/runner/claim-secrets.js +5 -1
  153. package/dist/runner/cli-run-spec.js +22 -10
  154. package/dist/runner/compare-end.d.ts +43 -0
  155. package/dist/runner/compare-end.js +95 -0
  156. package/dist/runner/computer-journal.d.ts +3 -0
  157. package/dist/runner/computer-journal.js +22 -2
  158. package/dist/runner/conformance/host-tools.d.ts +4 -0
  159. package/dist/runner/conformance/host-tools.js +14 -0
  160. package/dist/runner/harness-loops.d.ts +6 -1
  161. package/dist/runner/harness-loops.js +94 -54
  162. package/dist/runner/held.d.ts +5 -4
  163. package/dist/runner/journal-kinds.d.ts +4 -1
  164. package/dist/runner/journal-kinds.js +3 -0
  165. package/dist/runner/loop-contract.d.ts +10 -0
  166. package/dist/runner/main.d.ts +5 -5
  167. package/dist/runner/main.js +62 -11
  168. package/dist/runner/mcp-claim.js +40 -12
  169. package/dist/runner/meta-tools.js +4 -2
  170. package/dist/runner/metrics.d.ts +26 -0
  171. package/dist/runner/metrics.js +44 -1
  172. package/dist/runner/presence.d.ts +44 -0
  173. package/dist/runner/presence.js +96 -0
  174. package/dist/runner/promotion.d.ts +70 -7
  175. package/dist/runner/promotion.js +178 -28
  176. package/dist/runner/run-child-host.js +40 -10
  177. package/dist/runner/runner.d.ts +5 -0
  178. package/dist/runner/runner.js +8 -0
  179. package/dist/runner/sdk-loop.js +25 -1
  180. package/dist/runner/store-port.d.ts +3 -0
  181. package/dist/runner/store-secrets.js +19 -7
  182. package/dist/runner/workflow-first.d.ts +5 -2
  183. package/dist/runner/workflow-first.js +6 -3
  184. package/dist/runner/workflow-spec.js +3 -2
  185. package/dist/runs-over-store.d.ts +7 -2
  186. package/dist/runs-over-store.js +12 -4
  187. package/dist/sdk/check.d.ts +31 -0
  188. package/dist/sdk/check.js +58 -0
  189. package/dist/sdk/runs.d.ts +11 -3
  190. package/dist/sdk/runs.js +90 -15
  191. package/dist/sdk/schema.js +12 -4
  192. package/dist/secret-writes.d.ts +16 -3
  193. package/dist/secret-writes.js +28 -3
  194. package/dist/server-secrets-store.js +5 -0
  195. package/dist/server.d.ts +34 -2
  196. package/dist/server.js +437 -90
  197. package/dist/sign-ins-secrets.js +4 -1
  198. package/dist/skills/agentrun-serve/SKILL.md +11 -0
  199. package/dist/slack-url.d.ts +5 -0
  200. package/dist/slack-url.js +11 -0
  201. package/dist/slack.d.ts +107 -0
  202. package/dist/slack.js +292 -0
  203. package/dist/start-switches.d.ts +28 -0
  204. package/dist/start-switches.js +37 -0
  205. package/dist/stats.d.ts +1 -1
  206. package/dist/stats.js +2 -1
  207. package/dist/stop-signals.d.ts +11 -0
  208. package/dist/stop-signals.js +22 -0
  209. package/dist/store/agent-body.d.ts +1 -1
  210. package/dist/store/agent-body.js +2 -2
  211. package/dist/store/index.d.ts +3 -3
  212. package/dist/store/index.js +1 -1
  213. package/dist/store/postgres/migrations/0020_runners.sql +18 -0
  214. package/dist/store/postgres/store.d.ts +1 -1
  215. package/dist/store/postgres/store.js +4 -2
  216. package/dist/store/schema.d.ts +13 -5
  217. package/dist/store/schema.js +20 -11
  218. package/dist/store/seal.d.ts +16 -4
  219. package/dist/store/sqlite/store.d.ts +1 -1
  220. package/dist/store/sqlite/store.js +112 -28
  221. package/dist/store/store.d.ts +78 -24
  222. package/dist/store/store.js +11 -0
  223. package/dist/store-reads/analytics.js +3 -2
  224. package/dist/store-reads/cap.d.ts +7 -0
  225. package/dist/store-reads/cap.js +11 -1
  226. package/dist/store-reads/journal.js +27 -1
  227. package/dist/store-reads/learning.d.ts +23 -2
  228. package/dist/store-reads/learning.js +29 -8
  229. package/dist/store-reads/runs.d.ts +9 -0
  230. package/dist/store-reads/runs.js +19 -6
  231. package/dist/store-reads/stats.d.ts +4 -1
  232. package/dist/store-reads/stats.js +15 -6
  233. package/dist/store-view.d.ts +125 -14
  234. package/dist/store-view.js +156 -21
  235. package/dist/telemetry.d.ts +7 -7
  236. package/dist/telemetry.js +38 -15
  237. package/dist/template-eval.js +5 -2
  238. package/dist/template-github-permissions.d.ts +5 -1
  239. package/dist/template-github-permissions.js +7 -3
  240. package/dist/timeline/index.d.ts +1 -1
  241. package/dist/timeline/index.js +1 -1
  242. package/dist/timeline/timeline.d.ts +8 -0
  243. package/dist/timeline/timeline.js +30 -0
  244. package/dist/tool-gate.d.ts +8 -4
  245. package/dist/tool-gate.js +6 -7
  246. package/dist/tool-keys-store.js +2 -2
  247. package/dist/tool-keys.js +2 -1
  248. package/dist/tool-plane.d.ts +4 -0
  249. package/dist/tool-plane.js +12 -12
  250. package/dist/trigger-adapter.d.ts +3 -4
  251. package/dist/trigger-adapter.js +2 -2
  252. package/dist/trigger-composio.js +3 -3
  253. package/dist/trigger-email.js +0 -2
  254. package/dist/trigger-feed.js +0 -2
  255. package/dist/trigger-schedule.js +3 -0
  256. package/dist/trigger-secrets-shown.d.ts +6 -3
  257. package/dist/trigger-secrets-shown.js +22 -13
  258. package/dist/trigger-targets.d.ts +12 -3
  259. package/dist/trigger-targets.js +90 -10
  260. package/dist/triggers.d.ts +2 -2
  261. package/dist/validate.js +5 -1
  262. package/dist/viewer-credential.d.ts +25 -0
  263. package/dist/viewer-credential.js +51 -0
  264. package/dist/webhooks.d.ts +82 -8
  265. package/dist/webhooks.js +128 -45
  266. package/dist/wires.d.ts +6 -1
  267. package/dist/wires.js +5 -0
  268. package/dist/workspace/attach.d.ts +3 -2
  269. package/dist/workspace/attach.js +2 -1
  270. package/dist/workspace/attached-computers.d.ts +6 -8
  271. package/dist/workspace/attached-computers.js +27 -24
  272. package/dist/workspace/computer-deps.d.ts +2 -3
  273. package/dist/workspace/computer-deps.js +3 -6
  274. package/dist/workspace/computer-for-claim.js +72 -96
  275. package/dist/workspace/computer-kept.d.ts +0 -7
  276. package/dist/workspace/computer-kept.js +0 -17
  277. package/dist/workspace/resolve-computer.d.ts +23 -14
  278. package/dist/workspace/resolve-computer.js +66 -61
  279. package/dist/workspace/synced-folder.d.ts +20 -15
  280. package/dist/workspace/synced-folder.js +33 -43
  281. package/launcher/agentrun-serve +4 -1
  282. package/package.json +18 -10
  283. package/skills/agentrun-serve/SKILL.md +11 -0
  284. package/templates/README.md +1 -1
  285. package/templates/code-review/agent.md +2 -3
  286. package/templates/code-review/evals/mentions-defused/case.yaml +0 -1
  287. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -27
  288. package/templates/code-review/evals/other-repo/case.yaml +0 -1
  289. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +0 -18
  290. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +1 -1
  291. package/dist/console/assets/index-C2MYaUBa.css +0 -1
  292. package/dist/console/assets/index-CZZeCReB.js +0 -701
@@ -0,0 +1,518 @@
1
+ // `agentrun harness-check --recipe FILE`: a recipe's agent run for real, the way serve would run it, and judged. It loads
2
+ // the recipe (harness-recipe.ts: the five rules, each refused by its code), finds the binary its owner installed and
3
+ // checks its pin, then drives the ACP adapter over four turns of a live session on the run's model, and writes what it
4
+ // saw as a JSON report:
5
+ // Stage 2, the real binary: its tools are off (the first model request offers only ours), its environment is the
6
+ // allowlist (read from /proc on Linux), its pin holds at every start, its billing limits hold (proxy: a request past
7
+ // the cap is refused unsent; plan: the adapter's turn and call limits are set), and it makes no side request (the
8
+ // provider sees only the turns' Messages requests; anything it reaches for beyond loopback goes to the check's own
9
+ // proxy, which refuses and lists it).
10
+ // Stage 3, live: the agent is killed (SIGKILL) after a turn and the next turn resumes it (its own session/load, or a
11
+ // fresh session told the conversation), a denied call never runs, one of our tools runs over MCP, and another runner
12
+ // with its own directory picks the session up from the records.
13
+ // It prints the three facts a harness row carries: resume (load | restart), tool_gate (permission | config: whether the
14
+ // agent asks before a tool call) and billing (proxy | plan).
15
+ // The check spends: four short turns on the run's model, under a cap (default $0.25).
16
+ import { spawnSync } from "node:child_process";
17
+ import { randomBytes } from "node:crypto";
18
+ import { existsSync, readFileSync } from "node:fs";
19
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
20
+ import { createServer } from "node:http";
21
+ import { connect as netConnect } from "node:net";
22
+ import { tmpdir } from "node:os";
23
+ import { join } from "node:path";
24
+ import { modelPortFor, SessionFenced } from "@parcha/agentrun-kernel";
25
+ import { beforeRequestOf } from "@parcha/agentrun-kernel/kernel/cap";
26
+ import { ACP_PACKAGE, acpPackage } from "./acp-package.js";
27
+ import { ARCHIVE_CODES, archivePlatform, digestOf } from "./harness-archive.js";
28
+ import { installDirOf } from "./harness-install.js";
29
+ import { AGENT_VARS, loadRecipe, pinnedDigest, recipeBinaryOf, recipeInstallLine, RecipeRefused, releaseFor } from "./harness-recipe.js";
30
+ import { acpEntryOf } from "./harness-table.js";
31
+ import { providerModels } from "./model.js";
32
+ import { capModelOf } from "./runner/cli-run-spec.js";
33
+ import { keyShaped } from "./secret-name.js";
34
+ import { secretRedactor } from "./runner/redact.js";
35
+ import { hostSecrets, SECRET_NAMES } from "./secrets.js";
36
+ /** The proxy variables the check points at its own egress proxy, in both cases, whatever the recipe sets. */
37
+ const EGRESS_VARS = ["HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy"];
38
+ const NO_PROXY_VARS = ["NO_PROXY", "no_proxy"];
39
+ /** What a shell sets for itself when the binary is a script (its working directory, its depth): never the host's. */
40
+ const SHELL_OWN = ["PWD", "OLDPWD", "SHLVL", "_"];
41
+ export const CHECK_DEFAULT_CAP_USD = 0.25;
42
+ const TURN_MS = 240_000;
43
+ /** The check's session records, in memory for the check's life: one session, opened by each runner in turn. The newest
44
+ * open holds it; an older writer's append is fenced, as the server's store fences a runner whose claim was taken. */
45
+ function checkStore() {
46
+ const records = new Map();
47
+ const holders = new Map();
48
+ const read = async (key) => structuredClone(records.get(key) ?? []);
49
+ return {
50
+ read,
51
+ async open(key) {
52
+ const holder = (holders.get(key) ?? 0) + 1;
53
+ holders.set(key, holder);
54
+ return {
55
+ key,
56
+ read: () => read(key),
57
+ async append(added) {
58
+ if (holders.get(key) !== holder)
59
+ throw new SessionFenced(key);
60
+ records.set(key, [...(records.get(key) ?? []), ...structuredClone(added)]);
61
+ },
62
+ sync: async () => { },
63
+ };
64
+ },
65
+ };
66
+ }
67
+ const LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule the one address the refusing egress proxy of a check listens on
68
+ /** A loopback HTTP proxy that records what the agent reaches for beyond loopback. It tunnels a CONNECT to one of `vendor`
69
+ * (a plan-billed recipe's model.hosts, `host` for port 443 or `host:port`) and refuses everything else. */
70
+ async function egressProxy(vendor = []) {
71
+ const asked = [];
72
+ const sockets = new Set();
73
+ const allowed = new Set(vendor.map((host) => (host.includes(":") ? host : `${host}:443`)));
74
+ const server = createServer((req, res) => {
75
+ asked.push({ method: req.method ?? "GET", target: req.url ?? "", tunneled: false });
76
+ res.writeHead(403).end();
77
+ });
78
+ server.on("connect", (req, socket, head) => {
79
+ const target = req.url ?? "";
80
+ const tunneled = allowed.has(target);
81
+ asked.push({ method: "CONNECT", target, tunneled });
82
+ if (!tunneled)
83
+ return void socket.end("HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n");
84
+ const at = target.lastIndexOf(":");
85
+ const upstream = netConnect({ host: target.slice(0, at), port: Number(target.slice(at + 1)) }, () => {
86
+ socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
87
+ if (head.length)
88
+ upstream.write(head);
89
+ upstream.pipe(socket);
90
+ socket.pipe(upstream);
91
+ });
92
+ sockets.add(upstream);
93
+ upstream.on("close", () => (sockets.delete(upstream), socket.destroy()));
94
+ upstream.on("error", () => socket.end("HTTP/1.1 502 Bad Gateway\r\ncontent-length: 0\r\n\r\n"));
95
+ socket.on("error", () => upstream.destroy());
96
+ socket.on("close", () => upstream.destroy());
97
+ });
98
+ server.on("connection", (socket) => (sockets.add(socket), socket.on("close", () => sockets.delete(socket))));
99
+ await new Promise((resolve) => server.listen(0, LOOPBACK, resolve));
100
+ const port = server.address().port;
101
+ return {
102
+ url: `http://${LOOPBACK}:${port}`,
103
+ asked,
104
+ close: () => new Promise((resolve) => {
105
+ for (const socket of sockets)
106
+ socket.destroy();
107
+ server.close(() => resolve());
108
+ }),
109
+ };
110
+ }
111
+ /** A process's environment, by name, from /proc (Linux); undefined elsewhere or once it is gone. */
112
+ function environOf(pid) {
113
+ try {
114
+ return Object.fromEntries(readFileSync(`/proc/${pid}/environ`, "utf8").split("\0").filter(Boolean).map((kv) => [kv.slice(0, kv.indexOf("=")), kv.slice(kv.indexOf("=") + 1)]));
115
+ }
116
+ catch {
117
+ return undefined;
118
+ }
119
+ }
120
+ const alive = (pid) => {
121
+ try {
122
+ process.kill(pid, 0);
123
+ return true;
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ };
129
+ /** Kills the agent's process by its pid, once it is this process's own child running the recipe's binary (or what the
130
+ * binary exec'd, a script's interpreter): never another process. */
131
+ async function killAgent(pid, binary) {
132
+ let cmdline = "";
133
+ let parent;
134
+ try {
135
+ cmdline = readFileSync(`/proc/${pid}/cmdline`, "utf8");
136
+ parent = Number(readFileSync(`/proc/${pid}/stat`, "utf8").replace(/^.*\) /s, "").split(" ")[1]);
137
+ }
138
+ catch {
139
+ // Not Linux: ps says the command and the parent.
140
+ const ps = spawnSync("ps", ["-o", "ppid=,command=", "-p", String(pid)], { encoding: "utf8" }).stdout?.trim() ?? "";
141
+ parent = Number(ps.split(/\s+/)[0]);
142
+ cmdline = ps.slice(ps.indexOf(" ") + 1);
143
+ }
144
+ if (!cmdline || (parent !== process.pid && !cmdline.includes(binary)))
145
+ return false;
146
+ process.kill(pid, "SIGKILL");
147
+ for (let i = 0; i < 100 && alive(pid); i++)
148
+ await new Promise((resolve) => setTimeout(resolve, 50));
149
+ return !alive(pid);
150
+ }
151
+ /** The text of a request body, whatever the proxy sent it as. */
152
+ function bodyText(body) {
153
+ if (typeof body === "string")
154
+ return body;
155
+ if (body instanceof Uint8Array)
156
+ return Buffer.from(body).toString("utf8");
157
+ return "";
158
+ }
159
+ /** The model ref `provider/model-id`. */
160
+ function modelRef(ref) {
161
+ const at = ref.indexOf("/");
162
+ return at > 0 && at < ref.length - 1 ? { provider: ref.slice(0, at), modelId: ref.slice(at + 1) } : undefined;
163
+ }
164
+ /** The values of the keys `env` holds but those named in `except`, each read by name (withSecrets keeps the server's off
165
+ * its enumeration): SECRET_NAMES and every key-shaped name. */
166
+ const keyValues = (env, except = []) => [...new Set([...SECRET_NAMES, ...Object.keys(env).filter((name) => keyShaped(name))])]
167
+ .filter((name) => !except.includes(name))
168
+ .map((name) => env[name])
169
+ .filter((value) => typeof value === "string" && value.length >= 8);
170
+ /** `value` with every string in it put through `cut`, its arrays and objects walked (their names are the check's own). */
171
+ const cutEvery = (value, cut) => (typeof value === "string" ? cut(value)
172
+ : Array.isArray(value) ? value.map((each) => cutEvery(each, cut))
173
+ : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([name, each]) => [name, cutEvery(each, cut)]))
174
+ : value);
175
+ /** Runs the check. Never throws for what it judges: a refused recipe, a missing install or a failed stage is in the
176
+ * report (`ok: false`, `failures`). Every string of the report and every line it says has the server's secrets and the
177
+ * recipe's keys cut (runner/redact.ts secretRedactor), so an agent's words in it (a failed turn's stderr, a refusal, a
178
+ * log line) never carry a key out to the report's file or the terminal. */
179
+ export async function harnessCheck(options) {
180
+ // The values cut: the server's secrets, then the recipe's keys' values once it is loaded (checkRun adds them).
181
+ const held = [...hostSecrets(options.env), ...keyValues(options.env)];
182
+ const cut = () => secretRedactor(held);
183
+ const report = await checkRun({ ...options, say: (line) => options.say?.(cut()(line)) }, held);
184
+ return cutEvery(report, cut());
185
+ }
186
+ /** The check itself (harnessCheck), adding the values of the recipe's keys to `held` once it is loaded. */
187
+ async function checkRun(options, held) {
188
+ const say = options.say ?? (() => { });
189
+ const checkedAt = new Date().toISOString();
190
+ const failures = [];
191
+ let loaded;
192
+ try {
193
+ loaded = loadRecipe(options.recipe);
194
+ }
195
+ catch (error) {
196
+ if (!(error instanceof RecipeRefused))
197
+ throw error;
198
+ return { ok: false, recipe: { file: options.recipe }, refused: { code: error.code, message: error.message }, checkedAt, failures: [error.message] };
199
+ }
200
+ const { recipe } = loaded;
201
+ // The recipe's keys, read by name from the check's environment: the agent holds them, so its words may too.
202
+ held.push(...recipe.keys.map((name) => options.env[name]).filter((value) => typeof value === "string"));
203
+ const head = { recipe: { id: recipe.id, label: recipe.label, file: loaded.file, sha256: loaded.sha256 }, checkedAt };
204
+ const refuse = (code, message) => ({ ok: false, ...head, refused: { code, message: `${code}: ${message}` }, failures: [`${code}: ${message}`] });
205
+ say(`${recipe.label}: the recipe holds the five rules (${loaded.file})`);
206
+ // Stage 2's pins: the installed binary, the one the owner's install put there. Nothing is downloaded here.
207
+ const platform = options.platform ?? archivePlatform();
208
+ const release = releaseFor(recipe, platform);
209
+ if (!platform || !release)
210
+ return refuse("HARNESS_PLATFORM_UNSUPPORTED", `${recipe.label} ${recipe.release.version} has no release for ${platform ?? `${process.platform}-${process.arch}`}`);
211
+ const binary = recipeBinaryOf(options.data, recipe, release);
212
+ const line = recipeInstallLine(loaded.file, options.data, options.env);
213
+ const pin = pinnedDigest(options.data, recipe, release, platform);
214
+ if (!existsSync(binary) || !pin)
215
+ return refuse("HARNESS_NOT_INSTALLED", `${recipe.label} ${recipe.release.version} is not installed in ${installDirOf(options.data, recipe.id)}; a check never downloads it. Install it with: ${line}`);
216
+ const found = await digestOf(binary).catch(() => undefined);
217
+ if (found !== pin.sha256)
218
+ return refuse(ARCHIVE_CODES.binary, `${binary} has sha256 ${found ?? "(unreadable)"}, and ${pin.by === "recipe" ? "the recipe pins" : "its first install recorded"} ${pin.sha256}. Install it again with: ${line}`);
219
+ say(`${recipe.label}: the binary is the pinned one (${pin.by === "recipe" ? "the recipe's sha256" : "the first sha256 its install recorded"})`);
220
+ const acp = acpPackage();
221
+ if (!acp)
222
+ return refuse("HARNESS_NOT_INSTALLED", `the ACP adapter (${ACP_PACKAGE}) is not installed beside this server`);
223
+ // The run's model, for a recipe billed through the proxy: named here; its key, the login refusal and its price are its
224
+ // entry's (below), as a server's are.
225
+ const env = options.env;
226
+ let needs;
227
+ if (recipe.model.billing === "proxy") {
228
+ const ref = options.model ? modelRef(options.model) : undefined;
229
+ if (!ref)
230
+ return refuse("HARNESS_CHECK_USAGE", `${recipe.label} is billed through the proxy: name the run's model with --model provider/model-id (openrouter/anthropic/claude-haiku-4.5, anthropic/claude-haiku-4-5)`);
231
+ needs = { model: ref, models: await providerModels(env) };
232
+ }
233
+ // The session: the check's tools, its gate, its egress proxy, the recording fetch.
234
+ const nonce = randomBytes(6).toString("hex");
235
+ const echoed = [];
236
+ const deniedRan = [];
237
+ const tools = [
238
+ { name: "check_echo", description: "Echo the text back, prefixed with ECHO.", inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] }, replay: "never", call: async (args) => (echoed.push(args), { text: `ECHO:${args?.text ?? ""}` }) },
239
+ { name: "check_denied", description: "A tool this run refuses: calling it shows the refusal.", inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] }, replay: "never", call: async (args) => (deniedRan.push(args), { text: "this call should never have run" }) },
240
+ ];
241
+ // The gate allows check_echo alone. Everything else is denied, the agent's own calls (`acp_<kind>`) included, as a
242
+ // server's gate answers them: a call of ours whose title the adapter can't tie is one of those, so it fails mcp_tool.
243
+ const gateAsked = [];
244
+ const gate = async (call) => {
245
+ const answer = call.tool === "check_echo" ? "allow" : "deny";
246
+ gateAsked.push({ tool: call.tool, answer });
247
+ return answer === "allow" ? "allow" : { deny: "harness-check refuses this call on purpose" };
248
+ };
249
+ const forwarded = [];
250
+ const forward = options.fetch ?? fetch;
251
+ const recording = async (input, init) => {
252
+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
253
+ const text = bodyText(init?.body);
254
+ let toolNames = [];
255
+ try {
256
+ const parsed = JSON.parse(text);
257
+ toolNames = (parsed.tools ?? []).map((tool) => String(tool.name));
258
+ }
259
+ catch {
260
+ // Not JSON: no tools.
261
+ }
262
+ forwarded.push({ method: init?.method ?? "GET", path: url.pathname, tools: toolNames, text });
263
+ return forward(input, init);
264
+ };
265
+ const logs = [];
266
+ const log = (message, fields) => void logs.push({ message, ...(fields ?? {}) });
267
+ // A plan-billed agent reaches its vendor through the check's proxy, tunneled to the hosts its recipe names.
268
+ const egress = await egressProxy(recipe.model.billing === "plan" ? (recipe.model.hosts ?? []) : []);
269
+ const work = await mkdtemp(join(tmpdir(), "agentrun-harness-check-"));
270
+ const canary = `harness-check-canary-${nonce}`;
271
+ // The host's environment as the adapter reads it, by name, with the canary over it: built on `env` (its prototype), not
272
+ // spread from it, so the keys withSecrets keeps off its enumeration still read by name. The recipe's keys reach the
273
+ // agent from here alone (the adapter's recipe.keys, as a run's do): a host without one is refused before the start.
274
+ const hostEnv = Object.create(env, { HARNESS_CHECK_CANARY: { value: canary, enumerable: true } });
275
+ // The values of every key the host holds, the server's own included: withSecrets keeps those off its enumeration, so
276
+ // each is read by name.
277
+ const hostKeys = keyValues(env, recipe.keys);
278
+ const childVars = { ...recipe.env };
279
+ for (const name of EGRESS_VARS)
280
+ childVars[name] = egress.url;
281
+ for (const name of NO_PROXY_VARS)
282
+ childVars[name] = `${LOOPBACK},localhost`; // key-gate: loopback-rule the hosts the agent reaches without the refusing proxy: the model proxy and MCP on this machine
283
+ // The run's model id reaches a proxy-billed agent under the variable its recipe names.
284
+ const modelVar = recipe.model.billing === "proxy" ? recipe.model.env : undefined;
285
+ const acpRecipeOf = (model) => ({
286
+ id: recipe.id,
287
+ label: recipe.label,
288
+ command: binary,
289
+ args: [...recipe.args],
290
+ env: { ...childVars, ...(modelVar && model !== undefined ? { [modelVar]: model } : {}) },
291
+ keys: [...recipe.keys],
292
+ files: { ...recipe.files },
293
+ state: [...recipe.state],
294
+ declares: { ...recipe.declares },
295
+ billing: recipe.model.billing === "proxy" ? { kind: "proxy" } : { kind: "plan", maxTurns: recipe.model.maxTurns, maxToolCalls: recipe.model.maxToolCalls },
296
+ ...(recipe.quirks.mcpCall ? { quirks: { mcpCall: recipe.quirks.mcpCall } } : {}),
297
+ });
298
+ const starts = [];
299
+ // Each start of the agent's process checks the pin again: a binary swapped after the check began never runs.
300
+ const beforeStart = async (command) => {
301
+ const now = await digestOf(command);
302
+ starts.push(now);
303
+ if (now !== pin.sha256)
304
+ throw new Error(`${ARCHIVE_CODES.binary}: ${command} changed after the check began (sha256 ${now})`);
305
+ };
306
+ // A recipe starts as an ACP agent outside the built-ins does on a server (harness-table.ts acpEntryOf), on this check's
307
+ // log and host environment. Proxy-billed: as a module's, its model and key chosen and a login refused there, its price,
308
+ // the adapter over its recipe and the session's model proxy (the one on Anthropic's Messages there is, Goose's policy,
309
+ // its address under the variable the recipe names). Billed to its plan: as Cursor's, on its vendor's own default model.
310
+ const proxyAt = recipe.model.billing === "proxy" ? (recipe.model.hostEnv ?? "ANTHROPIC_HOST") : "ANTHROPIC_HOST";
311
+ const entry = needs ? acpEntryOf({
312
+ facts: { ...acp.gooseFacts, id: recipe.id, label: recipe.label },
313
+ recipe: (launch) => acpRecipeOf(launch.model),
314
+ proxy: (launch) => {
315
+ const messagesProxy = acp.gooseProxy({ model: launch.model, provider: launch.provider, price: launch.price, log: launch.log, fetch: recording });
316
+ return async (session) => {
317
+ // The proxy's own address, under proxyAt, beside the key that opens it alone (never a provider's).
318
+ const started = await messagesProxy(session);
319
+ const { ANTHROPIC_HOST: address, ...opens } = started.env;
320
+ return { env: { ...opens, [proxyAt]: address }, close: started.close };
321
+ };
322
+ },
323
+ beforeStart,
324
+ }, { log }) : acpEntryOf({
325
+ facts: { ...acp.cursorFacts, id: recipe.id, label: recipe.label },
326
+ recipe: () => acpRecipeOf(),
327
+ beforeStart,
328
+ }, { log });
329
+ const planNeeds = { model: { provider: recipe.id, modelId: "default" }, models: { getModel: () => undefined } };
330
+ const adapterFor = async () => entry.adapter(hostEnv, needs ?? planNeeds);
331
+ // The first runner's adapter is made before any turn, so a model this server can't run is refused before the agent
332
+ // starts; with it, the cap's model, priced here or refused.
333
+ let firstAdapter;
334
+ let capModel;
335
+ if (needs) {
336
+ const refuseHere = async (message) => {
337
+ await egress.close();
338
+ await rm(work, { recursive: true, force: true }).catch(() => { });
339
+ return refuse("HARNESS_CHECK_MODEL", message);
340
+ };
341
+ try {
342
+ firstAdapter = await adapterFor();
343
+ }
344
+ catch (error) {
345
+ return refuseHere(error.message);
346
+ }
347
+ const priceModel = entry.priceModel(hostEnv, needs.model);
348
+ const listed = needs.models.getModel(priceModel.provider, priceModel.modelId);
349
+ capModel = capModelOf(priceModel.modelId, "anthropic-messages", listed, listed === undefined);
350
+ if (!capModel.price)
351
+ return refuseHere(`${priceModel.provider}/${priceModel.modelId} has no price here, so the check's cap could not hold; name a priced model`);
352
+ }
353
+ let capUsd = options.capUsd ?? CHECK_DEFAULT_CAP_USD;
354
+ const store = checkStore();
355
+ const refusedRequests = [];
356
+ let lastBooking;
357
+ // A runner's session, in its own directory (the one a server lends, io.dir), on its own adapter.
358
+ const sessionOn = async (dir) => {
359
+ const adapter = firstAdapter ?? (await adapterFor());
360
+ firstAdapter = undefined;
361
+ const writer = await store.open("check");
362
+ const booking = await modelPortFor(writer, {
363
+ key: "check",
364
+ ...(capModel ? { beforeRequest: beforeRequestOf({ capUsd: () => capUsd, modelOf: () => capModel }) } : {}),
365
+ stop: (reason, message, code) => (refusedRequests.push({ reason, ...(code ? { code } : {}), ...(message ? { message } : {}) }), new Error(`${code ?? reason}: ${message ?? ""}`)),
366
+ });
367
+ lastBooking = booking;
368
+ const controller = new AbortController();
369
+ const session = await adapter.open({ key: "check", label: "root", system: [], tools, context: "fresh" }, { writer, models: booking.models, signal: controller.signal, onEvent: () => { }, gate, dir });
370
+ const turn = async (text) => {
371
+ const timer = setTimeout(() => controller.abort(new Error("the turn took too long")), options.turnMs ?? TURN_MS);
372
+ try {
373
+ await session.send(text);
374
+ return await session.turnEnd();
375
+ }
376
+ finally {
377
+ clearTimeout(timer);
378
+ }
379
+ };
380
+ return { session, turn, booking };
381
+ };
382
+ const opened = () => logs.filter((l) => l.message === "acp: the agent's session is open");
383
+ const asked = () => logs.filter((l) => l.message === "acp: the agent asked permission");
384
+ const messages = () => forwarded.filter((r) => r.method === "POST" && r.path.endsWith("/v1/messages"));
385
+ const stage2 = {};
386
+ const stage3 = {};
387
+ let resumeFact = "unknown";
388
+ try {
389
+ // Turn 1: one of our tools over MCP.
390
+ say(`${recipe.label}: turn 1, a call of our check_echo tool over MCP`);
391
+ const first = await sessionOn(join(work, "runner-a"));
392
+ const t1 = await first.turn(`Use the check_echo tool once, with the text argument set to ${nonce}. Then reply with exactly what it returned and nothing else.`);
393
+ const firstOpen = opened()[0];
394
+ // The environment while the agent runs.
395
+ const environ = firstOpen?.pid ? environOf(firstOpen.pid) : undefined;
396
+ const echoReached = messages().some((r) => r.text.includes(`ECHO:${nonce}`));
397
+ stage3.mcp_tool = { ok: t1.status === "completed" && echoed.length >= 1 && (recipe.model.billing !== "proxy" || echoReached), turn: t1.status, ...(t1.error ? { error: t1.error } : {}), calls: echoed.length, resultReachedModel: recipe.model.billing === "proxy" ? echoReached : null };
398
+ // Stage 2: the tools the agent offered its model on its first request. The proxy refuses a request that offers a tool
399
+ // its policy does not allow, so one that reached the provider at all passed that rule: the stage is whether one did.
400
+ // Its refusals are listed beside it, never counted: a port watcher's GET / is refused too.
401
+ if (recipe.model.billing === "proxy") {
402
+ const firstRequest = messages()[0];
403
+ const ours = new Set(tools.map((tool) => `agentrun__${tool.name}`));
404
+ const offered = firstRequest?.tools ?? [];
405
+ const refusals = logs.filter((l) => /refus/i.test(l.message)).map((l) => ({ message: l.message, ...(typeof l.reason === "string" ? { reason: l.reason } : {}) }));
406
+ stage2.tools_off = { ok: !!firstRequest, firstRequest: offered, notOurs: offered.filter((name) => !ours.has(name)), ...(refusals.length ? { proxyRefusals: refusals } : {}) };
407
+ }
408
+ else
409
+ stage2.tools_off = { ok: null, why: "plan billing: the vendor's model requests never reach this host, so the tools it offers are not seen" };
410
+ // Stage 2: the environment is the allowlist.
411
+ if (environ) {
412
+ // The recipe's keys too: the adapter hands each over by name (recipe.keys), never through childVars.
413
+ const expected = new Set([...Object.values(AGENT_VARS).flat(), ...Object.keys(childVars), ...(modelVar ? [modelVar] : []), ...recipe.keys, ...SHELL_OWN]);
414
+ const extra = Object.keys(environ).filter((name) => !expected.has(name)).sort();
415
+ const leaked = Object.entries(environ).filter(([, value]) => hostKeys.includes(value) || value === canary).map(([name]) => name).sort();
416
+ stage2.env_allowlist = { ok: extra.length === 0 && leaked.length === 0, names: Object.keys(environ).sort(), beyondAllowlist: extra, hostSecretsSeen: leaked };
417
+ }
418
+ else
419
+ stage2.env_allowlist = { ok: null, why: process.platform === "linux" ? "the agent's process was gone before its environment was read" : "the environment is read from /proc, on Linux alone" };
420
+ // Kill the agent, then turn 2: the denied call, and what turn 1 said.
421
+ let killed = false;
422
+ if (firstOpen?.pid)
423
+ killed = await killAgent(firstOpen.pid, binary);
424
+ say(`${recipe.label}: the agent is killed (SIGKILL, pid ${firstOpen?.pid ?? "unknown"}); turn 2, a denied call and the conversation so far`);
425
+ const before = messages().length;
426
+ const t2 = await first.turn(`Use the check_denied tool once, with the text argument set to two. It will be refused; that is expected. Then reply with the text the check_echo tool returned earlier in this conversation.`);
427
+ const secondOpen = opened()[1];
428
+ // What check_echo returned in turn 1 is in the model's next request: the conversation came through the kill.
429
+ const remembered = messages().slice(before).some((r) => r.text.includes(`ECHO:${nonce}`));
430
+ resumeFact = secondOpen ? (secondOpen.loaded ? "load" : "restart") : "unknown";
431
+ stage3.resume = { ok: killed && t2.status === "completed" && !!secondOpen && secondOpen.pid !== firstOpen?.pid && (recipe.model.billing !== "proxy" || remembered), killed, turn: t2.status, ...(t2.error ? { error: t2.error } : {}), newProcess: !!secondOpen && secondOpen.pid !== firstOpen?.pid, loaded: secondOpen?.loaded ?? null, sameSession: !!secondOpen && secondOpen.sessionId === firstOpen?.sessionId, conversationCarried: recipe.model.billing === "proxy" ? remembered : null };
432
+ const deniedAsked = gateAsked.filter((g) => g.tool === "check_denied");
433
+ stage3.denied_call = { ok: deniedAsked.length >= 1 && deniedAsked.every((g) => g.answer === "deny") && deniedRan.length === 0 && t2.status === "completed", gateAsked: deniedAsked.length, ran: deniedRan.length, turn: t2.status };
434
+ await first.session.close();
435
+ // Turn 3: another runner, its own directory, from the records.
436
+ say(`${recipe.label}: turn 3, another runner picks the session up from the records`);
437
+ const other = await sessionOn(join(work, "runner-b"));
438
+ const before3 = messages().length;
439
+ const t3 = await other.turn("Reply with the word ready and nothing else.");
440
+ const thirdOpen = opened().at(-1);
441
+ const carried3 = messages().slice(before3).some((r) => r.text.includes(`ECHO:${nonce}`));
442
+ stage3.other_runner = { ok: t3.status === "completed" && (recipe.model.billing !== "proxy" || carried3), turn: t3.status, ...(t3.error ? { error: t3.error } : {}), loaded: thirdOpen?.loaded ?? null, conversationCarried: recipe.model.billing === "proxy" ? carried3 : null };
443
+ // Turn 4: the billing limit. Proxy: the cap is set at what was spent, so the next request is refused unsent.
444
+ if (recipe.model.billing === "proxy") {
445
+ const spent = other.booking.spentUsd();
446
+ capUsd = spent ?? 0;
447
+ const sentBefore = messages().length;
448
+ const t4 = await other.turn("Reply with the word ok.");
449
+ const unsent = messages().length === sentBefore;
450
+ stage2.limits = { ok: t4.status !== "completed" && unsent && refusedRequests.some((r) => r.reason === "refused"), billing: "proxy", capUsd: capUsd, turn: t4.status, refusedUnsent: unsent, ...(refusedRequests.length ? { refusal: refusedRequests.at(-1) } : {}) };
451
+ }
452
+ else
453
+ stage2.limits = { ok: true, billing: "plan", maxTurns: recipe.model.maxTurns, maxToolCalls: recipe.model.maxToolCalls, why: "the adapter stops the run at these; the vendor bills the owner's plan" };
454
+ await other.session.close();
455
+ // Stage 2: the pin held at every start; no side request.
456
+ stage2.pins = { ok: starts.length > 0 && starts.every((sha) => sha === pin.sha256), binary, sha256: pin.sha256, pinnedBy: pin.by, archiveSha256: release.sha256, starts: starts.length };
457
+ if (recipe.model.billing === "proxy") {
458
+ const paths = [...new Set(forwarded.map((r) => `${r.method} ${r.path}`))];
459
+ // What the agent asked the proxy for beyond the Messages route: refused there, never sent on.
460
+ const atProxy = logs.filter((l) => /: refused$/.test(l.message) && typeof l.path === "string" && !String(l.path).startsWith("/v1/messages")).map((l) => `${String(l.method)} ${String(l.path)}`);
461
+ // The provider's Messages route, under its own prefix (OpenRouter's is /api/v1/messages).
462
+ stage2.side_requests = { ok: forwarded.every((r) => r.method === "POST" && r.path.endsWith("/v1/messages")), toProvider: paths, sent: forwarded.length, refusedAtProxy: atProxy, beyondLoopbackRefused: egress.asked.filter((a) => !a.tunneled).map((a) => `${a.method} ${a.target}`) };
463
+ }
464
+ else
465
+ stage2.side_requests = { ok: null, toVendor: [...new Set(egress.asked.filter((a) => a.tunneled).map((a) => a.target))], beyondLoopbackRefused: egress.asked.filter((a) => !a.tunneled).map((a) => `${a.method} ${a.target}`), why: "plan billing: the vendor's requests are tunneled to model.hosts through the check's proxy, so their content is not seen here" };
466
+ }
467
+ catch (error) {
468
+ failures.push(`the check stopped: ${error.message}`);
469
+ }
470
+ finally {
471
+ await egress.close();
472
+ await rm(work, { recursive: true, force: true }).catch(() => { });
473
+ }
474
+ for (const [stage, checks] of [["stage2", stage2], ["stage3", stage3]]) {
475
+ for (const [name, check] of Object.entries(checks))
476
+ if (check.ok === false)
477
+ failures.push(`${stage}.${name} failed`);
478
+ }
479
+ for (const name of ["tools_off", "env_allowlist", "limits", "pins", "side_requests"])
480
+ if (!(name in stage2) && !failures.some((f) => f.startsWith("the check stopped")))
481
+ failures.push(`stage2.${name} did not run`);
482
+ for (const name of ["mcp_tool", "resume", "denied_call", "other_runner"])
483
+ if (!(name in stage3) && !failures.some((f) => f.startsWith("the check stopped")))
484
+ failures.push(`stage3.${name} did not run`);
485
+ return {
486
+ ok: failures.length === 0,
487
+ ...head,
488
+ platform,
489
+ ...(options.model ? { model: options.model } : {}),
490
+ binary: { path: binary, sha256: pin.sha256, pinnedBy: pin.by },
491
+ stage2,
492
+ stage3,
493
+ facts: { resume: resumeFact, tool_gate: asked().length > 0 ? "permission" : "config", billing: recipe.model.billing },
494
+ // How the tool gate was reached: each permission the agent asked for, and each question the gate was asked.
495
+ gate: {
496
+ permissionsAsked: asked().map((l) => ({ toolCallId: l.toolCallId ?? null, kind: l.kind ?? null })),
497
+ asked: gateAsked,
498
+ },
499
+ spendUsd: lastBooking ? lastBooking.spentUsd() : 0,
500
+ failures,
501
+ };
502
+ }
503
+ /** The three facts and the verdict, as the command prints them. */
504
+ export function printedFacts(report) {
505
+ if (report.refused)
506
+ return [`harness-check: refused: ${report.refused.message}`];
507
+ const lines = [];
508
+ for (const [stage, checks] of [["stage 2", report.stage2 ?? {}], ["stage 3", report.stage3 ?? {}]]) {
509
+ for (const [name, check] of Object.entries(checks))
510
+ lines.push(`${stage} ${name}: ${check.ok === true ? "pass" : check.ok === false ? "FAIL" : `unverified (${String(check.why ?? "")})`}`);
511
+ }
512
+ lines.push(`resume: ${report.facts?.resume}`, `tool_gate: ${report.facts?.tool_gate}`, `billing: ${report.facts?.billing}`);
513
+ lines.push(`spend: ${report.spendUsd === null || report.spendUsd === undefined ? "unknown" : `$${report.spendUsd.toFixed(5)}`}`);
514
+ lines.push(`harness-check: ${report.ok ? "passed" : `FAILED (${report.failures.join("; ")})`}`);
515
+ return lines;
516
+ }
517
+ /** Writes the report to `file`. */
518
+ export const writeReport = (file, report) => writeFile(file, `${JSON.stringify(report, null, 2)}\n`);
@@ -0,0 +1,28 @@
1
+ import type { AcpPackage } from "./acp-package.js";
2
+ export declare const CURSOR_ID = "cursor";
3
+ /** The key Cursor runs on: the owner's Cursor API key, read by name, handed to Cursor's runs and no other. */
4
+ export declare const CURSOR_KEY = "CURSOR_API_KEY";
5
+ /** The owner's limits for a run of Cursor (CURSOR_LIMITS, the package's, by default): its turns and its tool calls. */
6
+ export declare const CURSOR_MAX_TURNS_ENV = "AGENTRUN_CURSOR_MAX_TURNS";
7
+ export declare const CURSOR_MAX_TOOL_CALLS_ENV = "AGENTRUN_CURSOR_MAX_TOOL_CALLS";
8
+ /** The provider a Cursor model is named under (`cursor/<model>`, `cursor/default` for Cursor's own default). */
9
+ export declare const CURSOR_PROVIDER = "cursor";
10
+ export declare const CURSOR_DEFAULT_MODEL = "default";
11
+ /** Cursor as an owner-installed harness, pinned by its tree: its pin, its install line and its not-installed code are its
12
+ * package's. */
13
+ export declare const CURSOR: import("./harness-owned.js").OwnerInstalled;
14
+ export declare const cursorHidden: (env: NodeJS.ProcessEnv) => string | undefined, cursorMissing: (env: NodeJS.ProcessEnv) => Promise<{
15
+ missing: import("./harness-owned.js").OwnerMissing;
16
+ } | {
17
+ binary: string;
18
+ sha256: string;
19
+ }>;
20
+ /** The limits a run of Cursor stops at on `env`: the owner's (CURSOR_MAX_TURNS_ENV, CURSOR_MAX_TOOL_CALLS_ENV), else the
21
+ * package's. A setting that is no whole number is refused by name. */
22
+ export declare function cursorLimitsOf(acp: AcpPackage, env: NodeJS.ProcessEnv): {
23
+ maxTurns: number;
24
+ maxToolCalls: number;
25
+ };
26
+ /** The card Cursor's owner reads (capabilities' harness `card`), with this server's limits; none where Cursor's adapter is
27
+ * not beside the server, or its limits are set wrong (its refusal says so). */
28
+ export declare function cursorCardOf(env: NodeJS.ProcessEnv): string | undefined;
@@ -0,0 +1,42 @@
1
+ import { acpPackage } from "./acp-package.js";
2
+ import { ownerInstalled } from "./harness-owned.js";
3
+ export const CURSOR_ID = "cursor";
4
+ /** The key Cursor runs on: the owner's Cursor API key, read by name, handed to Cursor's runs and no other. */
5
+ export const CURSOR_KEY = "CURSOR_API_KEY";
6
+ /** The owner's limits for a run of Cursor (CURSOR_LIMITS, the package's, by default): its turns and its tool calls. */
7
+ export const CURSOR_MAX_TURNS_ENV = "AGENTRUN_CURSOR_MAX_TURNS";
8
+ export const CURSOR_MAX_TOOL_CALLS_ENV = "AGENTRUN_CURSOR_MAX_TOOL_CALLS";
9
+ /** The provider a Cursor model is named under (`cursor/<model>`, `cursor/default` for Cursor's own default). */
10
+ export const CURSOR_PROVIDER = "cursor";
11
+ export const CURSOR_DEFAULT_MODEL = "default";
12
+ /** Cursor as an owner-installed harness, pinned by its tree: its pin, its install line and its not-installed code are its
13
+ * package's. */
14
+ export const CURSOR = ownerInstalled({ id: CURSOR_ID, label: "Cursor", pin: (acp) => acp.CURSOR_PIN, installLine: (acp) => acp.CURSOR_INSTALL, notInstalled: (acp) => acp.CURSOR_CODES.notInstalled, tree: true });
15
+ export const { hidden: cursorHidden, missing: cursorMissing } = CURSOR;
16
+ /** The limits a run of Cursor stops at on `env`: the owner's (CURSOR_MAX_TURNS_ENV, CURSOR_MAX_TOOL_CALLS_ENV), else the
17
+ * package's. A setting that is no whole number is refused by name. */
18
+ export function cursorLimitsOf(acp, env) {
19
+ const read = (name, fallback, least) => {
20
+ const given = env[name];
21
+ if (given === undefined || given === "")
22
+ return fallback;
23
+ const n = Number(given);
24
+ if (!/^\d+$/.test(given.trim()) || !Number.isSafeInteger(n) || n < least)
25
+ throw new Error(`${name} is ${JSON.stringify(given)}: set it to a whole number of at least ${least}, or unset it for ${fallback}`);
26
+ return n;
27
+ };
28
+ return { maxTurns: read(CURSOR_MAX_TURNS_ENV, acp.CURSOR_LIMITS.maxTurns, 1), maxToolCalls: read(CURSOR_MAX_TOOL_CALLS_ENV, acp.CURSOR_LIMITS.maxToolCalls, 0) };
29
+ }
30
+ /** The card Cursor's owner reads (capabilities' harness `card`), with this server's limits; none where Cursor's adapter is
31
+ * not beside the server, or its limits are set wrong (its refusal says so). */
32
+ export function cursorCardOf(env) {
33
+ const acp = acpPackage();
34
+ if (!acp)
35
+ return undefined;
36
+ try {
37
+ return acp.cursorCard(cursorLimitsOf(acp, env));
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
@@ -1,34 +1,9 @@
1
- import { type AcpPackage } from "./acp-package.js";
2
- import { type ArchiveInstallOptions } from "./harness-archive.js";
3
1
  export declare const GOOSE_ID = "goose";
4
- /** Why Goose does not run here: a code (HARNESS_NOT_INSTALLED, ACP_BINARY_MISMATCH, ACP_BINARY_UNPINNED, ...) and words
5
- * that start with it and end with the command that installs it. */
6
- export type GooseMissing = {
7
- readonly code: string;
8
- readonly message: string;
9
- };
10
- /** Goose's folder in `data`, and its binary there. */
11
- export declare const gooseDirOf: (data: string) => string;
12
- export declare const gooseBinaryOf: (data: string) => string;
13
- /** The agentrun command's own data directory, where `npx @parcha/agentrun` keeps its server's store (~/.agentrun: not the
14
- * server's own default, defaultData), and so where `agentrun harness install` installs with no --data. */
15
- export declare const commandData: (env: NodeJS.ProcessEnv) => string;
16
- /** The command that installs Goose into `data`: naming it with --data unless it is the agentrun command's own (commandData). */
17
- export declare function gooseInstallLine(acp: AcpPackage, data: string, env?: NodeJS.ProcessEnv): string;
18
- /** Why Goose is not listed here (HarnessEntry.hidden): not installed, or not the pinned binary, in words that end with what
19
- * to do, restarting AgentRun included (its harnesses are read at its start). Undefined once it is installed and verified.
20
- * The binary's sha256 is kept once per file identity (the package's check), so only the first look reads it. */
21
- export declare function gooseHidden(env: NodeJS.ProcessEnv): string | undefined;
22
- /** Why Goose cannot run here, its binary checked off the event loop; undefined when it can (with the binary to run). */
23
- export declare function gooseMissing(env: NodeJS.ProcessEnv): Promise<{
24
- missing: GooseMissing;
2
+ /** Goose as an owner-installed harness: its pin, its install line and its not-installed code are its package's. */
3
+ export declare const GOOSE: import("./harness-owned.js").OwnerInstalled;
4
+ export declare const gooseHidden: (env: NodeJS.ProcessEnv) => string | undefined, gooseMissing: (env: NodeJS.ProcessEnv) => Promise<{
5
+ missing: import("./harness-owned.js").OwnerMissing;
25
6
  } | {
26
7
  binary: string;
27
8
  sha256: string;
28
9
  }>;
29
- /** Installs the pinned Goose into `data` (agentrun-serve install-harness goose). */
30
- export declare function installGoose(data: string, options?: ArchiveInstallOptions, env?: NodeJS.ProcessEnv): Promise<{
31
- installed: "already" | "now";
32
- binary: string;
33
- version: string;
34
- }>;