@parcha/agentrun-serve 0.1.0-beta.55 → 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 (296) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +228 -45
  3. package/dist/acp-package.d.ts +2 -0
  4. package/dist/adapters.d.ts +18 -5
  5. package/dist/adapters.js +23 -9
  6. package/dist/agent-package.d.ts +3 -3
  7. package/dist/agent-package.js +17 -8
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-keys.d.ts +76 -0
  11. package/dist/api-keys.js +217 -0
  12. package/dist/api-only.d.ts +17 -5
  13. package/dist/api-only.js +36 -8
  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/calendar/tools.js +3 -2
  19. package/dist/chatgpt-plan.d.ts +28 -3
  20. package/dist/chatgpt-plan.js +182 -21
  21. package/dist/claude-login.d.ts +101 -14
  22. package/dist/claude-login.js +232 -49
  23. package/dist/claude-sign-in.d.ts +46 -0
  24. package/dist/claude-sign-in.js +93 -0
  25. package/dist/cli.js +63 -6
  26. package/dist/composio-made.d.ts +4 -0
  27. package/dist/composio-made.js +4 -0
  28. package/dist/composio-preset.d.ts +43 -2
  29. package/dist/composio-preset.js +92 -4
  30. package/dist/computer-held-routes.d.ts +5 -4
  31. package/dist/computer-held-routes.js +29 -8
  32. package/dist/computer-held.d.ts +6 -1
  33. package/dist/computer-held.js +14 -0
  34. package/dist/computer-record.js +4 -2
  35. package/dist/computer-viewer.js +4 -1
  36. package/dist/console/assets/{backend-D5EmB4N3.js → backend-DVhHzJX2.js} +19 -19
  37. package/dist/console/assets/index-Bwn1oTem.css +1 -0
  38. package/dist/console/assets/index-okP-y8PK.js +747 -0
  39. package/dist/console/index.html +2 -2
  40. package/dist/decisions.d.ts +1 -1
  41. package/dist/decisions.js +1 -1
  42. package/dist/docker-host-addresses.d.ts +22 -11
  43. package/dist/docker-host-addresses.js +38 -26
  44. package/dist/env-switch.d.ts +10 -0
  45. package/dist/env-switch.js +33 -2
  46. package/dist/errors.d.ts +1 -0
  47. package/dist/errors.js +2 -0
  48. package/dist/fal-price.d.ts +58 -20
  49. package/dist/fal-price.js +341 -82
  50. package/dist/handed-values.d.ts +43 -1
  51. package/dist/handed-values.js +119 -2
  52. package/dist/harness-archive.d.ts +13 -10
  53. package/dist/harness-archive.js +60 -34
  54. package/dist/harness-check.d.ts +3 -1
  55. package/dist/harness-check.js +25 -46
  56. package/dist/harness-keys.d.ts +73 -27
  57. package/dist/harness-keys.js +194 -61
  58. package/dist/harness-recipe-entry.d.ts +8 -7
  59. package/dist/harness-recipe-entry.js +21 -32
  60. package/dist/harness-recipe.d.ts +38 -25
  61. package/dist/harness-recipe.js +49 -36
  62. package/dist/harness-sign-in.js +12 -23
  63. package/dist/harness-table.d.ts +10 -3
  64. package/dist/harness-table.js +26 -21
  65. package/dist/harness.d.ts +1 -0
  66. package/dist/harness.js +17 -5
  67. package/dist/host-check.d.ts +4 -0
  68. package/dist/host-check.js +4 -0
  69. package/dist/hosted-search.d.ts +1 -1
  70. package/dist/hosted-search.js +1 -2
  71. package/dist/import-worker.d.ts +4 -2
  72. package/dist/import-worker.js +9 -2
  73. package/dist/in-flight.d.ts +26 -0
  74. package/dist/in-flight.js +52 -0
  75. package/dist/key-refusal.d.ts +26 -5
  76. package/dist/key-refusal.js +313 -37
  77. package/dist/learn/secrets.d.ts +31 -11
  78. package/dist/learn/secrets.js +152 -191
  79. package/dist/learning-cost.d.ts +6 -3
  80. package/dist/learning-cost.js +4 -2
  81. package/dist/link-check.js +1 -1
  82. package/dist/llms.txt +2 -2
  83. package/dist/marketplace.d.ts +77 -0
  84. package/dist/marketplace.js +224 -0
  85. package/dist/mcp-api-only-origins.d.ts +30 -0
  86. package/dist/mcp-api-only-origins.js +57 -0
  87. package/dist/mcp-gateway.d.ts +7 -5
  88. package/dist/mcp-gateway.js +9 -12
  89. package/dist/mcp-secret-writes.js +5 -3
  90. package/dist/mcp-servers-store.d.ts +28 -6
  91. package/dist/mcp-servers-store.js +53 -4
  92. package/dist/media-duration.d.ts +3 -0
  93. package/dist/media-duration.js +90 -9
  94. package/dist/model-form.d.ts +5 -4
  95. package/dist/model-form.js +11 -7
  96. package/dist/model.d.ts +5 -2
  97. package/dist/model.js +9 -5
  98. package/dist/ollama-provider.d.ts +7 -1
  99. package/dist/ollama-provider.js +14 -2
  100. package/dist/openapi.d.ts +3 -3
  101. package/dist/openapi.js +245 -42
  102. package/dist/otel/genai.d.ts +65 -0
  103. package/dist/otel/genai.js +116 -0
  104. package/dist/otel/tracer.d.ts +55 -0
  105. package/dist/otel/tracer.js +308 -0
  106. package/dist/page.d.ts +2 -0
  107. package/dist/page.js +3 -1
  108. package/dist/paid-calls.d.ts +1 -32
  109. package/dist/paid-calls.js +4 -39
  110. package/dist/place-offers.d.ts +14 -6
  111. package/dist/place-offers.js +26 -13
  112. package/dist/provider.d.ts +9 -0
  113. package/dist/provider.js +50 -3
  114. package/dist/redact/match.d.ts +101 -0
  115. package/dist/redact/match.js +1152 -0
  116. package/dist/refusal-words.d.ts +11 -0
  117. package/dist/refusal-words.js +11 -0
  118. package/dist/run-census.d.ts +67 -0
  119. package/dist/run-census.js +240 -0
  120. package/dist/run-computer.d.ts +6 -3
  121. package/dist/run-computer.js +4 -1
  122. package/dist/run-cut.d.ts +15 -6
  123. package/dist/run-cut.js +30 -9
  124. package/dist/run-files.d.ts +3 -0
  125. package/dist/run-files.js +3 -0
  126. package/dist/run-launch.d.ts +12 -1
  127. package/dist/run-launch.js +9 -10
  128. package/dist/run-learning-served.d.ts +2 -0
  129. package/dist/run-model-key.d.ts +8 -0
  130. package/dist/run-model-key.js +31 -1
  131. package/dist/run-reads-over-store.d.ts +24 -6
  132. package/dist/run-reads-over-store.js +67 -23
  133. package/dist/run-recordings.d.ts +5 -1
  134. package/dist/run-recordings.js +39 -14
  135. package/dist/run-timeline-served.d.ts +3 -1
  136. package/dist/run-timeline-served.js +4 -4
  137. package/dist/run-usage.d.ts +1 -0
  138. package/dist/runnable.d.ts +10 -1
  139. package/dist/runnable.js +20 -8
  140. package/dist/runner/adapter-loop.d.ts +14 -0
  141. package/dist/runner/adapter-loop.js +56 -11
  142. package/dist/runner/adapter-run-spec.d.ts +45 -8
  143. package/dist/runner/adapter-run-spec.js +154 -29
  144. package/dist/runner/adapters/pi.js +25 -3
  145. package/dist/runner/beside.js +11 -6
  146. package/dist/runner/big-writes.js +1 -10
  147. package/dist/runner/claim-secrets.d.ts +18 -3
  148. package/dist/runner/claim-secrets.js +35 -6
  149. package/dist/runner/cli-run-spec.d.ts +6 -0
  150. package/dist/runner/cli-run-spec.js +85 -36
  151. package/dist/runner/computer-journal.d.ts +9 -1
  152. package/dist/runner/computer-journal.js +26 -0
  153. package/dist/runner/conformance/harness.js +1 -1
  154. package/dist/runner/feedback-round.js +3 -0
  155. package/dist/runner/harness-loops.d.ts +6 -5
  156. package/dist/runner/harness-loops.js +7 -7
  157. package/dist/runner/held.d.ts +11 -5
  158. package/dist/runner/journal-kinds.d.ts +5 -0
  159. package/dist/runner/journal-kinds.js +5 -0
  160. package/dist/runner/loop-contract.d.ts +4 -0
  161. package/dist/runner/main.js +15 -6
  162. package/dist/runner/mcp-claim.js +30 -3
  163. package/dist/runner/mcp-run.d.ts +12 -0
  164. package/dist/runner/mcp-run.js +12 -5
  165. package/dist/runner/model-route.d.ts +17 -0
  166. package/dist/runner/model-route.js +120 -2
  167. package/dist/runner/presence.d.ts +4 -3
  168. package/dist/runner/presence.js +4 -2
  169. package/dist/runner/run-child-host.d.ts +5 -0
  170. package/dist/runner/run-child-host.js +71 -30
  171. package/dist/runner/run-child.js +5 -2
  172. package/dist/runner/runner.d.ts +18 -3
  173. package/dist/runner/runner.js +162 -36
  174. package/dist/runner/store-port.d.ts +1 -1
  175. package/dist/runner/store-secrets.d.ts +6 -0
  176. package/dist/runner/store-secrets.js +49 -7
  177. package/dist/runner/subagent.js +4 -40
  178. package/dist/runner/workflow-first.d.ts +11 -4
  179. package/dist/runner/workflow-first.js +14 -8
  180. package/dist/runner/workflow-spec.js +3 -2
  181. package/dist/runs-over-store.d.ts +15 -6
  182. package/dist/runs-over-store.js +33 -21
  183. package/dist/scrub-command.d.ts +73 -0
  184. package/dist/scrub-command.js +307 -0
  185. package/dist/secret-cut.d.ts +73 -0
  186. package/dist/secret-cut.js +291 -4
  187. package/dist/secret-rules.d.ts +143 -0
  188. package/dist/secret-rules.js +2564 -0
  189. package/dist/secrets.d.ts +7 -0
  190. package/dist/secrets.js +20 -0
  191. package/dist/server-keys.d.ts +20 -0
  192. package/dist/server-keys.js +25 -6
  193. package/dist/server.d.ts +57 -13
  194. package/dist/server.js +371 -113
  195. package/dist/skills/agentrun-serve/SKILL.md +4 -0
  196. package/dist/store/dialect.d.ts +3 -0
  197. package/dist/store/dialect.js +1 -0
  198. package/dist/store/index.d.ts +1 -1
  199. package/dist/store/index.js +1 -1
  200. package/dist/store/journal/storage.js +1 -1
  201. package/dist/store/postgres/dialect.js +3 -0
  202. package/dist/store/postgres/migrations/0027_run_launch_census.sql +31 -0
  203. package/dist/store/schema.d.ts +6 -0
  204. package/dist/store/schema.js +11 -1
  205. package/dist/store/seal.d.ts +6 -1
  206. package/dist/store/seal.js +5 -3
  207. package/dist/store/sqlite/run-launch.d.ts +9 -1
  208. package/dist/store/sqlite/run-launch.js +24 -13
  209. package/dist/store/sqlite/run-patch.d.ts +1 -1
  210. package/dist/store/sqlite/run-patch.js +13 -4
  211. package/dist/store/sqlite/store.js +76 -16
  212. package/dist/store/store.d.ts +53 -3
  213. package/dist/store/store.js +27 -0
  214. package/dist/store-reads/learning.d.ts +6 -3
  215. package/dist/store-reads/learning.js +22 -7
  216. package/dist/store-view.d.ts +3 -0
  217. package/dist/store-view.js +4 -4
  218. package/dist/suggestions.js +3 -2
  219. package/dist/template-eval.d.ts +22 -11
  220. package/dist/template-eval.js +124 -41
  221. package/dist/template-import.d.ts +10 -0
  222. package/dist/template-import.js +16 -7
  223. package/dist/templates.d.ts +10 -2
  224. package/dist/templates.js +28 -8
  225. package/dist/timeline/index.d.ts +1 -1
  226. package/dist/timeline/index.js +1 -1
  227. package/dist/timeline/labels.d.ts +6 -4
  228. package/dist/timeline/labels.js +18 -6
  229. package/dist/timeline/timeline.d.ts +17 -7
  230. package/dist/timeline/timeline.js +28 -14
  231. package/dist/timeline/util.js +1 -1
  232. package/dist/timeline/web-calls.d.ts +26 -9
  233. package/dist/timeline/web-calls.js +124 -37
  234. package/dist/tool-gate.d.ts +42 -3
  235. package/dist/tool-gate.js +69 -6
  236. package/dist/tool-keys-store.d.ts +2 -4
  237. package/dist/tool-keys-store.js +5 -21
  238. package/dist/tool-keys.d.ts +2 -2
  239. package/dist/tool-keys.js +2 -2
  240. package/dist/tool-list.js +1 -1
  241. package/dist/tool-plane.d.ts +2 -2
  242. package/dist/tool-plane.js +35 -33
  243. package/dist/tools.js +13 -7
  244. package/dist/trigger-targets.d.ts +4 -0
  245. package/dist/trigger-targets.js +9 -2
  246. package/dist/triggers.d.ts +67 -4
  247. package/dist/triggers.js +171 -22
  248. package/dist/until.d.ts +3 -0
  249. package/dist/until.js +11 -0
  250. package/dist/validate.js +1 -1
  251. package/dist/web-fake.d.ts +1 -3
  252. package/dist/web-fake.js +7 -18
  253. package/dist/web-fetch.d.ts +6 -72
  254. package/dist/web-fetch.js +11 -265
  255. package/dist/web-run.d.ts +31 -0
  256. package/dist/web-run.js +90 -0
  257. package/dist/web-save.d.ts +6 -4
  258. package/dist/web-save.js +9 -12
  259. package/dist/web-search.d.ts +9 -127
  260. package/dist/web-search.js +23 -259
  261. package/dist/wires.d.ts +13 -0
  262. package/dist/wires.js +11 -0
  263. package/dist/workflow-run.d.ts +5 -4
  264. package/dist/workflow-run.js +5 -4
  265. package/dist/workspace/computer-deps.d.ts +3 -1
  266. package/dist/workspace/computer-deps.js +12 -4
  267. package/dist/workspace/computer-for-claim.d.ts +19 -2
  268. package/dist/workspace/computer-for-claim.js +101 -13
  269. package/dist/workspace/computer-janitor.d.ts +15 -7
  270. package/dist/workspace/computer-janitor.js +33 -8
  271. package/dist/workspace/computer-kept.d.ts +55 -4
  272. package/dist/workspace/computer-kept.js +129 -8
  273. package/dist/workspace/index.d.ts +1 -1
  274. package/dist/workspace/index.js +1 -1
  275. package/dist/workspace/kind-skills.d.ts +4 -0
  276. package/dist/workspace/kind-skills.js +9 -0
  277. package/dist/workspace/run-end-computers.d.ts +5 -1
  278. package/dist/workspace/run-end-computers.js +27 -1
  279. package/dist/workspace/synced-folder.js +3 -4
  280. package/dist/wrapped.d.ts +65 -0
  281. package/dist/wrapped.js +77 -0
  282. package/package.json +17 -11
  283. package/skills/agentrun-serve/SKILL.md +4 -0
  284. package/templates/README.md +38 -15
  285. package/dist/console/assets/index-DUYLaqiR.js +0 -746
  286. package/dist/console/assets/index-DYhU4adm.css +0 -1
  287. package/dist/exa-keyless.d.ts +0 -34
  288. package/dist/exa-keyless.js +0 -118
  289. package/dist/firecrawl-keyless.d.ts +0 -41
  290. package/dist/firecrawl-keyless.js +0 -152
  291. package/dist/keyless-mcp.d.ts +0 -36
  292. package/dist/keyless-mcp.js +0 -127
  293. package/dist/text-urls.d.ts +0 -38
  294. package/dist/text-urls.js +0 -170
  295. package/dist/web-fetch-direct.d.ts +0 -119
  296. package/dist/web-fetch-direct.js +0 -190
