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

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 (275) hide show
  1. package/CHANGELOG.md +229 -0
  2. package/README.md +201 -52
  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 +17 -5
  11. package/dist/api-only.js +34 -8
  12. package/dist/browser-hold.d.ts +23 -0
  13. package/dist/browser-hold.js +48 -0
  14. package/dist/browser-person.d.ts +3 -0
  15. package/dist/browser-person.js +4 -1
  16. package/dist/chatgpt-plan.d.ts +18 -8
  17. package/dist/chatgpt-plan.js +91 -34
  18. package/dist/claude-login.d.ts +74 -16
  19. package/dist/claude-login.js +215 -56
  20. package/dist/claude-sign-in.d.ts +17 -6
  21. package/dist/claude-sign-in.js +42 -39
  22. package/dist/cli.js +63 -6
  23. package/dist/composio-made.d.ts +4 -0
  24. package/dist/composio-made.js +4 -0
  25. package/dist/composio-preset.d.ts +43 -2
  26. package/dist/composio-preset.js +92 -4
  27. package/dist/computer-held-routes.d.ts +5 -4
  28. package/dist/computer-held-routes.js +29 -8
  29. package/dist/computer-held.d.ts +6 -1
  30. package/dist/computer-held.js +14 -0
  31. package/dist/computer-record.js +4 -2
  32. package/dist/computer-viewer.js +4 -1
  33. package/dist/console/assets/{backend-Boh7tC4i.js → backend-DVhHzJX2.js} +19 -19
  34. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  35. package/dist/console/assets/index-okP-y8PK.js +747 -0
  36. package/dist/console/index.html +2 -2
  37. package/dist/decisions.d.ts +1 -1
  38. package/dist/decisions.js +1 -1
  39. package/dist/docker-host-addresses.d.ts +22 -11
  40. package/dist/docker-host-addresses.js +38 -26
  41. package/dist/env-switch.d.ts +10 -0
  42. package/dist/env-switch.js +33 -2
  43. package/dist/errors.d.ts +1 -0
  44. package/dist/errors.js +2 -0
  45. package/dist/fal-price.d.ts +58 -20
  46. package/dist/fal-price.js +341 -82
  47. package/dist/handed-values.d.ts +43 -1
  48. package/dist/handed-values.js +119 -2
  49. package/dist/harness-archive.d.ts +13 -10
  50. package/dist/harness-archive.js +60 -34
  51. package/dist/harness-check.d.ts +3 -1
  52. package/dist/harness-check.js +25 -46
  53. package/dist/harness-keys.d.ts +73 -27
  54. package/dist/harness-keys.js +194 -61
  55. package/dist/harness-recipe-entry.d.ts +8 -7
  56. package/dist/harness-recipe-entry.js +21 -32
  57. package/dist/harness-recipe.d.ts +38 -25
  58. package/dist/harness-recipe.js +49 -36
  59. package/dist/harness-sign-in.js +12 -23
  60. package/dist/harness-table.d.ts +10 -3
  61. package/dist/harness-table.js +26 -21
  62. package/dist/harness.d.ts +1 -0
  63. package/dist/harness.js +17 -5
  64. package/dist/hosted-search.d.ts +1 -1
  65. package/dist/hosted-search.js +1 -2
  66. package/dist/import-worker.d.ts +4 -2
  67. package/dist/import-worker.js +9 -2
  68. package/dist/in-flight.d.ts +26 -0
  69. package/dist/in-flight.js +52 -0
  70. package/dist/key-refusal.d.ts +9 -4
  71. package/dist/key-refusal.js +107 -25
  72. package/dist/learn/secrets.d.ts +13 -3
  73. package/dist/learn/secrets.js +118 -17
  74. package/dist/learning-cost.d.ts +6 -3
  75. package/dist/learning-cost.js +4 -2
  76. package/dist/link-check.js +1 -1
  77. package/dist/llms.txt +1 -1
  78. package/dist/marketplace.d.ts +77 -0
  79. package/dist/marketplace.js +224 -0
  80. package/dist/mcp-api-only-origins.d.ts +30 -0
  81. package/dist/mcp-api-only-origins.js +57 -0
  82. package/dist/mcp-gateway.d.ts +7 -5
  83. package/dist/mcp-gateway.js +9 -12
  84. package/dist/mcp-secret-writes.js +5 -3
  85. package/dist/mcp-servers-store.d.ts +28 -6
  86. package/dist/mcp-servers-store.js +53 -4
  87. package/dist/media-duration.d.ts +3 -0
  88. package/dist/media-duration.js +90 -9
  89. package/dist/model-form.d.ts +5 -4
  90. package/dist/model-form.js +11 -7
  91. package/dist/model.d.ts +5 -2
  92. package/dist/model.js +9 -5
  93. package/dist/ollama-provider.d.ts +7 -1
  94. package/dist/ollama-provider.js +14 -2
  95. package/dist/openapi.js +178 -27
  96. package/dist/otel/genai.d.ts +65 -0
  97. package/dist/otel/genai.js +116 -0
  98. package/dist/otel/tracer.d.ts +55 -0
  99. package/dist/otel/tracer.js +308 -0
  100. package/dist/page.d.ts +2 -0
  101. package/dist/page.js +3 -1
  102. package/dist/paid-calls.d.ts +1 -32
  103. package/dist/paid-calls.js +4 -39
  104. package/dist/provider.d.ts +9 -0
  105. package/dist/provider.js +50 -3
  106. package/dist/redact/match.d.ts +30 -3
  107. package/dist/redact/match.js +422 -41
  108. package/dist/refusal-words.d.ts +11 -0
  109. package/dist/refusal-words.js +11 -0
  110. package/dist/run-census.d.ts +67 -0
  111. package/dist/run-census.js +240 -0
  112. package/dist/run-computer.d.ts +6 -3
  113. package/dist/run-computer.js +4 -1
  114. package/dist/run-cut.d.ts +15 -6
  115. package/dist/run-cut.js +30 -9
  116. package/dist/run-files.d.ts +3 -0
  117. package/dist/run-files.js +3 -0
  118. package/dist/run-launch.d.ts +12 -1
  119. package/dist/run-launch.js +9 -10
  120. package/dist/run-learning-served.d.ts +2 -0
  121. package/dist/run-model-key.d.ts +8 -0
  122. package/dist/run-model-key.js +31 -1
  123. package/dist/run-reads-over-store.d.ts +24 -6
  124. package/dist/run-reads-over-store.js +67 -23
  125. package/dist/run-recordings.d.ts +5 -1
  126. package/dist/run-recordings.js +39 -14
  127. package/dist/run-timeline-served.d.ts +2 -0
  128. package/dist/run-timeline-served.js +2 -2
  129. package/dist/run-usage.d.ts +1 -0
  130. package/dist/runnable.d.ts +10 -1
  131. package/dist/runnable.js +20 -8
  132. package/dist/runner/adapter-loop.d.ts +11 -0
  133. package/dist/runner/adapter-loop.js +55 -10
  134. package/dist/runner/adapter-run-spec.d.ts +45 -8
  135. package/dist/runner/adapter-run-spec.js +150 -28
  136. package/dist/runner/adapters/pi.js +25 -3
  137. package/dist/runner/beside.js +4 -3
  138. package/dist/runner/big-writes.js +1 -10
  139. package/dist/runner/claim-secrets.d.ts +18 -3
  140. package/dist/runner/claim-secrets.js +35 -6
  141. package/dist/runner/cli-run-spec.d.ts +6 -0
  142. package/dist/runner/cli-run-spec.js +82 -35
  143. package/dist/runner/computer-journal.d.ts +9 -1
  144. package/dist/runner/computer-journal.js +26 -0
  145. package/dist/runner/conformance/harness.js +1 -1
  146. package/dist/runner/feedback-round.js +3 -0
  147. package/dist/runner/harness-loops.d.ts +6 -5
  148. package/dist/runner/harness-loops.js +7 -7
  149. package/dist/runner/held.d.ts +11 -5
  150. package/dist/runner/journal-kinds.d.ts +5 -0
  151. package/dist/runner/journal-kinds.js +5 -0
  152. package/dist/runner/main.js +7 -2
  153. package/dist/runner/mcp-claim.js +30 -3
  154. package/dist/runner/mcp-run.d.ts +12 -0
  155. package/dist/runner/mcp-run.js +12 -5
  156. package/dist/runner/model-route.d.ts +17 -0
  157. package/dist/runner/model-route.js +120 -2
  158. package/dist/runner/run-child-host.d.ts +3 -0
  159. package/dist/runner/run-child-host.js +69 -28
  160. package/dist/runner/run-child.js +5 -2
  161. package/dist/runner/runner.d.ts +14 -3
  162. package/dist/runner/runner.js +129 -33
  163. package/dist/runner/store-port.d.ts +1 -1
  164. package/dist/runner/store-secrets.d.ts +6 -0
  165. package/dist/runner/store-secrets.js +49 -7
  166. package/dist/runner/subagent.js +4 -40
  167. package/dist/runner/workflow-first.d.ts +11 -4
  168. package/dist/runner/workflow-first.js +14 -8
  169. package/dist/runner/workflow-spec.js +3 -2
  170. package/dist/runs-over-store.d.ts +15 -6
  171. package/dist/runs-over-store.js +33 -21
  172. package/dist/scrub-command.d.ts +73 -0
  173. package/dist/scrub-command.js +307 -0
  174. package/dist/secret-cut.d.ts +73 -0
  175. package/dist/secret-cut.js +291 -4
  176. package/dist/secret-rules.d.ts +143 -0
  177. package/dist/secret-rules.js +2564 -0
  178. package/dist/secrets.d.ts +7 -0
  179. package/dist/secrets.js +20 -0
  180. package/dist/server-keys.d.ts +20 -0
  181. package/dist/server-keys.js +25 -6
  182. package/dist/server.d.ts +52 -11
  183. package/dist/server.js +345 -118
  184. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  185. package/dist/store/index.d.ts +1 -1
  186. package/dist/store/index.js +1 -1
  187. package/dist/store/journal/storage.js +1 -1
  188. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  189. package/dist/store/schema.d.ts +6 -0
  190. package/dist/store/schema.js +11 -1
  191. package/dist/store/seal.d.ts +6 -1
  192. package/dist/store/seal.js +5 -3
  193. package/dist/store/sqlite/run-launch.d.ts +9 -1
  194. package/dist/store/sqlite/run-launch.js +24 -13
  195. package/dist/store/sqlite/run-patch.d.ts +1 -1
  196. package/dist/store/sqlite/run-patch.js +13 -4
  197. package/dist/store/sqlite/store.js +34 -4
  198. package/dist/store/store.d.ts +43 -2
  199. package/dist/store/store.js +20 -0
  200. package/dist/store-reads/learning.d.ts +6 -3
  201. package/dist/store-reads/learning.js +22 -7
  202. package/dist/store-view.d.ts +3 -0
  203. package/dist/store-view.js +3 -3
  204. package/dist/suggestions.js +3 -2
  205. package/dist/template-eval.d.ts +20 -9
  206. package/dist/template-eval.js +115 -33
  207. package/dist/template-import.d.ts +10 -0
  208. package/dist/template-import.js +16 -7
  209. package/dist/templates.d.ts +10 -2
  210. package/dist/templates.js +28 -8
  211. package/dist/timeline/labels.d.ts +6 -4
  212. package/dist/timeline/labels.js +18 -6
  213. package/dist/timeline/timeline.d.ts +5 -0
  214. package/dist/timeline/timeline.js +14 -8
  215. package/dist/timeline/util.js +1 -1
  216. package/dist/timeline/web-calls.d.ts +26 -9
  217. package/dist/timeline/web-calls.js +124 -37
  218. package/dist/tool-gate.d.ts +42 -3
  219. package/dist/tool-gate.js +66 -5
  220. package/dist/tool-keys-store.d.ts +2 -4
  221. package/dist/tool-keys-store.js +5 -21
  222. package/dist/tool-keys.d.ts +2 -2
  223. package/dist/tool-keys.js +2 -2
  224. package/dist/tool-list.js +1 -1
  225. package/dist/tool-plane.d.ts +2 -2
  226. package/dist/tool-plane.js +35 -33
  227. package/dist/tools.js +13 -7
  228. package/dist/trigger-targets.d.ts +4 -0
  229. package/dist/trigger-targets.js +9 -2
  230. package/dist/triggers.d.ts +67 -4
  231. package/dist/triggers.js +171 -22
  232. package/dist/until.d.ts +3 -0
  233. package/dist/until.js +11 -0
  234. package/dist/web-fake.d.ts +1 -3
  235. package/dist/web-fake.js +7 -18
  236. package/dist/web-fetch.d.ts +6 -72
  237. package/dist/web-fetch.js +11 -265
  238. package/dist/web-run.d.ts +31 -0
  239. package/dist/web-run.js +90 -0
  240. package/dist/web-save.d.ts +6 -4
  241. package/dist/web-save.js +9 -12
  242. package/dist/web-search.d.ts +9 -127
  243. package/dist/web-search.js +23 -259
  244. package/dist/wires.d.ts +13 -0
  245. package/dist/wires.js +11 -0
  246. package/dist/workflow-run.d.ts +5 -4
  247. package/dist/workflow-run.js +5 -4
  248. package/dist/workspace/computer-deps.d.ts +2 -1
  249. package/dist/workspace/computer-deps.js +9 -2
  250. package/dist/workspace/computer-for-claim.d.ts +12 -1
  251. package/dist/workspace/computer-for-claim.js +77 -8
  252. package/dist/workspace/computer-kept.d.ts +3 -0
  253. package/dist/workspace/computer-kept.js +11 -2
  254. package/dist/workspace/index.d.ts +1 -1
  255. package/dist/workspace/index.js +1 -1
  256. package/dist/workspace/kind-skills.d.ts +4 -0
  257. package/dist/workspace/kind-skills.js +9 -0
  258. package/dist/workspace/synced-folder.js +3 -4
  259. package/dist/wrapped.d.ts +13 -5
  260. package/dist/wrapped.js +52 -26
  261. package/package.json +17 -11
  262. package/skills/agentrun-serve/SKILL.md +4 -0
  263. package/templates/README.md +30 -8
  264. package/dist/console/assets/index-CQ3cJRzI.js +0 -746
  265. package/dist/console/assets/index-DKkaS3a0.css +0 -1
  266. package/dist/exa-keyless.d.ts +0 -34
  267. package/dist/exa-keyless.js +0 -118
  268. package/dist/firecrawl-keyless.d.ts +0 -41
  269. package/dist/firecrawl-keyless.js +0 -152
  270. package/dist/keyless-mcp.d.ts +0 -36
  271. package/dist/keyless-mcp.js +0 -127
  272. package/dist/text-urls.d.ts +0 -38
  273. package/dist/text-urls.js +0 -170
  274. package/dist/web-fetch-direct.d.ts +0 -119
  275. package/dist/web-fetch-direct.js +0 -190
