@parcha/agentrun-serve 0.1.0-beta.56 → 0.1.0-beta.58

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 (312) hide show
  1. package/CHANGELOG.md +281 -0
  2. package/README.md +246 -66
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +15 -3
  5. package/dist/adapters.js +17 -6
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/api-keys.d.ts +76 -0
  9. package/dist/api-keys.js +217 -0
  10. package/dist/api-only.d.ts +15 -5
  11. package/dist/api-only.js +32 -8
  12. package/dist/box-paths.d.ts +4 -3
  13. package/dist/box-paths.js +7 -4
  14. package/dist/browser-hold.d.ts +23 -0
  15. package/dist/browser-hold.js +48 -0
  16. package/dist/browser-person.d.ts +3 -0
  17. package/dist/browser-person.js +4 -1
  18. package/dist/chatgpt-plan.d.ts +18 -8
  19. package/dist/chatgpt-plan.js +91 -34
  20. package/dist/claude-login-token.d.ts +117 -0
  21. package/dist/claude-login-token.js +737 -0
  22. package/dist/claude-login.d.ts +120 -22
  23. package/dist/claude-login.js +347 -63
  24. package/dist/claude-sign-in.d.ts +17 -6
  25. package/dist/claude-sign-in.js +42 -39
  26. package/dist/cli.js +33 -10
  27. package/dist/composio-made.d.ts +4 -0
  28. package/dist/composio-made.js +4 -0
  29. package/dist/composio-preset.d.ts +43 -2
  30. package/dist/composio-preset.js +92 -4
  31. package/dist/computer-attach.d.ts +35 -17
  32. package/dist/computer-attach.js +301 -49
  33. package/dist/computer-held-routes.d.ts +5 -4
  34. package/dist/computer-held-routes.js +29 -8
  35. package/dist/computer-held.d.ts +6 -1
  36. package/dist/computer-held.js +14 -0
  37. package/dist/computer-record.js +4 -2
  38. package/dist/computer-viewer.js +4 -1
  39. package/dist/computers.d.ts +10 -10
  40. package/dist/computers.js +5 -5
  41. package/dist/console/assets/{backend-Boh7tC4i.js → backend-CSAWUqtZ.js} +19 -19
  42. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  43. package/dist/console/assets/index-DPh29cyz.js +747 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/decisions.d.ts +1 -1
  46. package/dist/decisions.js +1 -1
  47. package/dist/dial-relay.d.ts +25 -4
  48. package/dist/dial-relay.js +129 -1
  49. package/dist/docker-host-addresses.d.ts +22 -11
  50. package/dist/docker-host-addresses.js +38 -26
  51. package/dist/env-switch.d.ts +8 -0
  52. package/dist/env-switch.js +31 -2
  53. package/dist/errors.d.ts +1 -0
  54. package/dist/errors.js +2 -0
  55. package/dist/fal-price.d.ts +56 -20
  56. package/dist/fal-price.js +400 -90
  57. package/dist/handed-values.d.ts +43 -1
  58. package/dist/handed-values.js +119 -2
  59. package/dist/harness-archive.d.ts +13 -10
  60. package/dist/harness-archive.js +60 -34
  61. package/dist/harness-check.d.ts +3 -1
  62. package/dist/harness-check.js +25 -46
  63. package/dist/harness-keys.d.ts +73 -27
  64. package/dist/harness-keys.js +194 -61
  65. package/dist/harness-recipe-entry.d.ts +8 -7
  66. package/dist/harness-recipe-entry.js +21 -32
  67. package/dist/harness-recipe.d.ts +38 -25
  68. package/dist/harness-recipe.js +49 -36
  69. package/dist/harness-sign-in.js +12 -23
  70. package/dist/harness-table.d.ts +10 -3
  71. package/dist/harness-table.js +26 -21
  72. package/dist/harness.d.ts +1 -0
  73. package/dist/harness.js +17 -5
  74. package/dist/hosted-search.d.ts +1 -1
  75. package/dist/hosted-search.js +1 -2
  76. package/dist/import-worker.d.ts +4 -2
  77. package/dist/import-worker.js +9 -2
  78. package/dist/in-flight.d.ts +26 -0
  79. package/dist/in-flight.js +52 -0
  80. package/dist/key-refusal.d.ts +9 -4
  81. package/dist/key-refusal.js +107 -25
  82. package/dist/learn/ledger.d.ts +170 -0
  83. package/dist/learn/ledger.js +218 -0
  84. package/dist/learn/promote.d.ts +3 -3
  85. package/dist/learn/promote.js +1 -1
  86. package/dist/learn/secrets.d.ts +13 -3
  87. package/dist/learn/secrets.js +118 -17
  88. package/dist/learning-cost.d.ts +28 -23
  89. package/dist/learning-cost.js +19 -23
  90. package/dist/link-check.js +1 -1
  91. package/dist/live-reach.d.ts +2 -0
  92. package/dist/live-reach.js +2 -0
  93. package/dist/llms.txt +1 -1
  94. package/dist/marketplace.d.ts +77 -0
  95. package/dist/marketplace.js +224 -0
  96. package/dist/mcp-api-only-origins.d.ts +35 -0
  97. package/dist/mcp-api-only-origins.js +57 -0
  98. package/dist/mcp-gateway.d.ts +7 -5
  99. package/dist/mcp-gateway.js +9 -12
  100. package/dist/mcp-secret-writes.js +5 -3
  101. package/dist/mcp-servers-store.d.ts +28 -6
  102. package/dist/mcp-servers-store.js +53 -4
  103. package/dist/media-duration.d.ts +3 -0
  104. package/dist/media-duration.js +90 -9
  105. package/dist/micro.d.ts +2 -0
  106. package/dist/micro.js +2 -0
  107. package/dist/model-form.d.ts +5 -4
  108. package/dist/model-form.js +11 -7
  109. package/dist/model.d.ts +10 -6
  110. package/dist/model.js +16 -11
  111. package/dist/monid.d.ts +14 -1
  112. package/dist/monid.js +103 -26
  113. package/dist/ollama-provider.d.ts +7 -1
  114. package/dist/ollama-provider.js +14 -2
  115. package/dist/openapi.js +210 -37
  116. package/dist/otel/genai.d.ts +65 -0
  117. package/dist/otel/genai.js +116 -0
  118. package/dist/otel/tracer.d.ts +55 -0
  119. package/dist/otel/tracer.js +308 -0
  120. package/dist/page.d.ts +2 -0
  121. package/dist/page.js +3 -1
  122. package/dist/paid-calls.d.ts +1 -32
  123. package/dist/paid-calls.js +4 -39
  124. package/dist/place-offers.d.ts +4 -0
  125. package/dist/place-offers.js +7 -4
  126. package/dist/provider.d.ts +11 -2
  127. package/dist/provider.js +59 -8
  128. package/dist/redact/match.d.ts +30 -3
  129. package/dist/redact/match.js +422 -41
  130. package/dist/refusal-words.d.ts +11 -0
  131. package/dist/refusal-words.js +11 -0
  132. package/dist/run-census.d.ts +67 -0
  133. package/dist/run-census.js +240 -0
  134. package/dist/run-computer.d.ts +6 -3
  135. package/dist/run-computer.js +4 -1
  136. package/dist/run-cut.d.ts +15 -6
  137. package/dist/run-cut.js +30 -9
  138. package/dist/run-files.d.ts +3 -0
  139. package/dist/run-files.js +3 -0
  140. package/dist/run-launch.d.ts +12 -1
  141. package/dist/run-launch.js +9 -10
  142. package/dist/run-learning-served.d.ts +4 -2
  143. package/dist/run-model-key.d.ts +8 -0
  144. package/dist/run-model-key.js +31 -1
  145. package/dist/run-reads-over-store.d.ts +24 -6
  146. package/dist/run-reads-over-store.js +67 -23
  147. package/dist/run-recordings.d.ts +5 -1
  148. package/dist/run-recordings.js +39 -14
  149. package/dist/run-timeline-served.d.ts +2 -0
  150. package/dist/run-timeline-served.js +2 -2
  151. package/dist/run-usage.d.ts +1 -0
  152. package/dist/run-view.d.ts +1 -2
  153. package/dist/run-view.js +2 -1
  154. package/dist/runnable.d.ts +10 -1
  155. package/dist/runnable.js +20 -8
  156. package/dist/runner/adapter-loop.d.ts +11 -0
  157. package/dist/runner/adapter-loop.js +58 -26
  158. package/dist/runner/adapter-run-spec.d.ts +55 -11
  159. package/dist/runner/adapter-run-spec.js +183 -52
  160. package/dist/runner/adapters/pi.js +25 -3
  161. package/dist/runner/beside.d.ts +9 -2
  162. package/dist/runner/beside.js +27 -9
  163. package/dist/runner/big-writes.js +1 -10
  164. package/dist/runner/claim-secrets.d.ts +27 -10
  165. package/dist/runner/claim-secrets.js +49 -22
  166. package/dist/runner/cli-run-spec.d.ts +6 -0
  167. package/dist/runner/cli-run-spec.js +97 -38
  168. package/dist/runner/computer-journal.d.ts +9 -1
  169. package/dist/runner/computer-journal.js +26 -0
  170. package/dist/runner/conformance/harness.js +1 -1
  171. package/dist/runner/feedback-round.js +3 -0
  172. package/dist/runner/harness-loops.d.ts +6 -5
  173. package/dist/runner/harness-loops.js +7 -7
  174. package/dist/runner/held.d.ts +24 -6
  175. package/dist/runner/journal-kinds.d.ts +5 -0
  176. package/dist/runner/journal-kinds.js +5 -0
  177. package/dist/runner/main.d.ts +11 -6
  178. package/dist/runner/main.js +19 -9
  179. package/dist/runner/mcp-claim.js +31 -3
  180. package/dist/runner/mcp-run.d.ts +9 -0
  181. package/dist/runner/mcp-run.js +11 -5
  182. package/dist/runner/model-route.d.ts +17 -0
  183. package/dist/runner/model-route.js +120 -2
  184. package/dist/runner/presence.d.ts +11 -1
  185. package/dist/runner/presence.js +7 -0
  186. package/dist/runner/reflect-hook.js +1 -1
  187. package/dist/runner/run-child-host.d.ts +22 -8
  188. package/dist/runner/run-child-host.js +128 -41
  189. package/dist/runner/run-child.js +5 -2
  190. package/dist/runner/runner.d.ts +17 -3
  191. package/dist/runner/runner.js +130 -34
  192. package/dist/runner/save-slots.js +2 -1
  193. package/dist/runner/store-port.d.ts +1 -1
  194. package/dist/runner/store-secrets.d.ts +6 -0
  195. package/dist/runner/store-secrets.js +49 -7
  196. package/dist/runner/subagent.d.ts +11 -0
  197. package/dist/runner/subagent.js +16 -38
  198. package/dist/runner/workflow-first.d.ts +35 -15
  199. package/dist/runner/workflow-first.js +38 -25
  200. package/dist/runner/workflow-spec.js +4 -3
  201. package/dist/runs-over-store.d.ts +15 -6
  202. package/dist/runs-over-store.js +33 -21
  203. package/dist/scrub-command.d.ts +73 -0
  204. package/dist/scrub-command.js +307 -0
  205. package/dist/secret-cut.d.ts +73 -0
  206. package/dist/secret-cut.js +291 -4
  207. package/dist/secret-rules.d.ts +143 -0
  208. package/dist/secret-rules.js +2564 -0
  209. package/dist/secrets.d.ts +7 -0
  210. package/dist/secrets.js +20 -0
  211. package/dist/server-keys.d.ts +20 -0
  212. package/dist/server-keys.js +25 -6
  213. package/dist/server.d.ts +65 -13
  214. package/dist/server.js +470 -157
  215. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  216. package/dist/slots.d.ts +9 -0
  217. package/dist/slots.js +45 -0
  218. package/dist/store/index.d.ts +1 -1
  219. package/dist/store/index.js +1 -1
  220. package/dist/store/journal/storage.js +1 -1
  221. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  222. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  223. package/dist/store/schema.d.ts +23 -0
  224. package/dist/store/schema.js +58 -2
  225. package/dist/store/seal.d.ts +6 -1
  226. package/dist/store/seal.js +5 -3
  227. package/dist/store/sqlite/run-launch.d.ts +9 -1
  228. package/dist/store/sqlite/run-launch.js +24 -13
  229. package/dist/store/sqlite/run-patch.d.ts +12 -2
  230. package/dist/store/sqlite/run-patch.js +42 -5
  231. package/dist/store/sqlite/store.js +105 -12
  232. package/dist/store/store.d.ts +57 -2
  233. package/dist/store/store.js +20 -0
  234. package/dist/store-reads/learning.d.ts +84 -124
  235. package/dist/store-reads/learning.js +210 -274
  236. package/dist/store-view.d.ts +3 -0
  237. package/dist/store-view.js +3 -3
  238. package/dist/suggestions.js +3 -2
  239. package/dist/template-eval.d.ts +39 -9
  240. package/dist/template-eval.js +191 -60
  241. package/dist/template-import.js +6 -2
  242. package/dist/templates.d.ts +10 -2
  243. package/dist/templates.js +28 -8
  244. package/dist/timeline/labels.d.ts +6 -4
  245. package/dist/timeline/labels.js +18 -6
  246. package/dist/timeline/timeline.d.ts +5 -0
  247. package/dist/timeline/timeline.js +14 -8
  248. package/dist/timeline/util.js +1 -1
  249. package/dist/timeline/web-calls.d.ts +22 -7
  250. package/dist/timeline/web-calls.js +106 -35
  251. package/dist/tool-gate.d.ts +42 -3
  252. package/dist/tool-gate.js +66 -5
  253. package/dist/tool-keys-store.d.ts +2 -4
  254. package/dist/tool-keys-store.js +5 -21
  255. package/dist/tool-keys.d.ts +2 -2
  256. package/dist/tool-keys.js +2 -2
  257. package/dist/tool-list.js +1 -1
  258. package/dist/tool-plane.d.ts +2 -2
  259. package/dist/tool-plane.js +35 -33
  260. package/dist/tools.js +13 -7
  261. package/dist/trigger-targets.d.ts +4 -0
  262. package/dist/trigger-targets.js +9 -2
  263. package/dist/triggers.d.ts +67 -4
  264. package/dist/triggers.js +171 -22
  265. package/dist/until.d.ts +3 -0
  266. package/dist/until.js +11 -0
  267. package/dist/web-fake.d.ts +1 -3
  268. package/dist/web-fake.js +7 -18
  269. package/dist/web-fetch.d.ts +6 -72
  270. package/dist/web-fetch.js +11 -265
  271. package/dist/web-run.d.ts +31 -0
  272. package/dist/web-run.js +90 -0
  273. package/dist/web-save.d.ts +10 -13
  274. package/dist/web-save.js +13 -55
  275. package/dist/web-search.d.ts +9 -127
  276. package/dist/web-search.js +23 -259
  277. package/dist/wires.d.ts +13 -0
  278. package/dist/wires.js +11 -0
  279. package/dist/workflow-run.d.ts +5 -4
  280. package/dist/workflow-run.js +5 -4
  281. package/dist/workspace/attached-computers.d.ts +32 -9
  282. package/dist/workspace/attached-computers.js +77 -13
  283. package/dist/workspace/computer-deps.d.ts +8 -2
  284. package/dist/workspace/computer-deps.js +10 -3
  285. package/dist/workspace/computer-for-claim.d.ts +12 -1
  286. package/dist/workspace/computer-for-claim.js +83 -11
  287. package/dist/workspace/computer-kept.d.ts +3 -0
  288. package/dist/workspace/computer-kept.js +11 -2
  289. package/dist/workspace/index.d.ts +1 -1
  290. package/dist/workspace/index.js +1 -1
  291. package/dist/workspace/kind-skills.d.ts +4 -0
  292. package/dist/workspace/kind-skills.js +9 -0
  293. package/dist/workspace/paired-route.d.ts +91 -0
  294. package/dist/workspace/paired-route.js +153 -0
  295. package/dist/workspace/synced-folder.js +3 -4
  296. package/dist/wrapped.d.ts +20 -6
  297. package/dist/wrapped.js +66 -25
  298. package/package.json +17 -11
  299. package/skills/agentrun-serve/SKILL.md +4 -0
  300. package/templates/README.md +32 -10
  301. package/dist/console/assets/index-CQ3cJRzI.js +0 -746
  302. package/dist/console/assets/index-DKkaS3a0.css +0 -1
  303. package/dist/exa-keyless.d.ts +0 -34
  304. package/dist/exa-keyless.js +0 -118
  305. package/dist/firecrawl-keyless.d.ts +0 -41
  306. package/dist/firecrawl-keyless.js +0 -152
  307. package/dist/keyless-mcp.d.ts +0 -36
  308. package/dist/keyless-mcp.js +0 -127
  309. package/dist/text-urls.d.ts +0 -38
  310. package/dist/text-urls.js +0 -170
  311. package/dist/web-fetch-direct.d.ts +0 -119
  312. package/dist/web-fetch-direct.js +0 -190