@@ -3,9 +3,10 @@
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
- // call's arguments and its output's head 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
+ // 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
10
11
  // server: a grader agent with no tools that sees the rubric, the run's input, its answer and its calls, never another
11
12
  // grader or an expected answer, and answers {pass, reason}. readCases checks a package's cases without running one.
@@ -15,7 +16,7 @@ import { chmodSync, cpSync, lstatSync, mkdtempSync, readdirSync, readFileSync, r
15
16
  import { tmpdir } from "node:os";
16
17
  import { join } from "node:path";
17
18
  import { parseDocument } from "yaml";
18
- import { answerJson, lastJsonBlock } from "./answer-json.js";
19
+ import { answerJson, jsonBlockOf } from "./answer-json.js";
19
20
  import { correctionsProblems } from "./learn/index.js";
20
21
  import { linkCheck } from "./link-check.js";
21
22
  import { frontMatter } from "./manifest.js";
@@ -29,7 +30,7 @@ import { EMAIL_TOOLS } from "./email/names.js";
29
30
  import { CALENDAR_EVENTS } from "./calendar/names.js";
30
31
  import { nameMapOf, settingsKeyOf, shellToolOf } from "./tool-gate.js";
31
32
  import { builtinHarness } from "./harness-table.js";
32
- import { webShownOf } from "./timeline/index.js";
33
+ import { CALLS_PAGE_ROWS, webShownOf } from "./timeline/index.js";
33
34
  import { ASK_TOOL, BOUND_TOOLS } from "./tools.js";
34
35
  import { webFixtureOf } from "./web-fake.js";
35
36
  import { WEB_FETCH_TOOL } from "./web-fetch.js";
@@ -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,12 +914,20 @@ 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
  }