@@ -216,6 +216,8 @@ export async function agentCostOverStore(store, agentId, limit = Infinity, refus
216
216
  const ended = listed.filter((run) => FINAL_STATES.includes(run.state) && !run.importedFrom && run.archivedAt === null && !isShadowRun(run.id)).sort((a, b) => a.startedAt - b.startedAt || (a.id < b.id ? -1 : 1));
217
217
  const rows = [];
218
218
  let unknownPath = 0;
219
+ // The hand-backs a restart cut (metrics.workflow_cut: pathMetrics), counted apart from the workflow's own (costSummary).
220
+ const cut = new Set();
219
221
  // One numbering, the bill's: the runs that do a job, 1 the first; a replay checks a revision and has none.
220
222
  let jobs = 0;
221
223
  for (const run of ended) {
@@ -229,12 +231,14 @@ export async function agentCostOverStore(store, agentId, limit = Infinity, refus
229
231
  unknownPath += 1;
230
232
  continue;
231
233
  }
234
+ if (placed.path === "handed_back" && run.metrics?.workflow_cut === true)
235
+ cut.add(run.id);
232
236
  rows.push(await costRunOf(records, run, JOB_PATHS.includes(placed.path) ? (jobs += 1) : null, placed));
233
237
  }
234
238
  // Where each revision took over, over every run before the limit cuts the read (the first is the summary's takeover).
235
239
  const runs = tookOverOf(rows);
236
240
  // Each learned workflow that ran first, where it stands against the money rule (workflow-first.ts workflowCostsOf), over
237
- // the runs the run's launch reads (pastRunsOverStore) at the all-in cost this series shows: a workflow over the line
241
+ // the runs the run's launch reads (pastRunsOverStore) at the all-in it reads (moneyAllInOf): a workflow over the line
238
242
  // shows `needs_revision` with its two numbers, so the page and the launch's decision agree.
239
243
  const workflows = workflowCostsOf(await pastRunsOverStore(store, agentId, new Map(runs.map((run) => [run.run_id, run.total_usd])), records));
240
244
  const promotions = await promotionsOf(store.settings, agentId);
@@ -245,7 +249,7 @@ export async function agentCostOverStore(store, agentId, limit = Infinity, refus
245
249
  // not be the first promotion), and each revision's compile and check over the served runs that carry it: runs on no
246
250
  // named disk alone, as a run on one learns nothing and serves nothing (learn/learning-of.ts).
247
251
  const ledger = await agentLedgerOf(records, promotions, listed.filter((run) => run.disk === null), await resetLedgerOf(store.settings, agentId), skip);
248
- const summary = costSummary(runs, replay);
252
+ const summary = costSummary(runs, replay, cut);
249
253
  const booked = billOf(runs, summary);
250
254
  // What no run carries is the booked total less every run's all-in (A8), so a revision whose records aged out of the
251
255
  // feed lands here, never nowhere: unknown while any run's figures are.
@@ -480,8 +484,9 @@ export async function costRunOf(store, run, n, { path, workflow }) {
480
484
  * and the cost page: of its newest PAST_RUNS runs on no named disk (learn/learning-of.ts: one on a named disk learns
481
485
  * nothing), each that ended (ended, stopped or failed) since its learning's reset (learn/compile.ts sinceReset: a
482
486
  * workflow before it is not the one it learned after, whatever its name), is neither imported nor archived nor a
483
- * workflow revision's run, with its all-in cost (allInOf). `known`: all-in costs already read, by run id (the cost
484
- * page's series), read again for no run; `records`, where any other's rows are read (the store's by default). */
487
+ * workflow revision's run, with its all-in cost as the money rule reads it (moneyAllInOf). `known`: all-in costs already
488
+ * read (allInOf), by run id (the cost page's series), read again for no served run; `records`, where any other's rows
489
+ * are read (the store's by default). */
485
490
  export async function pastRunsOverStore(store, agentId, known, records = store) {
486
491
  const kinds = new Map();
487
492
  const kept = [];
@@ -510,10 +515,19 @@ export async function pastRunsOverStore(store, agentId, known, records = store)
510
515
  // A few reads a run, a batch at a time: a launch reads up to PAST_RUNS of them.
511
516
  const past = [];
512
517
  for (let at = 0; at < kept.length; at += 16) {
513
- past.push(...(await Promise.all(kept.slice(at, at + 16).map(async (run) => ({ metrics: run.metrics, startedAt: run.startedAt, allInUsd: known?.has(run.id) ? known.get(run.id) : (await allInOf(paged, run)).total_usd })))));
518
+ past.push(...(await Promise.all(kept.slice(at, at + 16).map(async (run) => ({ metrics: run.metrics, startedAt: run.startedAt, allInUsd: await moneyAllInOf(paged, run, known) })))));
514
519
  }
515
520
  return past;
516
521
  }
522
+ /** A run's all-in as the money rule reads it (runner/workflow-first.ts PastRun): a run a learned workflow served
523
+ * (SERVED_PATHS) at its all-in (allInOf, or `known`'s); any other as the run view reads it (runAllInOverStore's
524
+ * allInV2Of), its compile turns its revision's, never the agent's by-hand cost, and no revision's share (only a served
525
+ * run carries one). Its recurring learning (a follow-up's rounds, its audit shadow) stays on it. */
526
+ async function moneyAllInOf(records, run, known) {
527
+ if (SERVED_PATHS.includes(metricOf(run).path))
528
+ return known?.has(run.id) ? known.get(run.id) : (await allInOf(records, run)).total_usd;
529
+ return allInV2Of({ run_id: run.id, ...(await allInOf(records, run)) }, await compilesOf(records, run.id), new Map());
530
+ }
517
531
  /** The money rule's decision for agent `agentId` (runner/workflow-first.ts costStopOf) over the runs a run's launch reads
518
532
  * (pastRunsOverStore), as the launch reads them: runs that can't be read now stop nothing (workflowFirstOf serves). What
519
533
  * the promotions read and the learning view fold into each workflow's state (learn/promote.ts servingStateOf). */
@@ -525,7 +539,8 @@ export const costStopOverStore = async (store, agentId) => costStopOf(await past
525
539
  * new answer is the agent's, with its digest. Else, for a run its launch offered a learned workflow, its timeline
526
540
  * (runner/learning-end.ts runPathOf, the agent calling the tool itself): `workflow` when its job did only that,
527
541
  * `handed_back` when the agent went on, with the workflow its job called last. Any other run's path is `agent`. Both
528
- * read the run's rows less its feedback rounds' (withoutFeedbackRounds): a grade's round never moves the path. */
542
+ * read the run's rows less its feedback rounds' (withoutFeedbackRounds): a grade's round never moves the path. `cut` on a
543
+ * hand-back a restart cut (servedOf: the workflow's call ended `interrupted`), never one the workflow made itself. */
529
544
  export async function runPathOverStore(store, runId, started, redact) {
530
545
  const entries = await runEntries(store, runId, BACKGROUND_CONTEXT);
531
546
  const served = servedOf(entries);
@@ -541,7 +556,7 @@ export async function runPathOverStore(store, runId, started, redact) {
541
556
  // runner's `redact`, adapter-loop.ts servedAnswerText): an agent that says it again leaves the path the workflow's.
542
557
  const answer = servedAnswerOf(entries)?.answer ?? "";
543
558
  const alone = served.outcome === "answered" && servedAnswerStands(answer, rows, redact ? redact(answer) : undefined);
544
- return { path: alone ? "workflow" : "handed_back", workflow: served.workflow, ...(served.digest ? { digest: served.digest } : {}), ...(served.promotion !== undefined ? { promotion: served.promotion } : {}) };
559
+ return { path: alone ? "workflow" : "handed_back", workflow: served.workflow, ...(served.digest ? { digest: served.digest } : {}), ...(served.promotion !== undefined ? { promotion: served.promotion } : {}), ...(served.cut ? { cut: true } : {}) };
545
560
  }
546
561
  const path = runPathOf(rows);
547
562
  // Only a name the launch offered: a call's raw `name` (a failed call's included) is the model's text, never shown.
@@ -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,20 @@ 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;
265
274
  /** 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
275
  * shell tool held to bash's setting (bash_background, bash_output, ...) keeps its own name, so its grader sees it. A
267
276
  * call on a saved server `toolkits` names ({<saved server>: <the package's toolkit>}, a need an owner's server filled
268
277
  * under another name) is named on the package's toolkit, as the package's graders name it. Each with its arguments and
269
278
  * its output as the rows of a calls=whole read carry them (tool_input, tool_result_text), else its previews. */
270
279
  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. */
280
+ /** 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),
281
+ * its name under the run's cut (the listing's `name`, absent from a server that doesn't cut it), its size, its type
282
+ * (null for an extension the server does not type) and whether the server could read it. */
273
283
  export type Listed = {
274
284
  path: string;
285
+ name?: string;
275
286
  bytes: number;
276
287
  type: string | null;
277
288
  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,10 +1040,13 @@ 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;
1043
+ /** The least time between two of those reads of one run. */
1044
+ export const CLAIM_READ_EVERY_MS = 5_000;
976
1045
  /** 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);
1046
+ * CLAIM_READ_TIMEOUT_MS, runs past the run's `deadline` or is stopped by `signal` (the eval's stop): not known, so never
1047
+ * a reason to cancel the run. Its bound ends at the deadline, so a read that stalls never puts the cancel past it. */
1048
+ async function heldNow(api, runId, deadline, signal) {
1049
+ const timeout = AbortSignal.timeout(Math.max(0, Math.min(CLAIM_READ_TIMEOUT_MS, deadline - Date.now())));
980
1050
  const read = await api("GET", `/runs/${runId}`, undefined, {}, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout }).catch(() => undefined);
981
1051
  return read?.status === 200 && isObject(read.body) ? isObject(read.body.claim) : undefined;
982
1052
  }
@@ -988,11 +1058,15 @@ async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIME
988
1058
  const started = Date.now();
989
1059
  // A run nobody takes stays queued: given up on once it has gone queueTimeoutMs with no runner holding it, by name, never
990
1060
  // 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
1061
+ // machine), so a queued page past the bound asks the run read whether a runner holds it now. Once one has, every queued
1062
+ // page asks (at most one read in CLAIM_READ_EVERY_MS): a claim can lapse for a moment on a stalled machine (not renewed
1063
+ // in time, then claimed again), so one read that finds none never ends the wait. The run is cancelled only when reads
1064
+ // found no runner holding it from the first such read to one queueTimeoutMs later, none between them finding one. A read
1065
+ // that doesn't answer (failed, stalled past its bound or the deadline, or stopped) says neither, and the stop and the
994
1066
  // deadline still end the wait.
995
- let queuedUntil = started + queueTimeoutMs;
1067
+ let unheldSince = started;
1068
+ let everHeld = false;
1069
+ let askedAt = -Infinity;
996
1070
  for (;;) {
997
1071
  if (signal?.aborted) {
998
1072
  await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
@@ -1016,16 +1090,23 @@ async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIME
1016
1090
  const waiting = rows.findLast((row) => row.kind === "waiting");
1017
1091
  return { status, rows, waiting: typeof waiting?.summary === "string" ? waiting.summary : "it waits on a person" };
1018
1092
  }
1019
- if (status === "queued" && Date.now() > queuedUntil) {
1020
- const held = await heldNow(api, runId, signal);
1021
- if (held === true)
1022
- queuedUntil = Date.now() + queueTimeoutMs;
1093
+ if (status === "queued" && (everHeld || Date.now() - started > queueTimeoutMs) && Date.now() - askedAt >= CLAIM_READ_EVERY_MS) {
1094
+ askedAt = Date.now();
1095
+ const held = await heldNow(api, runId, deadline, signal);
1096
+ if (held === true) {
1097
+ everHeld = true;
1098
+ unheldSince = undefined;
1099
+ }
1023
1100
  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
+ unheldSince ??= askedAt;
1102
+ if (Date.now() - unheldSince >= queueTimeoutMs) {
1103
+ await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1104
+ 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` };
1105
+ }
1026
1106
  }
1027
1107
  }
1028
- if (Date.now() > deadline) {
1108
+ // At the deadline, not only past it: the claim read's bound ends at the deadline, and may end in its very millisecond.
1109
+ if (Date.now() >= deadline) {
1029
1110
  await api("POST", `/runs/${runId}/cancel`, {});
1030
1111
  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` };
1031
1112
  }
@@ -1050,16 +1131,16 @@ export function callsOf(rows, harness, toolkits = {}) {
1050
1131
  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
1132
  });
1052
1133
  }
1053
- /** Every file of a run's work folder (the files route, page by page). */
1134
+ /** 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
1135
  async function filesOf(api, runId) {
1055
1136
  const files = [];
1056
1137
  for (let cursor = null;;) {
1057
- const page = await api("GET", `/runs/${runId}/files${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`);
1138
+ const page = await api("GET", `/runs/${runId}/files?cut=run${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`);
1058
1139
  if (page.status !== 200 || !isObject(page.body))
1059
1140
  return files;
1060
1141
  for (const file of page.body.files ?? []) {
1061
1142
  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 });
1143
+ 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
1144
  }
1064
1145
  cursor = typeof page.body.next_cursor === "string" ? page.body.next_cursor : null;
1065
1146
  if (!cursor)
@@ -1108,7 +1189,8 @@ export async function finalFilesOf(api, runId, listed, signal, readTimeoutMs = F
1108
1189
  texts.set(file.path, read.body);
1109
1190
  left -= bytes;
1110
1191
  }
1111
- return listed.map((file) => ({ path: file.path, bytes: file.bytes, ...(texts.has(file.path) ? { text: texts.get(file.path) } : {}) }));
1192
+ // Each by its cut name alone: its path is for the reads above, never a grader.
1193
+ return listed.map((file) => ({ ...(file.name !== undefined ? { name: file.name } : {}), bytes: file.bytes, ...(texts.has(file.path) ? { text: texts.get(file.path) } : {}) }));
1112
1194
  }
1113
1195
  /** Each path a file_exists grader names that the run's work folder holds, read one by one (GET /runs/{id}/files/{path}):
1114
1196
  * the listing is capped (its `truncated`), so a file past its cap or depth is never taken for absent. Only the status
@@ -1572,7 +1654,7 @@ async function runOnce(ctx, one, n, fakes, mail, feeds) {
1572
1654
  }
1573
1655
  stopped();
1574
1656
  // 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 } } : {}) });
1657
+ 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
1658
  let runId;
1577
1659
  let fired;
1578
1660
  if (via !== undefined && kept) {
@@ -25,6 +25,16 @@ export declare function loadImported(deps: Pick<TemplateImportDeps, "registry" |
25
25
  /** The uploads served here whose row the store no longer keeps (an agent's purge removed it: Agents.purge), no longer
26
26
  * served. Only the package read before the store is removed, so an upload put in meanwhile stays served. */
27
27
  export declare function dropRemovedUploads(deps: Pick<TemplateImportDeps, "registry" | "store">): Promise<void>;
28
+ /** An upload: its files checked as an import's are, its id `upload:<name>` (its manifest's name), its sha the package's
29
+ * sha256; a dry run answers it, storing nothing; else it is stored and served (201), in place of the one of its name. */
30
+ /** An upload's files ({files} of POST /v2/templates/import) checked as the import checks them, storing nothing: the
31
+ * package's bytes by path (each hidden path left out) and the package read from them; else the refusal the route answers
32
+ * (422). `agentrun deploy` runs this on the body it is about to send (agentrun-serve check-upload), so a package a target
33
+ * refuses is refused before anything is sent, by this one check. */
34
+ export declare function checkUpload(raw: unknown): {
35
+ files: Map<string, Buffer>;
36
+ pkg: Package;
37
+ };
28
38
  /** POST /v2/templates/import: the package read at its source's commit and checked; a dry run answers it, storing nothing;
29
39
  * else it is stored and served (201), in place of the one under its id. `signal` ends the read (the request's). An
30
40
  * upload ({files}) is uploadTemplate's. */
@@ -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;
@@ -159,18 +163,23 @@ function bodyOf(body, apiOnly) {
159
163
  }
160
164
  /** An upload: its files checked as an import's are, its id `upload:<name>` (its manifest's name), its sha the package's
161
165
  * sha256; a dry run answers it, storing nothing; else it is stored and served (201), in place of the one of its name. */
162
- async function uploadTemplate(deps, raw, dryRun) {
163
- let pkg;
164
- let files;
166
+ /** An upload's files ({files} of POST /v2/templates/import) checked as the import checks them, storing nothing: the
167
+ * package's bytes by path (each hidden path left out) and the package read from them; else the refusal the route answers
168
+ * (422). `agentrun deploy` runs this on the body it is about to send (agentrun-serve check-upload), so a package a target
169
+ * refuses is refused before anything is sent, by this one check. */
170
+ export function checkUpload(raw) {
165
171
  try {
166
- files = uploadFiles(raw);
172
+ const files = uploadFiles(raw);
167
173
  const name = manifestOf(files.get(MANIFEST)?.toString("utf8") ?? "")?.name;
168
174
  const id = `${UPLOAD_PREFIX}${typeof name === "string" ? name : ""}`;
169
- pkg = importedPackage(id, { source: id, sha: uploadSha(files), publisher: "" }, files);
175
+ return { files, pkg: importedPackage(id, { source: id, sha: uploadSha(files), publisher: "" }, files) };
170
176
  }
171
177
  catch (error) {
172
178
  refusalOf(error);
173
179
  }
180
+ }
181
+ async function uploadTemplate(deps, raw, dryRun) {
182
+ const { files, pkg } = checkUpload(raw);
174
183
  const replaced = deps.registry.get(pkg.id)?.origin?.sha ?? null;
175
184
  if (dryRun)
176
185
  return { status: 200, pkg, trusted: true, replaced };