@@ -17,6 +17,9 @@ export interface ViewDeps {
17
17
  readonly origin: string;
18
18
  readonly serverSecrets: () => string[];
19
19
  readonly signIns?: SignInReader;
20
+ /** The server's seal key, which opens what a run's caller handed it while its launch holds it (run-cut.ts runCutValues);
21
+ * undefined when it has none, and a run that holds some is then withheld. */
22
+ readonly sealKey: Buffer | undefined;
20
23
  /** The server's clock (ms), for the claim-lease check that decides a run is live; defaults to Date.now. The server
21
24
  * passes the same clock the store uses, so a test on a moved clock reads a fresh claim as live. */
22
25
  readonly now?: () => number;
@@ -8,7 +8,7 @@ import { isDeepStrictEqual } from "node:util";
8
8
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
9
9
  import { CAPS, isMessageRow } from "./timeline/index.js";
10
10
  import { runLink } from "./console-links.js";
11
- import { redacted, redactedAnswer, redactedOutput, withoutLoopback } from "./key-refusal.js";
11
+ import { redacted, redactedAnswer, redactedOutput, withheldWhole, withoutLoopback } from "./key-refusal.js";
12
12
  import { structuredAnswer } from "./answer-json.js";
13
13
  import { isObject } from "./validate.js";
14
14
  import { currentLearning, holdsForOk, learningView, LEARNING_LABEL, secretsShown, shortOf } from "./learning.js";
@@ -266,7 +266,7 @@ async function storeRunIn(store, runId, deps, cut, since) {
266
266
  // Its final answer whole (store-reads/journal.ts wholeAnswers), as main served a run's answer: a row's cut is no answer's.
267
267
  // A run that ended reads settled, and its usage row says its cost ("Cost: …"), never what it has cost so far. One
268
268
  // looking back is still going: its look-back's rows come yet.
269
- const timelineOptions = { settled: terminal && !lookingBack, ended: terminal && !lookingBack, redact: (text) => redacted(text, values) };
269
+ const timelineOptions = { settled: terminal && !lookingBack, ended: terminal && !lookingBack, redact: (text) => redacted(text, values), holds: (text) => withheldWhole(text, values) };
270
270
  // Rendered from the records read above, so its usage row and the cost's `plan` (bookedSpend over the same entries) are
271
271
  // of one read.
272
272
  const timeline = withAsks(await wholeAnswers(store, runId, context, await runTimeline(store, runId, context, timelineOptions, records), timelineOptions, wholeAnswerFor(values), since));
@@ -788,7 +788,7 @@ export async function factsOverStore(store, runId, deps) {
788
788
  }
789
789
  /** A run's live moment from the store (momentOf), for the one acceptance each act a run takes reads. A run no runner holds
790
790
  * (ended, or running with no live claim) reads live false. */
791
- export async function momentOverStore(store, runId, deps = { origin: "", serverSecrets: () => [] }) {
791
+ export async function momentOverStore(store, runId, deps = { origin: "", serverSecrets: () => [], sealKey: undefined }) {
792
792
  const run = await storeRunOf(store, runId, deps);
793
793
  if (!run)
794
794
  return undefined;
@@ -18,6 +18,7 @@
18
18
  // server's, made when a person presses Create, and its token is never the run's. Decisions are kept in the store's
19
19
  // settings (suggestions.item.<id>, suggestions.scan.<repo>), so every server on one store sees the same list.
20
20
  import { createHash, randomUUID } from "node:crypto";
21
+ import { API_KEYS_PAGE } from "./api-keys.js";
21
22
  import { ApiError, invalid } from "./errors.js";
22
23
  import { githubCall } from "./github.js";
23
24
  import { deleteBranch, GithubWriteRefused, openPull, pushFiles } from "./github-pull-request.js";
@@ -271,7 +272,7 @@ function header(s, repo, commit, mark) {
271
272
  `wire it in at ${oneLine(s.integration.call_site.path)}:${s.integration.call_site.line}. ${oneLine(s.integration.call_site.note)}`,
272
273
  "",
273
274
  "Configure in the app's environment (never commit the key):",
274
- ...[["AGENTRUN_URL", "the AgentRun server, like https://agentrun.example.com"], ["AGENTRUN_API_KEY", "an API key of that server"], [agentVariable(s.key), "the agent's id there (the pull request that added this file names it)"]].map(([name, what], _, all) => ` ${name.padEnd(Math.max(...all.map(([n]) => n.length)) + 2)}${what}`),
275
+ ...[["AGENTRUN_URL", "the AgentRun server, like https://agentrun.example.com"], ["AGENTRUN_API_KEY", "an API key of that server (make one in its console: Settings > AgentRun API keys)"], [agentVariable(s.key), "the agent's id there (the pull request that added this file names it)"]].map(([name, what], _, all) => ` ${name.padEnd(Math.max(...all.map(([n]) => n.length)) + 2)}${what}`),
275
276
  ];
276
277
  return lines.map((line) => (line ? `${mark} ${line}` : mark)).join("\n");
277
278
  }
@@ -443,7 +444,7 @@ The app's own code is not changed: nothing calls the agent until you wire it in.
443
444
  | Variable | Value |
444
445
  | --- | --- |
445
446
  | \`AGENTRUN_URL\` | ${at.publicUrl ? `\`${at.publicUrl}\`` : "your AgentRun server's address"} |
446
- | \`AGENTRUN_API_KEY\` | an API key of that server: keep it in your secrets, never in the repository |
447
+ | \`AGENTRUN_API_KEY\` | an API key of that server, made in its console under ${at.publicUrl ? `[Settings → AgentRun API keys](${at.publicUrl.replace(/\/+$/, "")}${API_KEYS_PAGE})` : "Settings → AgentRun API keys"} and shown once: keep it in your secrets, never in the repository |
447
448
  | \`${agentVariable(s.key)}\` | \`${at.agentId}\` |
448
449
 
449
450
  The agent is already made on the AgentRun server as \`${at.agentId}\`, from these same files: try it there before you merge.
@@ -18,8 +18,8 @@ export declare const GRADER_CAP_USD = 0.5;
18
18
  export declare const GRADER_PROMPT_MAX = 120000;
19
19
  /** How long one run may take before the eval cancels it and fails it. */
20
20
  export declare const RUN_TIMEOUT_MS: number;
21
- /** How long a run may stay queued, no runner having taken it, before the eval stops waiting on it: it fails by that
22
- * name, its state when the wait gave up, never by the run's whole timeout. */
21
+ /** How long a run may stay queued, no runner holding it, before the eval stops waiting on it: it fails by that name,
22
+ * never by the run's whole timeout. 5 minutes: a busy machine's runner can be slow to make its first claim. */
23
23
  export declare const QUEUE_TIMEOUT_MS: number;
24
24
  export declare const GRADER_NAME = "Template eval grader";
25
25
  /** The folder under TMPDIR where local evals keep the one install of each harness's pin they all share. */
@@ -67,8 +67,9 @@ export type Grader = ({
67
67
  /** An email case's layouts this grader grades the runs of; absent, every run. */
68
68
  layouts?: Layout[];
69
69
  };
70
- /** One answer of a fake tool: taken when every argument `when` lists equals the call's; `when` a list, when any one of
71
- * its entries does (one answer for each spelling of a call: a file by `sha` or by `ref`, say). */
70
+ /** One answer of a fake tool: taken when every argument `when` lists equals the call's, or, listed as `{"$pattern":
71
+ * <regex>}`, is a string the regex matches whole; `when` a list, when any one of its entries does (one answer for each
72
+ * spelling of a call: a file by `sha` or by `ref`, say). */
72
73
  type Answer = {
73
74
  when: Json | Json[];
74
75
  result: Json;
@@ -139,6 +140,9 @@ export type EvalCase = {
139
140
  /** The case's previous runs (eval-previous.ts): each run's agent gets them seeded as completed runs of the package's
140
141
  * schedule trigger, which then starts the run as it would, handing it the last one's result. */
141
142
  previous?: PreviousFixture;
143
+ /** The files each run's work folder holds before its first turn (`files:`, a path in the folder to its text): the eval's
144
+ * own runner writes them at the claim (EvalFakes.files), so a case can start where an earlier run left off. */
145
+ files?: Record<string, string>;
142
146
  };
143
147
  /** Cases that do not check: every problem, each naming its file. */
144
148
  export declare class CaseError extends Error {
@@ -164,9 +168,11 @@ export type ToolCall = {
164
168
  result?: string | null;
165
169
  arguments?: Json;
166
170
  };
167
- /** A file a run left in its work folder: its path, its size in bytes and, for a text file read whole, its text. */
171
+ /** A file a run left in its work folder, as a grader is told of it: its name (its path under the run's cut, the listing's
172
+ * `name`; absent from a server that doesn't cut its listing's names, when the file is shown by no name, never its path),
173
+ * its size in bytes and, for a text file read whole, its text. */
168
174
  export type FinalFile = {
169
- path: string;
175
+ name?: string;
170
176
  bytes: number;
171
177
  text?: string;
172
178
  };
@@ -229,7 +235,8 @@ export declare function fitCalls(lines: readonly {
229
235
  /** A run's final files in at most `room` characters: each text file in a <file> block, whole when they all fit; else each
230
236
  * text past a length L keeps its head and tail with its middle cut and marked, L the longest that fits (so the largest
231
237
  * is cut first); else every text left out. A file with no text (media, a binary, one past what was read) is named with
232
- * its size on a last line, cut to the room when even that passes it. */
238
+ * its size on a last line, cut to the room when even that passes it. Each file is named by its cut name alone: one with
239
+ * none is in a block with no path, or counted. */
233
240
  export declare function fitFiles(files: readonly FinalFile[], room: number): string;
234
241
  /** A grader run's answer read as its verdict: its json block's (jsonBlockOf), else the last flat JSON object's, {pass, reason}. */
235
242
  export declare function verdictOf(answer: string): {
@@ -262,16 +269,39 @@ export type Api = (method: string, path: string, body?: unknown, headers?: Recor
262
269
  export declare function apiOf(baseUrl: string, token: string): Api;
263
270
  /** How long the run read that asks whether a runner holds a queued run may take. */
264
271
  export declare const CLAIM_READ_TIMEOUT_MS = 10000;
272
+ /** The least time between two of those reads of one run. */
273
+ export declare const CLAIM_READ_EVERY_MS = 5000;
274
+ /** How long that read may take: its wait, and 10 s for the answer to arrive. */
275
+ export declare const PAGE_READ_TIMEOUT_MS: number;
276
+ /** The bound of a read in waitRun made at `now`: `capMs`, or the time left to `deadline` when that is less (`ms`, whole
277
+ * milliseconds and never below 0, as AbortSignal.timeout takes them), and whether the time left is what bounds it
278
+ * (`atDeadline`). */
279
+ export declare function readBound(deadline: number, capMs: number, now: number): {
280
+ ms: number;
281
+ atDeadline: boolean;
282
+ };
283
+ /** A run waited for: its rows until it ends (completed, failed, cancelled) or waits on a person (input_required), or
284
+ * `deadline` passes (then it is cancelled). A stop of the eval (`signal`) cancels it too, and throws. Each of its reads
285
+ * ends at the deadline and at the stop (bounded), so a server that stalls one never holds the wait past either.
286
+ * Exported for its tests. */
287
+ export declare function waitRun(api: Api, runId: string, deadline: number, signal?: AbortSignal, queueTimeoutMs?: number): Promise<{
288
+ status: string;
289
+ rows: Json[];
290
+ waiting?: string;
291
+ why?: string;
292
+ }>;
265
293
  /** A run's tool calls, each named as a grader names it: the gate's own rule (RunGate.enter), its settings key, but a
266
294
  * shell tool held to bash's setting (bash_background, bash_output, ...) keeps its own name, so its grader sees it. A
267
295
  * call on a saved server `toolkits` names ({<saved server>: <the package's toolkit>}, a need an owner's server filled
268
296
  * under another name) is named on the package's toolkit, as the package's graders name it. Each with its arguments and
269
297
  * its output as the rows of a calls=whole read carry them (tool_input, tool_result_text), else its previews. */
270
298
  export declare function callsOf(rows: readonly Json[], harness: string, toolkits?: Readonly<Record<string, string>>): ToolCall[];
271
- /** A file of a run's work folder as its listing names it: its size, its type (null for an extension the server does not
272
- * type) and whether the server could read it. */
299
+ /** A file of a run's work folder as its listing names it: its path (for this eval's own reads, never a grader's prompt),
300
+ * its name under the run's cut (the listing's `name`, absent from a server that doesn't cut it), its size, its type
301
+ * (null for an extension the server does not type) and whether the server could read it. */
273
302
  export type Listed = {
274
303
  path: string;
304
+ name?: string;
275
305
  bytes: number;
276
306
  type: string | null;
277
307
  unreadable: boolean;
@@ -3,7 +3,8 @@
3
3
  // Everything goes through the v2 API alone, on an in-process server over a temp data directory by default (an eval never
4
4
  // touches the owner's server) or on one named by its address and token. Per case: a fake MCP server per `mcp` fixture,
5
5
  // saved under its name with no credential and recording every call; the package applied with the case's parameters and
6
- // grants, a fresh agent per run, its learning seeded from the case's corrections; one run per `runs` with the prompt's body as
6
+ // grants, a fresh agent per run, its learning seeded from the case's corrections and its work folder from the case's
7
+ // files; one run per `runs` with the prompt's body as
7
8
  // its input and the case's cap, on the case's clock when it sets one (`now`), waited for; then its answer, its tool calls (its timeline read with calls=whole, each
8
9
  // call's arguments and its output whole, to CALL_RESULT_CHARS, through the run's redaction, and the fakes' own logs) and its files, graded, and held to the package's output schema when it declares one (outputVerdict,
9
10
  // the server's own verdict). Every grader is deterministic but `llm`, which is itself a run on the same
@@ -38,6 +39,7 @@ import { WEB_SEARCH_TOOL } from "./web-search.js";
38
39
  import { dayIn, serverZone } from "./environment.js";
39
40
  import { instantOf } from "./trigger-adapter.js";
40
41
  import { applyBodyOf, compiled, filledPins, filledSource, onServerName, onServers, packageView, readPackage } from "./templates.js";
42
+ import { INPUTS_DIR } from "./uploads.js";
41
43
  import { inputIssues, inputSchemaOf, isObject, MODEL_REF } from "./validate.js";
42
44
  /** What a grader run is told, whatever the rubric: blind, strict, and its verdict as one JSON block. */
43
45
  export const GRADER_INSTRUCTIONS = `You grade one run of an AI agent against one rubric. You see the rubric, the task the agent was given, its answer, and the tool calls it made; nothing else, and nothing else matters.
@@ -58,16 +60,16 @@ export const GRADER_CAP_USD = 0.5;
58
60
  export const GRADER_PROMPT_MAX = 120_000;
59
61
  /** How long one run may take before the eval cancels it and fails it. */
60
62
  export const RUN_TIMEOUT_MS = 30 * 60_000;
61
- /** How long a run may stay queued, no runner having taken it, before the eval stops waiting on it: it fails by that
62
- * name, its state when the wait gave up, never by the run's whole timeout. */
63
- export const QUEUE_TIMEOUT_MS = 2 * 60_000;
63
+ /** How long a run may stay queued, no runner holding it, before the eval stops waiting on it: it fails by that name,
64
+ * never by the run's whole timeout. 5 minutes: a busy machine's runner can be slow to make its first claim. */
65
+ export const QUEUE_TIMEOUT_MS = 5 * 60_000;
64
66
  export const GRADER_NAME = "Template eval grader";
65
67
  /** The folder under TMPDIR where local evals keep the one install of each harness's pin they all share. */
66
68
  export const EVAL_HARNESSES = "agentrun-eval-harnesses";
67
69
  /** An owner's data folder is the eval's own server's to open (EvalOptions.data): a named server keeps its own. */
68
70
  export const ON_DATA_WITH_SERVER = "--on-data is the data folder of the eval's own server, and --server names another server: give one of them";
69
71
  const PROMPT_FIELDS = ["description", "runs", "max_cost_usd", "input"];
70
- const CASE_FIELDS = ["parameters", "grants", "mcp", "web", "monid", "learning", "now", "email", "calendar", "feed", "previous"];
72
+ const CASE_FIELDS = ["parameters", "grants", "mcp", "web", "monid", "learning", "now", "email", "calendar", "feed", "previous", "files"];
71
73
  const GRADER_FIELDS = {
72
74
  llm: ["type", "target"],
73
75
  regex: ["type", "pattern", "flags", "expect", "target"],
@@ -84,9 +86,12 @@ const LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule each fake MCP server li
84
86
  /** A host name on this machine: a case with fake MCP servers needs a server here, which reaches them on loopback. */
85
87
  const LOOPBACK_HOST = /^(?:127\.\d+\.\d+\.\d+|localhost|\[::1\])$/; // key-gate: loopback-rule a server on this machine reaches the fakes
86
88
  /** A case's fields that the eval's own runner alone binds (EvalFakes), each with what it does: a named server refuses them. */
87
- const OWN_SERVER_FAKES = [["web", "web fakes the web tools"], ["now", "now sets its runs' clock"], ["monid", "monid fakes the package's monid endpoints"], ["email", "email fakes the server's email account"], ["calendar", "calendar fakes the server's calendar"], ["feed", "feed fakes the package's feeds"], ["previous", "previous seeds the case's earlier runs in the server's store"]];
89
+ const OWN_SERVER_FAKES = [["web", "web fakes the web tools"], ["now", "now sets its runs' clock"], ["monid", "monid fakes the package's monid endpoints"], ["email", "email fakes the server's email account"], ["calendar", "calendar fakes the server's calendar"], ["feed", "feed fakes the package's feeds"], ["previous", "previous seeds the case's earlier runs in the server's store"], ["files", "files seeds its runs' work folders"]];
88
90
  /** A case's run input: its prompt's body as content (none when empty), then its typed fields. */
89
91
  export const runInput = (content, fields) => ({ ...(content ? { content } : {}), ...fields });
92
+ /** The regex a `when` value matches by, when it is `{"$pattern": <regex>}` and nothing else: anchored here, so a key
93
+ * made of a run's random stem (ns-k7m2p9qa-voice-cold-open) matches whole, never by a prefix the author left open. */
94
+ const patternOf = (value) => (isObject(value) && Object.keys(value).length === 1 && typeof value.$pattern === "string" ? new RegExp(`^(?:${value.$pattern})$`) : undefined);
90
95
  /** Cases that do not check: every problem, each naming its file. */
91
96
  export class CaseError extends Error {
92
97
  dir;
@@ -156,6 +161,31 @@ function fixtureOf(text, name, at, bad) {
156
161
  bad(`${at}: tools.${tool} is {description, input: an object's JSON Schema, answers: [{when: {...} or [{...}, ...], result: an MCP tool result}], default?: a result, search?: {query: the argument's name, files: [{path, text}], limit?, note?}}`);
157
162
  continue;
158
163
  }
164
+ // A `when` value that names $pattern is a regex over the call's argument: one that is no string, does not compile, or
165
+ // sits beside another key would be compared by equality and match nothing, so it fails here, not as a silent miss.
166
+ for (const [i, answer] of answers.entries()) {
167
+ const whens = Array.isArray(answer.when) ? answer.when.map((when, j) => [`[${j}]`, when]) : [["", answer.when]];
168
+ for (const [j, when] of whens) {
169
+ for (const [key, value] of Object.entries(when)) {
170
+ if (!isObject(value) || !Object.hasOwn(value, "$pattern"))
171
+ continue;
172
+ const where = `${at}: tools.${tool}.answers[${i}].when${j}.${key}`;
173
+ const others = Object.keys(value).filter((name) => name !== "$pattern");
174
+ if (others.length)
175
+ bad(`${where}: a {"$pattern": ...} value holds no other key, and this one holds ${others.join(", ")}`);
176
+ else if (typeof value.$pattern !== "string")
177
+ bad(`${where}: $pattern is a regular expression's source, a string`);
178
+ else {
179
+ try {
180
+ new RegExp(value.$pattern);
181
+ }
182
+ catch (error) {
183
+ bad(`${where}: its $pattern does not compile: ${error.message}`);
184
+ }
185
+ }
186
+ }
187
+ }
188
+ }
159
189
  tools[tool] = { description: spec.description, input: spec.input, answers: answers, ...(isObject(spec.default) ? { default: spec.default } : {}), ...(isObject(spec.search) ? { search: spec.search } : {}) };
160
190
  }
161
191
  return { server: value.server, description: value.description, tools };
@@ -521,6 +551,29 @@ export function readCases(dir, names) {
521
551
  if (body || fields || f.max_cost_usd !== undefined)
522
552
  bad(`${at}/prompt.md: a previous case's run is started by the package's schedule trigger, on the trigger's input and cap: its prompt.md holds description and runs alone`);
523
553
  }
554
+ // The case's files: each run's work folder holds them before its first turn, as a run that resumes finds what the run
555
+ // before it left (a keys file, say). Text only, each path in the folder and outside inputs/, which the server fills
556
+ // with the run's uploads and its message.
557
+ let files;
558
+ if (c.files !== undefined) {
559
+ if (!isObject(c.files))
560
+ bad(`${at}/case.yaml: files is a mapping of a path in the run's work folder to the text that file starts with`);
561
+ else {
562
+ files = {};
563
+ for (const [path, text] of Object.entries(c.files)) {
564
+ const shown = JSON.stringify(path);
565
+ if (!path || path.startsWith("/") || /[\\\0]/.test(path) || path.split("/").some((part) => part === "" || part === "." || part === ".."))
566
+ bad(`${at}/case.yaml: files: ${shown} is not a path in the run's work folder (relative, with no empty, . or .. segment)`);
567
+ else if (path.split("/")[0] === INPUTS_DIR)
568
+ bad(`${at}/case.yaml: files: ${shown} is under ${INPUTS_DIR}/, where the server puts the run's uploads and its message`);
569
+ else if (typeof text !== "string")
570
+ bad(`${at}/case.yaml: files: ${shown} is the file's text, a string`);
571
+ // An own property, so a path such as __proto__ is a file, never the object's prototype.
572
+ else
573
+ Object.defineProperty(files, path, { value: text, writable: true, enumerable: true, configurable: true });
574
+ }
575
+ }
576
+ }
524
577
  let learning;
525
578
  if (c.learning !== undefined) {
526
579
  const file = inside(root, c.learning, "file");
@@ -557,7 +610,7 @@ export function readCases(dir, names) {
557
610
  cases.push({
558
611
  name, description: typeof f.description === "string" ? f.description : "", runs: typeof f.runs === "number" ? f.runs : 1,
559
612
  ...(typeof f.max_cost_usd === "number" ? { maxCostUsd: f.max_cost_usd } : {}), input: body, ...(fields ? { fields } : {}),
560
- parameters, grants, mcp, ...(web ? { web } : {}), ...(monid ? { monid } : {}), ...(learning !== undefined ? { learning } : {}), graders, ...(typeof c.now === "string" ? { now: c.now } : {}), ...(email ? { email } : {}), ...(calendar ? { calendar } : {}), ...(feed ? { feed } : {}), ...(previous ? { previous } : {}),
613
+ parameters, grants, mcp, ...(web ? { web } : {}), ...(monid ? { monid } : {}), ...(learning !== undefined ? { learning } : {}), graders, ...(typeof c.now === "string" ? { now: c.now } : {}), ...(email ? { email } : {}), ...(calendar ? { calendar } : {}), ...(feed ? { feed } : {}), ...(previous ? { previous } : {}), ...(files ? { files } : {}),
561
614
  });
562
615
  }
563
616
  if (problems.length)
@@ -586,7 +639,12 @@ export function fakeAnswer(fixture, tool, args) {
586
639
  const spec = fixture.tools[tool];
587
640
  if (!spec)
588
641
  return { isError: true, content: [{ type: "text", text: `The fake ${fixture.server} has no tool ${tool}.` }] };
589
- const matches = (when) => Object.entries(when).every(([key, value]) => Object.hasOwn(args, key) && same(args[key], value));
642
+ const matches = (when) => Object.entries(when).every(([key, value]) => {
643
+ if (!Object.hasOwn(args, key))
644
+ return false;
645
+ const pattern = patternOf(value);
646
+ return pattern ? typeof args[key] === "string" && pattern.test(args[key]) : same(args[key], value);
647
+ });
590
648
  const hit = spec.answers.find((answer) => (Array.isArray(answer.when) ? answer.when.some(matches) : matches(answer.when)));
591
649
  if (hit)
592
650
  return hit.result;
@@ -733,8 +791,8 @@ export function graderInput(grader, input, run, max = GRADER_PROMPT_MAX) {
733
791
  const lines = run.calls.map((call, i) => {
734
792
  const head = `${i + 1}. ${call.tool}${call.arguments ? ` ${JSON.stringify(call.arguments)}` : call.preview ? ` (${call.preview})` : ""}${call.status ? ` -> ${call.status}` : ""}`;
735
793
  const result = call.result ?? "";
736
- const named = texts.filter((file) => head.includes(file.path) || result.includes(file.path)).sort((a, b) => b.path.length - a.path.length)[0];
737
- return { head: named ? `${head} [the file ${named.path} is in <files>, whole unless marked cut]` : head, result, tool: call.name ?? call.tool };
794
+ const named = texts.flatMap((file) => (file.name !== undefined && (head.includes(file.name) || result.includes(file.name)) ? [file.name] : [])).sort((a, b) => b.length - a.length)[0];
795
+ return { head: named ? `${head} [the file ${named} is in <files>, whole unless marked cut]` : head, result, tool: call.name ?? call.tool };
738
796
  });
739
797
  // Each call a fake MCP server received, its arguments whole in its log: they are the part a cut may take.
740
798
  const mcpLines = run.mcpCalls.map((call, i) => ({ head: `${i + 1}. ${call.tool}`, result: JSON.stringify(call.arguments ?? {}) }));
@@ -833,12 +891,13 @@ function middle(text, keep) {
833
891
  /** A run's final files in at most `room` characters: each text file in a <file> block, whole when they all fit; else each
834
892
  * text past a length L keeps its head and tail with its middle cut and marked, L the longest that fits (so the largest
835
893
  * is cut first); else every text left out. A file with no text (media, a binary, one past what was read) is named with
836
- * its size on a last line, cut to the room when even that passes it. */
894
+ * its size on a last line, cut to the room when even that passes it. Each file is named by its cut name alone: one with
895
+ * none is in a block with no path, or counted. */
837
896
  export function fitFiles(files, room) {
838
- const block = (file, text) => `<file path="${file.path}" bytes="${file.bytes}">\n${text}\n</file>`;
897
+ const block = (file, text) => `<file${file.name === undefined ? "" : ` path="${file.name}"`} bytes="${file.bytes}">\n${text}\n</file>`;
839
898
  const texts = files.filter((file) => file.text !== undefined);
840
899
  const others = files.filter((file) => file.text === undefined);
841
- const named = others.length ? [`Not shown (not text, or past what a grader is given), by path and size in bytes: ${others.map((file) => `${file.path} (${file.bytes})`).join(", ")}`] : [];
900
+ const named = others.length ? [`Not shown (not text, or past what a grader is given), by path and size in bytes: ${namesOf(others)}`] : [];
842
901
  const whole = [...texts.map((file) => block(file, file.text)), ...named].join("\n");
843
902
  if (whole.length <= room)
844
903
  return whole;
@@ -855,9 +914,17 @@ export function fitFiles(files, room) {
855
914
  }
856
915
  return [LONG, ...texts.map((file) => block(file, middle(file.text, low))), ...named].join("\n");
857
916
  }
858
- const list = [saidCut("every file's text is left out"), `By path and size in bytes: ${files.map((file) => `${file.path} (${file.bytes})`).join(", ")}`].join("\n");
917
+ const list = [saidCut("every file's text is left out"), `By path and size in bytes: ${namesOf(files)}`].join("\n");
859
918
  return list.length <= room ? list : room < 4 ? "" : `${list.slice(0, room - 4)} ...`;
860
919
  }
920
+ /** Files by their cut names and sizes, "a.mp4 (9000000), b.txt (5)", and those with no name counted after them: a file is
921
+ * never named to a grader by anything but its cut name. */
922
+ function namesOf(files) {
923
+ const named = files.flatMap((file) => (file.name === undefined ? [] : [`${file.name} (${file.bytes})`]));
924
+ const unnamed = files.length - named.length;
925
+ const count = unnamed ? `${unnamed} file${unnamed === 1 ? "" : "s"} not named (this server doesn't cut file names)` : "";
926
+ return named.length && count ? `${named.join(", ")}; and ${count}` : named.length ? named.join(", ") : count;
927
+ }
861
928
  /** A grader run's answer read as its verdict: its json block's (jsonBlockOf), else the last flat JSON object's, {pass, reason}. */
862
929
  export function verdictOf(answer) {
863
930
  const candidates = [jsonBlockOf(answer), ...[...answer.matchAll(/\{[^{}]*"pass"[^{}]*\}/g)].map((m) => m[0]).reverse()];
@@ -973,63 +1040,121 @@ function expectOk(what, answered, ok = [200, 201, 202]) {
973
1040
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
974
1041
  /** How long the run read that asks whether a runner holds a queued run may take. */
975
1042
  export const CLAIM_READ_TIMEOUT_MS = 10_000;
976
- /** Whether a runner holds the run now (the run read's `claim`); undefined when the read fails, takes over
977
- * CLAIM_READ_TIMEOUT_MS or is stopped by `signal` (the eval's stop): not known, so never a reason to cancel the run. */
978
- async function heldNow(api, runId, signal) {
979
- const timeout = AbortSignal.timeout(CLAIM_READ_TIMEOUT_MS);
980
- const read = await api("GET", `/runs/${runId}`, undefined, {}, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout }).catch(() => undefined);
981
- return read?.status === 200 && isObject(read.body) ? isObject(read.body.claim) : undefined;
1043
+ /** The least time between two of those reads of one run. */
1044
+ export const CLAIM_READ_EVERY_MS = 5_000;
1045
+ /** How long a timeline page read asks the server to wait for a new row (its wait_ms). */
1046
+ const PAGE_WAIT_MS = 5_000;
1047
+ /** How long that read may take: its wait, and 10 s for the answer to arrive. */
1048
+ export const PAGE_READ_TIMEOUT_MS = PAGE_WAIT_MS + 10_000;
1049
+ /** The bound of a read in waitRun made at `now`: `capMs`, or the time left to `deadline` when that is less (`ms`, whole
1050
+ * milliseconds and never below 0, as AbortSignal.timeout takes them), and whether the time left is what bounds it
1051
+ * (`atDeadline`). */
1052
+ export function readBound(deadline, capMs, now) {
1053
+ const left = deadline - now;
1054
+ return left < capMs ? { ms: Math.max(0, Math.ceil(left)), atDeadline: true } : { ms: capMs, atDeadline: false };
1055
+ }
1056
+ /** A read in waitRun, bounded as readBound says and by the eval's stop (`stop`): the `signal` its request takes, whether
1057
+ * to `send` it at all (not with no time left), and `byDeadline()`, true once the deadline ended it. The wait takes that
1058
+ * as its end, with no second read of the clock: the timer runs on a monotonic clock in whole milliseconds, and
1059
+ * Date.now() can still read a millisecond short of the deadline when it fires. */
1060
+ function bounded(deadline, capMs, stop) {
1061
+ const { ms, atDeadline } = readBound(deadline, capMs, Date.now());
1062
+ const timeout = AbortSignal.timeout(ms);
1063
+ return { signal: stop ? AbortSignal.any([stop, timeout]) : timeout, send: ms > 0, byDeadline: () => atDeadline && (ms === 0 || timeout.aborted) };
1064
+ }
1065
+ /** Whether a runner holds the run now (the run read's `claim`): "deadline" when the read ran to the run's `deadline`, or
1066
+ * there was no time left to send it; undefined when it fails, takes over CLAIM_READ_TIMEOUT_MS or is stopped by
1067
+ * `signal` (the eval's stop): not known, so never a reason to cancel the run as unheld. */
1068
+ async function heldNow(api, runId, deadline, signal) {
1069
+ const read = bounded(deadline, CLAIM_READ_TIMEOUT_MS, signal);
1070
+ const answered = read.send ? await api("GET", `/runs/${runId}`, undefined, {}, { signal: read.signal }).catch(() => undefined) : undefined;
1071
+ if (read.byDeadline())
1072
+ return "deadline";
1073
+ return answered?.status === 200 && isObject(answered.body) ? isObject(answered.body.claim) : undefined;
982
1074
  }
983
1075
  /** A run waited for: its rows until it ends (completed, failed, cancelled) or waits on a person (input_required), or
984
- * `deadline` passes (then it is cancelled). A stop of the eval (`signal`) cancels it too, and throws. */
985
- async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIMEOUT_MS) {
1076
+ * `deadline` passes (then it is cancelled). A stop of the eval (`signal`) cancels it too, and throws. Each of its reads
1077
+ * ends at the deadline and at the stop (bounded), so a server that stalls one never holds the wait past either.
1078
+ * Exported for its tests. */
1079
+ export async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIMEOUT_MS) {
986
1080
  const view = new Map();
987
1081
  let after = 0;
988
1082
  const started = Date.now();
989
1083
  // A run nobody takes stays queued: given up on once it has gone queueTimeoutMs with no runner holding it, by name, never
990
1084
  // left to the whole deadline. A run's view reads queued until its first rows show, held or not (a slow start on a busy
991
- // machine), so a queued page past the bound asks the run read whether a runner holds it now: one does, and the bound
992
- // starts again from now, so a run a runner keeps holding is waited for to its own deadline. A read that doesn't answer
993
- // (failed, stalled past its bound, or stopped) says neither: it is asked again at the next page, and the stop and the
994
- // deadline still end the wait.
995
- let queuedUntil = started + queueTimeoutMs;
1085
+ // machine), so a queued page past the bound asks the run read whether a runner holds it now. Once one has, every queued
1086
+ // page asks (at most one read in CLAIM_READ_EVERY_MS): a claim can lapse for a moment on a stalled machine (not renewed
1087
+ // in time, then claimed again), so one read that finds none never ends the wait. The run is cancelled only when reads
1088
+ // found no runner holding it from the first such read to one queueTimeoutMs later, none between them finding one. A read
1089
+ // that doesn't answer (failed, stalled past its bound, or stopped) says neither.
1090
+ let unheldSince = started;
1091
+ let everHeld = false;
1092
+ let askedAt = -Infinity;
1093
+ let rows = [];
1094
+ let state;
996
1095
  for (;;) {
997
1096
  if (signal?.aborted) {
998
1097
  await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
999
1098
  signal.throwIfAborted();
1000
1099
  }
1001
1100
  // calls=whole: each call's arguments and its output, whole to CALL_RESULT_CHARS (tool_input, tool_result_text), which its graders read.
1002
- // CALLS_PAGE_ROWS rows a page, the most a calls=whole page holds (an older server's default is 500).
1003
- const page = expectOk(`reading run ${runId}'s timeline`, await api("GET", `/runs/${runId}/timeline?after=${after}&wait_ms=5000&calls=whole&limit=${CALLS_PAGE_ROWS}`));
1004
- if (page.reset)
1005
- view.clear();
1006
- for (const id of page.drop ?? [])
1007
- view.delete(id);
1008
- for (const row of page.rows ?? [])
1009
- view.set(String(row.id), row);
1010
- after = Number(page.next_after ?? after);
1011
- const rows = [...view.values()].sort((a, b) => Number(a.seq ?? 0) - Number(b.seq ?? 0));
1012
- const status = String(page.status);
1013
- if (ENDED.includes(status) && page.final && !page.has_more)
1014
- return { status, rows };
1015
- if (status === "input_required" && !page.has_more) {
1016
- const waiting = rows.findLast((row) => row.kind === "waiting");
1017
- return { status, rows, waiting: typeof waiting?.summary === "string" ? waiting.summary : "it waits on a person" };
1018
- }
1019
- if (status === "queued" && Date.now() > queuedUntil) {
1020
- const held = await heldNow(api, runId, signal);
1021
- if (held === true)
1022
- queuedUntil = Date.now() + queueTimeoutMs;
1023
- else if (held === false) {
1024
- await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1025
- return { status: "timed_out", rows, why: `the run stayed queued for ${Math.round(queueTimeoutMs / 1000)} s with no runner holding it, and it was cancelled` };
1101
+ // CALLS_PAGE_ROWS rows a page, the most a calls=whole page holds (an older server's default is 500). A page its bound
1102
+ // cut (stalled past PAGE_READ_TIMEOUT_MS, run to the deadline, or stopped) is no page: it is asked again, unless the
1103
+ // stop or the deadline below ends the wait.
1104
+ const read = bounded(deadline, PAGE_READ_TIMEOUT_MS, signal);
1105
+ const answered = read.send
1106
+ ? await api("GET", `/runs/${runId}/timeline?after=${after}&wait_ms=${PAGE_WAIT_MS}&calls=whole&limit=${CALLS_PAGE_ROWS}`, undefined, {}, { signal: read.signal }).catch((error) => {
1107
+ if (read.signal.aborted)
1108
+ return undefined;
1109
+ throw error;
1110
+ })
1111
+ : undefined;
1112
+ let timedOut = read.byDeadline();
1113
+ const page = answered === undefined ? undefined : expectOk(`reading run ${runId}'s timeline`, answered);
1114
+ if (page) {
1115
+ if (page.reset)
1116
+ view.clear();
1117
+ for (const id of page.drop ?? [])
1118
+ view.delete(id);
1119
+ for (const row of page.rows ?? [])
1120
+ view.set(String(row.id), row);
1121
+ after = Number(page.next_after ?? after);
1122
+ rows = [...view.values()].sort((a, b) => Number(a.seq ?? 0) - Number(b.seq ?? 0));
1123
+ state = page.state;
1124
+ const status = String(page.status);
1125
+ if (ENDED.includes(status) && page.final && !page.has_more)
1126
+ return { status, rows };
1127
+ if (status === "input_required" && !page.has_more) {
1128
+ const waiting = rows.findLast((row) => row.kind === "waiting");
1129
+ return { status, rows, waiting: typeof waiting?.summary === "string" ? waiting.summary : "it waits on a person" };
1130
+ }
1131
+ if (status === "queued" && (everHeld || Date.now() - started > queueTimeoutMs) && Date.now() - askedAt >= CLAIM_READ_EVERY_MS) {
1132
+ askedAt = Date.now();
1133
+ const held = await heldNow(api, runId, deadline, signal);
1134
+ if (held === "deadline")
1135
+ timedOut = true;
1136
+ else if (held === true) {
1137
+ everHeld = true;
1138
+ unheldSince = undefined;
1139
+ }
1140
+ else if (held === false) {
1141
+ unheldSince ??= askedAt;
1142
+ if (Date.now() - unheldSince >= queueTimeoutMs) {
1143
+ await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1144
+ return { status: "timed_out", rows, why: `the run stayed queued for ${Math.round(queueTimeoutMs / 1000)} s with no runner holding it, and it was cancelled` };
1145
+ }
1146
+ }
1026
1147
  }
1027
1148
  }
1028
- if (Date.now() > deadline) {
1029
- await api("POST", `/runs/${runId}/cancel`, {});
1030
- return { status: "timed_out", rows, why: `the run took longer than ${Math.round((deadline - started) / 1000)} s (state ${String(page.state)} when the wait gave up) and was cancelled` };
1149
+ if (signal?.aborted)
1150
+ continue;
1151
+ // A read the deadline ended, or the clock at the deadline, not only past it. A cancel that fails is sent again once the
1152
+ // wait's answer is settled (settle cancels a run not ended): the wait still ends timed out.
1153
+ if (timedOut || Date.now() >= deadline) {
1154
+ await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1155
+ return { status: "timed_out", rows, why: `the run took longer than ${Math.round((deadline - started) / 1000)} s (state ${String(state ?? "unknown")} when the wait gave up) and was cancelled` };
1031
1156
  }
1032
- if (page.has_more !== true && page.unchanged === true)
1157
+ if (page?.has_more !== true && page?.unchanged === true)
1033
1158
  await sleep(250);
1034
1159
  }
1035
1160
  }
@@ -1050,16 +1175,16 @@ export function callsOf(rows, harness, toolkits = {}) {
1050
1175
  return { tool: shellToolOf(name) ?? (key === undefined ? undefined : onServerName(key, toolkits)) ?? name, name, preview: row.tool_input_preview ?? null, ...(isObject(row.tool_input) ? { arguments: row.tool_input } : {}), status: result?.tool_status ?? null, result: output };
1051
1176
  });
1052
1177
  }
1053
- /** Every file of a run's work folder (the files route, page by page). */
1178
+ /** Every file of a run's work folder (the files route, page by page), each with its name under the run's cut (`?cut=run`). */
1054
1179
  async function filesOf(api, runId) {
1055
1180
  const files = [];
1056
1181
  for (let cursor = null;;) {
1057
- const page = await api("GET", `/runs/${runId}/files${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`);
1182
+ const page = await api("GET", `/runs/${runId}/files?cut=run${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
1058
1183
  if (page.status !== 200 || !isObject(page.body))
1059
1184
  return files;
1060
1185
  for (const file of page.body.files ?? []) {
1061
1186
  if (typeof file.path === "string")
1062
- files.push({ path: file.path, bytes: typeof file.size_bytes === "number" ? file.size_bytes : 0, type: typeof file.content_type === "string" ? file.content_type : null, unreadable: file.unreadable === true });
1187
+ files.push({ path: file.path, ...(typeof file.name === "string" ? { name: file.name } : {}), bytes: typeof file.size_bytes === "number" ? file.size_bytes : 0, type: typeof file.content_type === "string" ? file.content_type : null, unreadable: file.unreadable === true });
1063
1188
  }
1064
1189
  cursor = typeof page.body.next_cursor === "string" ? page.body.next_cursor : null;
1065
1190
  if (!cursor)
@@ -1108,7 +1233,8 @@ export async function finalFilesOf(api, runId, listed, signal, readTimeoutMs = F
1108
1233
  texts.set(file.path, read.body);
1109
1234
  left -= bytes;
1110
1235
  }
1111
- return listed.map((file) => ({ path: file.path, bytes: file.bytes, ...(texts.has(file.path) ? { text: texts.get(file.path) } : {}) }));
1236
+ // Each by its cut name alone: its path is for the reads above, never a grader.
1237
+ return listed.map((file) => ({ ...(file.name !== undefined ? { name: file.name } : {}), bytes: file.bytes, ...(texts.has(file.path) ? { text: texts.get(file.path) } : {}) }));
1112
1238
  }
1113
1239
  /** Each path a file_exists grader names that the run's work folder holds, read one by one (GET /runs/{id}/files/{path}):
1114
1240
  * the listing is capped (its `truncated`), so a file past its cap or depth is never taken for absent. Only the status
@@ -1157,6 +1283,11 @@ export async function evalTemplate(options) {
1157
1283
  const log = options.log ?? (() => undefined);
1158
1284
  if (options.data !== undefined && options.server)
1159
1285
  throw new Error(ON_DATA_WITH_SERVER);
1286
+ // A NaN bound would never end a wait (no clock reads past it); a fraction of a millisecond is rounded up (readBound).
1287
+ for (const [name, ms] of [["runTimeoutMs", options.runTimeoutMs], ["queueTimeoutMs", options.queueTimeoutMs]]) {
1288
+ if (ms !== undefined && !(Number.isFinite(ms) && ms > 0))
1289
+ throw new RangeError(`${name} is a time in milliseconds over 0, not ${ms}`);
1290
+ }
1160
1291
  const { pkg, cases } = readCases(options.dir, options.cases);
1161
1292
  if (options.graderModel !== undefined && !MODEL_REF.test(options.graderModel))
1162
1293
  throw new CaseError(options.dir, [`--grader-model is "provider/model-id", not ${options.graderModel}`]);
@@ -1572,7 +1703,7 @@ async function runOnce(ctx, one, n, fakes, mail, feeds) {
1572
1703
  }
1573
1704
  stopped();
1574
1705
  // The case's fakes, for this run's agent alone, before its run can be claimed.
1575
- ctx.fakes.set(agentId, { ...(one.web !== undefined ? { web: one.web } : {}), ...(one.now !== undefined ? { now: new Date(instantOf(one.now)) } : {}), ...(one.monid !== undefined ? { monid: one.monid } : {}), ...(mail ? { email: { imap: mail.faux.imap, smtp: mail.faux.smtp, kind: mail.layout } } : {}) });
1706
+ ctx.fakes.set(agentId, { ...(one.web !== undefined ? { web: one.web } : {}), ...(one.now !== undefined ? { now: new Date(instantOf(one.now)) } : {}), ...(one.monid !== undefined ? { monid: one.monid } : {}), ...(mail ? { email: { imap: mail.faux.imap, smtp: mail.faux.smtp, kind: mail.layout } } : {}), ...(one.files ? { files: one.files } : {}) });
1576
1707
  let runId;
1577
1708
  let fired;
1578
1709
  if (via !== undefined && kept) {
@@ -23,8 +23,8 @@ const uploadSha = (files) => packageSha256([...files].map(([path, data]) => ({ p
23
23
  const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
24
24
  /** A path part that is not plain, or a character no package path holds (a control character, a backslash). */
25
25
  const NOT_PLAIN = (path) => /[\0-\x1f\x7f\\]/.test(path) || path.split("/").some((part) => part === "" || part === "." || part === "..");
26
- /** An upload's files ({path, encoding, content}) as the package's bytes by path: 422 under files.<i> for one that is not
27
- * that shape; the GitHub import's own refusals (ImportRefused "package") for a path that is not plain or is there twice,
26
+ /** An upload's files ({path, encoding, content}) as the package's bytes by path, each hidden path left out: 422 under
27
+ * files.<i> for one that is not that shape; the GitHub import's own refusals (ImportRefused "package") for a path that is not plain or is there twice,
28
28
  * over its count and over the bytes it keeps. */
29
29
  function uploadFiles(raw) {
30
30
  const shape = "files is a list of {path, encoding, content}: each file of the package, its encoding utf8 or base64";
@@ -52,6 +52,10 @@ function uploadFiles(raw) {
52
52
  for (const [path, data] of read) {
53
53
  if (NOT_PLAIN(path))
54
54
  throw new ImportRefused("package", `The package holds ${JSON.stringify(path)}, a path that is not plain: refused.`);
55
+ // A hidden file or folder (.env, .DS_Store, .cache/) is no part of a package (templates.ts reads none): left out here,
56
+ // before anything is counted, stored or hashed, so a client's .env is never kept.
57
+ if (path.split("/").some((part) => part.startsWith(".")))
58
+ continue;
55
59
  if (files.has(path))
56
60
  throw new ImportRefused("package", `The package holds ${JSON.stringify(path)} twice: refused.`);
57
61
  kept += data.length;