861
- /** A grader run's answer read as its verdict: the last json block's (else the last JSON object's) {pass, reason}. */
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
+ }
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
- const candidates = [lastJsonBlock(answer), ...[...answer.matchAll(/\{[^{}]*"pass"[^{}]*\}/g)].map((m) => m[0]).reverse()];
930
+ const candidates = [jsonBlockOf(answer), ...[...answer.matchAll(/\{[^{}]*"pass"[^{}]*\}/g)].map((m) => m[0]).reverse()];
864
931
  for (const text of candidates) {
865
932
  if (text === undefined)
866
933
  continue;
@@ -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,18 +1058,23 @@ 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);
999
1073
  signal.throwIfAborted();
1000
1074
  }
1001
- // calls=whole: each call's arguments and its output's head (tool_input, tool_result_text), which its graders read.
1002
- const page = expectOk(`reading run ${runId}'s timeline`, await api("GET", `/runs/${runId}/timeline?after=${after}&wait_ms=5000&calls=whole`));
1075
+ // calls=whole: each call's arguments and its output, whole to CALL_RESULT_CHARS (tool_input, tool_result_text), which its graders read.
1076
+ // CALLS_PAGE_ROWS rows a page, the most a calls=whole page holds (an older server's default is 500).
1077
+ 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}`));
1003
1078
  if (page.reset)
1004
1079
  view.clear();
1005
1080
  for (const id of page.drop ?? [])
@@ -1015,16 +1090,23 @@ async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIME
1015
1090
  const waiting = rows.findLast((row) => row.kind === "waiting");
1016
1091
  return { status, rows, waiting: typeof waiting?.summary === "string" ? waiting.summary : "it waits on a person" };
1017
1092
  }
1018
- if (status === "queued" && Date.now() > queuedUntil) {
1019
- const held = await heldNow(api, runId, signal);
1020
- if (held === true)
1021
- 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
+ }
1022
1100
  else if (held === false) {
1023
- await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1024
- 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
+ }
1025
1106
  }
1026
1107
  }
1027
- 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) {
1028
1110
  await api("POST", `/runs/${runId}/cancel`, {});
1029
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` };
1030
1112
  }
@@ -1036,7 +1118,7 @@ async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIME
1036
1118
  * shell tool held to bash's setting (bash_background, bash_output, ...) keeps its own name, so its grader sees it. A
1037
1119
  * call on a saved server `toolkits` names ({<saved server>: <the package's toolkit>}, a need an owner's server filled
1038
1120
  * under another name) is named on the package's toolkit, as the package's graders name it. Each with its arguments and
1039
- * its output's head as the rows of a calls=whole read carry them (tool_input, tool_result_text), else its previews. */
1121
+ * its output as the rows of a calls=whole read carry them (tool_input, tool_result_text), else its previews. */
1040
1122
  export function callsOf(rows, harness, toolkits = {}) {
1041
1123
  const results = new Map(rows.filter((row) => row.kind === "tool_result" && row.tool_use_id).map((row) => [String(row.tool_use_id), row]));
1042
1124
  // The rows are a server's, read over its API: the names are the built-in harness's, the only facts known here.
@@ -1049,16 +1131,16 @@ export function callsOf(rows, harness, toolkits = {}) {
1049
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 };
1050
1132
  });
1051
1133
  }
1052
- /** 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`). */
1053
1135
  async function filesOf(api, runId) {
1054
1136
  const files = [];
1055
1137
  for (let cursor = null;;) {
1056
- 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)}` : ""}`);
1057
1139
  if (page.status !== 200 || !isObject(page.body))
1058
1140
  return files;
1059
1141
  for (const file of page.body.files ?? []) {
1060
1142
  if (typeof file.path === "string")
1061
- 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 });
1062
1144
  }
1063
1145
  cursor = typeof page.body.next_cursor === "string" ? page.body.next_cursor : null;
1064
1146
  if (!cursor)
@@ -1107,7 +1189,8 @@ export async function finalFilesOf(api, runId, listed, signal, readTimeoutMs = F
1107
1189
  texts.set(file.path, read.body);
1108
1190
  left -= bytes;
1109
1191
  }
1110
- 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) } : {}) }));
1111
1194
  }
1112
1195
  /** Each path a file_exists grader names that the run's work folder holds, read one by one (GET /runs/{id}/files/{path}):
1113
1196
  * the listing is capped (its `truncated`), so a file past its cap or depth is never taken for absent. Only the status
@@ -1571,7 +1654,7 @@ async function runOnce(ctx, one, n, fakes, mail, feeds) {
1571
1654
  }
1572
1655
  stopped();
1573
1656
  // The case's fakes, for this run's agent alone, before its run can be claimed.
1574
- 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 } : {}) });
1575
1658
  let runId;
1576
1659
  let fired;
1577
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 };
@@ -233,6 +233,14 @@ export declare function folderFiles(dir: string): PackageFiles;
233
233
  /** A package held in memory, by path (template-source.ts keeps regular files alone): its folders are those its files'
234
234
  * paths name. */
235
235
  export declare function memoryFiles(name: string, where: string, files: ReadonlyMap<string, Buffer>): PackageFiles;
236
+ /** Each of a package's triggers (POST /v2/triggers bodies, as its manifest or an export writes them) with no spend cap of
237
+ * its own (target.max_cost_usd, read by isCap here, not left to the trigger's schema), by its index and name. A package
238
+ * with triggers and no budget.per_run_usd is taken only when this is empty, so every run a trigger starts is capped by
239
+ * the budget or by its trigger. readPackage refuses by it, and an export blocks by it (agent-package.ts). */
240
+ export declare function uncappedTriggers(triggers: readonly unknown[]): {
241
+ index: number;
242
+ name: string;
243
+ }[];
236
244
  /** Reads the package at `from` (its folder, or its files: PackageFiles) checked whole: a valid package, or PackageError
237
245
  * with every problem found. */
238
246
  export declare function readPackage(from: string | PackageFiles, { evalFixtures }?: {
@@ -260,7 +268,7 @@ export declare function packageView(p: Package): {
260
268
  license: string | null;
261
269
  author: Json | null;
262
270
  repository: string | null;
263
- category: "engineering" | "security" | "sales" | "marketing" | "research" | "finance" | "operations" | "compliance" | "personal" | null;
271
+ category: "personal" | "engineering" | "security" | "sales" | "marketing" | "research" | "finance" | "operations" | "compliance" | null;
264
272
  tags: string[];
265
273
  output: {
266
274
  schema: string;
@@ -334,7 +342,7 @@ export declare function packageDetail<Pick>(p: Package, computerHere: (p: Packag
334
342
  license: string | null;
335
343
  author: Json | null;
336
344
  repository: string | null;
337
- category: "engineering" | "security" | "sales" | "marketing" | "research" | "finance" | "operations" | "compliance" | "personal" | null;
345
+ category: "personal" | "engineering" | "security" | "sales" | "marketing" | "research" | "finance" | "operations" | "compliance" | null;
338
346
  tags: string[];
339
347
  output: {
340
348
  schema: string;
package/dist/templates.js CHANGED
@@ -508,6 +508,20 @@ function fieldsSchema(value, of, bad) {
508
508
  }
509
509
  return { type: "object", additionalProperties: false, ...(required.length ? { required } : {}), properties };
510
510
  }
511
+ /** A spend cap a run can hold: a number above 0 and finite (0, a negative, NaN and Infinity are none). */
512
+ const isCap = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
513
+ /** Each of a package's triggers (POST /v2/triggers bodies, as its manifest or an export writes them) with no spend cap of
514
+ * its own (target.max_cost_usd, read by isCap here, not left to the trigger's schema), by its index and name. A package
515
+ * with triggers and no budget.per_run_usd is taken only when this is empty, so every run a trigger starts is capped by
516
+ * the budget or by its trigger. readPackage refuses by it, and an export blocks by it (agent-package.ts). */
517
+ export function uncappedTriggers(triggers) {
518
+ return triggers.flatMap((trigger, index) => {
519
+ const target = isObject(trigger) ? trigger.target : undefined;
520
+ if (isObject(target) && isCap(target.max_cost_usd))
521
+ return [];
522
+ return [{ index, name: isObject(trigger) && typeof trigger.name === "string" ? trigger.name.trim() : "" }];
523
+ });
524
+ }
511
525
  /** Reads the package at `from` (its folder, or its files: PackageFiles) checked whole: a valid package, or PackageError
512
526
  * with every problem found. */
513
527
  export function readPackage(from, { evalFixtures = true } = {}) {
@@ -554,8 +568,10 @@ export function readPackage(from, { evalFixtures = true } = {}) {
554
568
  bad(MANIFEST, `${field} names one item twice`);
555
569
  return value;
556
570
  };
557
- /** `path` is a regular file inside the package. */
558
- const inside = (path) => typeof path === "string" && !path.startsWith("/") && !path.split("/").some((part) => part === ".." || part === "." || part === "") && kind(path) === "file";
571
+ /** `path`, named in agent.md, passes through a hidden file or folder: one the package leaves out (entries), so never read. */
572
+ const hidden = (path) => typeof path === "string" && path.split("/").some((part) => part.startsWith("."));
573
+ /** `path` is a regular file inside the package, none of its parts hidden (".", ".." and ".env" alike) or empty. */
574
+ const inside = (path) => typeof path === "string" && !path.startsWith("/") && !hidden(path) && !path.split("/").includes("") && kind(path) === "file";
559
575
  const name = src.name;
560
576
  if (src.kind("") !== "dir")
561
577
  throw new PackageError(dir, ["it is not a folder: a package is one"]);
@@ -604,7 +620,7 @@ export function readPackage(from, { evalFixtures = true } = {}) {
604
620
  bad(MANIFEST, "repository is an http(s) URL");
605
621
  // Display only: what a marketplace page and the console's list file it under, and its tags.
606
622
  if (f.category !== undefined && !CATEGORIES.includes(f.category))
607
- bad(MANIFEST, `category is one of ${CATEGORIES.join(", ")}`);
623
+ bad(MANIFEST, `category is one of ${CATEGORIES.join(", ")}, not ${JSON.stringify(f.category)}`);
608
624
  const tags = f.tags === undefined ? [] : Array.isArray(f.tags) && f.tags.length <= MAX_TAGS && f.tags.every((tag) => typeof tag === "string" && TAG.test(tag)) && new Set(f.tags).size === f.tags.length ? f.tags : (bad(MANIFEST, `tags is a list of at most ${MAX_TAGS} tags, each once, each lowercase letters, digits and dashes (${TAG.source})`), []);
609
625
  const harness = f.harness === undefined ? undefined : list(f.harness, "harness", (id) => HARNESSES.includes(id));
610
626
  if (harness && !harness.length)
@@ -703,9 +719,8 @@ export function readPackage(from, { evalFixtures = true } = {}) {
703
719
  bad(MANIFEST, `secrets names ${secret}, a key this server cannot hold: a package needs the keys Settings saves and a run is handed (${PACKAGE_SECRETS.join(", ")})`);
704
720
  // Each run's limits: its spend cap (per_run_usd, the agent's max_cost_usd), required once a budget is given, and the most
705
721
  // requests on free models it makes (max_requests, the agent's max_requests), which a dollar cap cannot bound.
706
- const perRun = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
707
722
  const requests = (value) => value === undefined || (typeof value === "number" && Number.isSafeInteger(value) && value >= 1);
708
- if (f.budget !== undefined && !(isObject(f.budget) && !unknownFields(f.budget, ["per_run_usd", "max_requests"]).length && perRun(f.budget.per_run_usd) && requests(f.budget.max_requests)))
723
+ if (f.budget !== undefined && !(isObject(f.budget) && !unknownFields(f.budget, ["per_run_usd", "max_requests"]).length && isCap(f.budget.per_run_usd) && requests(f.budget.max_requests)))
709
724
  bad(MANIFEST, "budget is {per_run_usd: a number above 0, max_requests: a whole number of free-model requests above 0, when given}");
710
725
  const learningIssue = f.learning === undefined ? undefined : learningSettingIssue(f.learning, "learning");
711
726
  if (learningIssue)
@@ -743,13 +758,18 @@ export function readPackage(from, { evalFixtures = true } = {}) {
743
758
  bad(MANIFEST, `triggers[${i}].source.server ${need.toolkit}: the trigger's server is the mcp need of the toolkit ${need.toolkit}, so that need is required: true. An optional one may have no saved server here, and the trigger would have none`);
744
759
  }
745
760
  });
746
- if (triggers.length && !(isObject(f.budget) && f.budget.per_run_usd !== undefined))
747
- bad(MANIFEST, "budget is required when the package has triggers: {per_run_usd}, each run's cap");
761
+ // Every run a trigger starts is capped: by the package's budget, else by each trigger's own max_cost_usd.
762
+ if (triggers.length && !(isObject(f.budget) && f.budget.per_run_usd !== undefined)) {
763
+ for (const { index, name } of uncappedTriggers(triggers))
764
+ bad(MANIFEST, `triggers[${index}]${name ? ` (${name})` : ""} has no max_cost_usd of its own, and the package has no budget: every run a trigger starts is capped, so give the trigger's target a max_cost_usd above 0, or the package a budget: {per_run_usd}, each run's cap`);
765
+ }
748
766
  let outputSchema;
749
767
  if (f.output !== undefined) {
750
768
  const at = isObject(f.output) ? f.output.schema : undefined;
751
769
  const evalSize = typeof at === "string" && at.startsWith("evals/") && inside(at) ? src.size(at) : 0;
752
- if (!isObject(f.output) || unknownFields(f.output, ["schema"]).length || !inside(at))
770
+ if (isObject(f.output) && typeof at === "string" && hidden(at) && !at.split("/").some((part) => part === "." || part === ".."))
771
+ bad(MANIFEST, `output.schema ${at} is a hidden file: a hidden file or folder is no part of a package, so it is never read. Name a file with no part of its path starting with "."`);
772
+ else if (!isObject(f.output) || unknownFields(f.output, ["schema"]).length || !inside(at))
753
773
  bad(MANIFEST, "output is {schema: a JSON Schema file in the package}");
754
774
  else if (evalSize > MAX_FILE_BYTES || agentBytes + evalSize > MAX_PACKAGE_BYTES) {
755
775
  bad(at, evalSize > MAX_FILE_BYTES ? `is over ${MAX_FILE_BYTES} bytes, a package file's limit: the answer's schema is given to the agent, so it keeps an agent file's limits, under evals/ too` : `takes the agent's files over ${MAX_PACKAGE_BYTES} bytes together, POST /v2/agents' own limit: the answer's schema is given to the agent, so it counts as an agent file, under evals/ too`);
@@ -6,4 +6,4 @@ export { costLabel, endedUsage, PAGE_CHANGED_ROW, RUN_RESUMED, toolCallWords, TU
6
6
  export { FEEDBACK_SUFFIX, isFeedbackRow, isMessageRow, isUserEntry, MESSAGE_ORIGIN, messageOrigins, NOTE_SUFFIX, originMatcher, originOf, TRIGGER_LABELS, TRIGGER_SOURCES, type MessageOrigin, type TriggerSource } from "./origin.js";
7
7
  export { cut, scrubUrl, scrubUrls } from "./util.js";
8
8
  export { webCut, webShownOf, webWithin, type WebShown } from "./web-calls.js";
9
- export { answeredRequests, BROWSER_CHARGE, CALL_ENDED_WITH_RUN, compactionAnswers, CALL_REFUSED, CALL_RESULT_CHARS, CAP_REFUSED, CAP_WRAPUP, CAPS, chargedTool, COMPUTER_NOTE, endedOnTurnEndingTool, HOST_PHASE, METRIC_NAMES, REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, runMetricsOf, runMetricsWithDecisions, timelineOf, timelineReducer, TOOL_COST, TOOL_STARTED, TOOL_UNMETERED, type AgentEventLike, type DecisionLike, type EntryLike, type RunMetrics, type SideSpend, type TimelineEvent, type TimelineKind, type TimelineOptions, type ToolMetrics, } from "./timeline.js";
9
+ export { answeredRequests, BROWSER_CHARGE, CALL_ENDED_WITH_RUN, compactionAnswers, CALL_REFUSED, CALL_RESULT_CHARS, CALLS_PAGE_ROWS, CAP_REFUSED, CAP_WRAPUP, CAPS, chargedTool, COMPUTER_NOTE, endedOnTurnEndingTool, HOST_PHASE, METRIC_NAMES, REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, runMetricsOf, runMetricsWithDecisions, timelineOf, timelineReducer, TOOL_COST, TOOL_STARTED, TOOL_UNMETERED, type AgentEventLike, type DecisionLike, type EntryLike, type RunMetrics, type SideSpend, type TimelineEvent, type TimelineKind, type TimelineOptions, type ToolMetrics, } from "./timeline.js";
@@ -6,4 +6,4 @@ export { costLabel, endedUsage, PAGE_CHANGED_ROW, RUN_RESUMED, toolCallWords, TU
6
6
  export { FEEDBACK_SUFFIX, isFeedbackRow, isMessageRow, isUserEntry, MESSAGE_ORIGIN, messageOrigins, NOTE_SUFFIX, originMatcher, originOf, TRIGGER_LABELS, TRIGGER_SOURCES } from "./origin.js";
7
7
  export { cut, scrubUrl, scrubUrls } from "./util.js";
8
8
  export { webCut, webShownOf, webWithin } from "./web-calls.js";
9
- export { answeredRequests, BROWSER_CHARGE, CALL_ENDED_WITH_RUN, compactionAnswers, CALL_REFUSED, CALL_RESULT_CHARS, CAP_REFUSED, CAP_WRAPUP, CAPS, chargedTool, COMPUTER_NOTE, endedOnTurnEndingTool, HOST_PHASE, METRIC_NAMES, REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, runMetricsOf, runMetricsWithDecisions, timelineOf, timelineReducer, TOOL_COST, TOOL_STARTED, TOOL_UNMETERED, } from "./timeline.js";
9
+ export { answeredRequests, BROWSER_CHARGE, CALL_ENDED_WITH_RUN, compactionAnswers, CALL_REFUSED, CALL_RESULT_CHARS, CALLS_PAGE_ROWS, CAP_REFUSED, CAP_WRAPUP, CAPS, chargedTool, COMPUTER_NOTE, endedOnTurnEndingTool, HOST_PHASE, METRIC_NAMES, REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, runMetricsOf, runMetricsWithDecisions, timelineOf, timelineReducer, TOOL_COST, TOOL_STARTED, TOOL_UNMETERED, } from "./timeline.js";
@@ -15,13 +15,15 @@ export type FoldSpec = {
15
15
  };
16
16
  /** Registers the label of one tool, in the past tense, and with `name` what the tool is called where calls are counted
17
17
  * (a run's analytics). `saysFailure`: the label of a call that errored says so itself ("Could not take a screenshot"),
18
- * so its row adds only why. A host adds its own tools here. */
18
+ * so its row adds only why; `true` for every error, or a test of the errored result for the errors whose label says so.
19
+ * A host adds its own tools here. */
19
20
  export declare function registerLabel(tool: string, label: LabelFn, fold?: FoldSpec, { name, saysFailure }?: {
20
21
  name?: string;
21
- saysFailure?: true;
22
+ saysFailure?: true | ((result: ToolResultView) => boolean);
22
23
  }): void;
23
- /** Whether `tool`'s label says a call that errored failed (registerLabel's saysFailure). */
24
- export declare const saysFailure: (tool: string) => boolean;
24
+ /** Whether `tool`'s label says that its errored call `result` failed (registerLabel's saysFailure). `result` is the one
25
+ * the label was given, so the two read the same text. */
26
+ export declare const saysFailure: (tool: string, result: ToolResultView) => boolean;
25
27
  /** What a tool is called where its calls are counted, in plain words: its registered name, else the name it was called by. */
26
28
  export declare const nameOf: (tool: string) => string;
27
29
  /** A finished call's outcome, when its own result says more than that the call returned: a tool that answers a refusal