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

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 (234) hide show
  1. package/CHANGELOG.md +142 -2
  2. package/README.md +310 -98
  3. package/dist/adapters.d.ts +11 -0
  4. package/dist/adapters.js +49 -0
  5. package/dist/agent-package.d.ts +3 -3
  6. package/dist/agent-package.js +6 -13
  7. package/dist/agents-store.js +6 -5
  8. package/dist/answer-json.d.ts +6 -2
  9. package/dist/answer-json.js +22 -4
  10. package/dist/api-only.d.ts +16 -4
  11. package/dist/api-only.js +23 -7
  12. package/dist/calendar/tools.js +3 -2
  13. package/dist/chatgpt-plan.d.ts +16 -1
  14. package/dist/chatgpt-plan.js +116 -12
  15. package/dist/claude-login.d.ts +34 -5
  16. package/dist/claude-login.js +31 -7
  17. package/dist/claude-sign-in.d.ts +35 -0
  18. package/dist/claude-sign-in.js +90 -0
  19. package/dist/cli.js +5 -3
  20. package/dist/composio-made.d.ts +26 -1
  21. package/dist/composio-made.js +39 -2
  22. package/dist/composio-preset.d.ts +3 -2
  23. package/dist/composio-preset.js +46 -14
  24. package/dist/computer-held-routes.js +2 -3
  25. package/dist/computer-setting.d.ts +4 -2
  26. package/dist/computer-setting.js +0 -2
  27. package/dist/computers-running.d.ts +8 -0
  28. package/dist/computers-running.js +27 -0
  29. package/dist/console/assets/backend-Boh7tC4i.js +166 -0
  30. package/dist/console/assets/index-CQ3cJRzI.js +746 -0
  31. package/dist/console/assets/index-DKkaS3a0.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/docker-host-addresses.d.ts +23 -3
  34. package/dist/docker-host-addresses.js +90 -18
  35. package/dist/exa-keyless.d.ts +2 -3
  36. package/dist/exa-keyless.js +43 -127
  37. package/dist/firecrawl-keyless.d.ts +41 -0
  38. package/dist/firecrawl-keyless.js +152 -0
  39. package/dist/handed-secret.d.ts +3 -1
  40. package/dist/handed-secret.js +4 -2
  41. package/dist/harness-keys.d.ts +98 -0
  42. package/dist/harness-keys.js +247 -0
  43. package/dist/harness-recipe-entry.d.ts +14 -9
  44. package/dist/harness-recipe-entry.js +25 -14
  45. package/dist/harness-table.d.ts +16 -1
  46. package/dist/harness-table.js +19 -7
  47. package/dist/harness.d.ts +4 -0
  48. package/dist/harness.js +12 -1
  49. package/dist/host-check.d.ts +6 -0
  50. package/dist/host-check.js +10 -0
  51. package/dist/import-summary.d.ts +1 -1
  52. package/dist/import-summary.js +1 -1
  53. package/dist/import.d.ts +5 -5
  54. package/dist/import.js +54 -67
  55. package/dist/key-refusal.d.ts +21 -5
  56. package/dist/key-refusal.js +231 -37
  57. package/dist/keyless-mcp.d.ts +36 -0
  58. package/dist/keyless-mcp.js +127 -0
  59. package/dist/learn/audit.d.ts +3 -3
  60. package/dist/learn/audit.js +3 -3
  61. package/dist/learn/commit.d.ts +8 -7
  62. package/dist/learn/commit.js +60 -20
  63. package/dist/learn/compile.d.ts +4 -3
  64. package/dist/learn/compile.js +7 -5
  65. package/dist/learn/folder.d.ts +16 -3
  66. package/dist/learn/folder.js +46 -13
  67. package/dist/learn/promote.d.ts +37 -13
  68. package/dist/learn/promote.js +112 -40
  69. package/dist/learn/secrets.d.ts +20 -10
  70. package/dist/learn/secrets.js +44 -176
  71. package/dist/learning-routes.d.ts +22 -17
  72. package/dist/learning-routes.js +40 -39
  73. package/dist/learning.js +2 -2
  74. package/dist/llms.txt +1 -1
  75. package/dist/manifest.d.ts +10 -0
  76. package/dist/manifest.js +30 -0
  77. package/dist/mcp-pin-first.d.ts +4 -2
  78. package/dist/mcp-pin-first.js +5 -2
  79. package/dist/mcp-secret-writes.d.ts +16 -7
  80. package/dist/mcp-secret-writes.js +35 -27
  81. package/dist/mcp-servers-store.d.ts +30 -6
  82. package/dist/mcp-servers-store.js +112 -28
  83. package/dist/mcp-sources.d.ts +10 -2
  84. package/dist/mcp-sources.js +9 -2
  85. package/dist/mcp-store.d.ts +13 -7
  86. package/dist/mcp-store.js +12 -9
  87. package/dist/model-form.d.ts +3 -2
  88. package/dist/model-form.js +11 -7
  89. package/dist/model.d.ts +20 -4
  90. package/dist/model.js +68 -9
  91. package/dist/native/history.d.ts +1 -1
  92. package/dist/native/history.js +2 -2
  93. package/dist/ollama-provider.d.ts +92 -0
  94. package/dist/ollama-provider.js +495 -0
  95. package/dist/openapi/agentrun-v2.openapi.json +2 -2
  96. package/dist/openapi.d.ts +3 -3
  97. package/dist/openapi.js +197 -55
  98. package/dist/page.d.ts +11 -3
  99. package/dist/page.js +22 -7
  100. package/dist/place-offers.d.ts +25 -1
  101. package/dist/place-offers.js +62 -8
  102. package/dist/print.js +1 -1
  103. package/dist/purged-workflow.d.ts +35 -7
  104. package/dist/purged-workflow.js +73 -26
  105. package/dist/redact/match.d.ts +74 -0
  106. package/dist/redact/match.js +771 -0
  107. package/dist/run-computer.d.ts +2 -0
  108. package/dist/run-computer.js +2 -0
  109. package/dist/run-files.d.ts +4 -0
  110. package/dist/run-files.js +4 -0
  111. package/dist/run-keys.d.ts +2 -4
  112. package/dist/run-keys.js +6 -7
  113. package/dist/run-launch.d.ts +4 -0
  114. package/dist/run-launch.js +4 -0
  115. package/dist/run-reads-over-store.d.ts +3 -2
  116. package/dist/run-reads-over-store.js +66 -2
  117. package/dist/run-secrets.js +5 -2
  118. package/dist/run-timeline-served.d.ts +1 -1
  119. package/dist/run-timeline-served.js +4 -4
  120. package/dist/runner/adapter-loop.d.ts +9 -3
  121. package/dist/runner/adapter-loop.js +34 -15
  122. package/dist/runner/adapter-run-spec.d.ts +3 -0
  123. package/dist/runner/adapter-run-spec.js +9 -4
  124. package/dist/runner/audit.js +8 -4
  125. package/dist/runner/beside.d.ts +2 -1
  126. package/dist/runner/beside.js +13 -5
  127. package/dist/runner/claim-secrets.d.ts +5 -8
  128. package/dist/runner/claim-secrets.js +6 -0
  129. package/dist/runner/cli-run-spec.d.ts +1 -1
  130. package/dist/runner/cli-run-spec.js +41 -7
  131. package/dist/runner/harness-loops.d.ts +22 -9
  132. package/dist/runner/harness-loops.js +21 -11
  133. package/dist/runner/held.d.ts +3 -0
  134. package/dist/runner/learning-end.d.ts +1 -1
  135. package/dist/runner/learning-end.js +8 -3
  136. package/dist/runner/loop-contract.d.ts +9 -4
  137. package/dist/runner/main.js +12 -6
  138. package/dist/runner/mcp-claim.d.ts +3 -0
  139. package/dist/runner/mcp-claim.js +26 -2
  140. package/dist/runner/mcp-run.d.ts +3 -0
  141. package/dist/runner/mcp-run.js +2 -1
  142. package/dist/runner/metrics.d.ts +10 -10
  143. package/dist/runner/metrics.js +19 -38
  144. package/dist/runner/model-route.d.ts +3 -0
  145. package/dist/runner/model-route.js +6 -2
  146. package/dist/runner/presence.d.ts +4 -3
  147. package/dist/runner/presence.js +4 -2
  148. package/dist/runner/promotion.d.ts +15 -9
  149. package/dist/runner/promotion.js +25 -15
  150. package/dist/runner/run-child-host.d.ts +2 -0
  151. package/dist/runner/run-child-host.js +19 -9
  152. package/dist/runner/run-child.js +3 -1
  153. package/dist/runner/runner.d.ts +4 -0
  154. package/dist/runner/runner.js +33 -3
  155. package/dist/runner/sdk-loop.js +2 -0
  156. package/dist/runner/workflow-loop.d.ts +2 -2
  157. package/dist/runner/workflow-loop.js +1 -2
  158. package/dist/runner/workflow-spec.d.ts +1 -1
  159. package/dist/runner/workflow-spec.js +6 -6
  160. package/dist/sdk/check.d.ts +4 -1
  161. package/dist/sdk/check.js +2 -1
  162. package/dist/sdk/runs.d.ts +2 -2
  163. package/dist/sdk/runs.js +8 -6
  164. package/dist/secret-cut.js +2 -1
  165. package/dist/secret-writes.d.ts +3 -2
  166. package/dist/secret-writes.js +1 -1
  167. package/dist/server.d.ts +49 -10
  168. package/dist/server.js +324 -118
  169. package/dist/standard-webhooks.d.ts +11 -0
  170. package/dist/standard-webhooks.js +20 -2
  171. package/dist/store/dialect.d.ts +3 -0
  172. package/dist/store/dialect.js +1 -0
  173. package/dist/store/index.d.ts +2 -2
  174. package/dist/store/index.js +1 -1
  175. package/dist/store/postgres/dialect.js +3 -0
  176. package/dist/store/schema.js +5 -2
  177. package/dist/store/sqlite/store.js +133 -47
  178. package/dist/store/store.d.ts +64 -15
  179. package/dist/store/store.js +7 -0
  180. package/dist/store-reads/journal.d.ts +7 -2
  181. package/dist/store-reads/journal.js +9 -6
  182. package/dist/store-reads/learning.d.ts +12 -9
  183. package/dist/store-reads/learning.js +18 -24
  184. package/dist/store-view.d.ts +0 -5
  185. package/dist/store-view.js +10 -9
  186. package/dist/template-eval.d.ts +51 -6
  187. package/dist/template-eval.js +177 -53
  188. package/dist/template-import.js +4 -2
  189. package/dist/templates.d.ts +5 -3
  190. package/dist/templates.js +19 -40
  191. package/dist/timeline/index.d.ts +1 -1
  192. package/dist/timeline/index.js +1 -1
  193. package/dist/timeline/labels.d.ts +2 -2
  194. package/dist/timeline/labels.js +2 -2
  195. package/dist/timeline/timeline.d.ts +14 -9
  196. package/dist/timeline/timeline.js +15 -7
  197. package/dist/tool-gate.js +3 -1
  198. package/dist/tool-plane.d.ts +17 -9
  199. package/dist/tool-plane.js +38 -17
  200. package/dist/tools.js +2 -2
  201. package/dist/trigger-launch-hook.d.ts +16 -8
  202. package/dist/trigger-launch-hook.js +32 -23
  203. package/dist/trigger-targets.d.ts +18 -8
  204. package/dist/trigger-targets.js +42 -19
  205. package/dist/triggers.d.ts +85 -23
  206. package/dist/triggers.js +303 -96
  207. package/dist/validate.js +1 -1
  208. package/dist/web-fake.js +3 -3
  209. package/dist/web-fetch-direct.d.ts +4 -0
  210. package/dist/web-fetch-direct.js +8 -1
  211. package/dist/web-fetch.d.ts +12 -3
  212. package/dist/web-fetch.js +47 -14
  213. package/dist/web-search.d.ts +33 -4
  214. package/dist/web-search.js +100 -41
  215. package/dist/webhooks.js +4 -5
  216. package/dist/workspace/computer-deps.d.ts +2 -1
  217. package/dist/workspace/computer-deps.js +5 -4
  218. package/dist/workspace/computer-for-claim.d.ts +8 -2
  219. package/dist/workspace/computer-for-claim.js +28 -9
  220. package/dist/workspace/computer-janitor.d.ts +15 -7
  221. package/dist/workspace/computer-janitor.js +33 -8
  222. package/dist/workspace/computer-kept.d.ts +52 -4
  223. package/dist/workspace/computer-kept.js +118 -6
  224. package/dist/workspace/run-end-computers.d.ts +5 -1
  225. package/dist/workspace/run-end-computers.js +27 -1
  226. package/dist/wrapped.d.ts +57 -0
  227. package/dist/wrapped.js +51 -0
  228. package/launcher/agentrun-serve +5 -1
  229. package/package.json +17 -13
  230. package/templates/README.md +10 -9
  231. package/dist/console/assets/index-B_85An2t.js +0 -745
  232. package/dist/console/assets/index-n1YsbnYh.css +0 -1
  233. package/dist/import-sources.d.ts +0 -116
  234. package/dist/import-sources.js +0 -693
@@ -5,7 +5,7 @@
5
5
  // saved under its name with no credential and recording every call; the package applied with the case's parameters and
6
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
7
7
  // 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,
8
+ // 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
9
  // the server's own verdict). Every grader is deterministic but `llm`, which is itself a run on the same
10
10
  // server: a grader agent with no tools that sees the rubric, the run's input, its answer and its calls, never another
11
11
  // grader or an expected answer, and answers {pass, reason}. readCases checks a package's cases without running one.
@@ -15,9 +15,10 @@ import { chmodSync, cpSync, lstatSync, mkdtempSync, readdirSync, readFileSync, r
15
15
  import { tmpdir } from "node:os";
16
16
  import { join } from "node:path";
17
17
  import { parseDocument } from "yaml";
18
- import { answerJson, lastJsonBlock } from "./answer-json.js";
18
+ import { answerJson, jsonBlockOf } from "./answer-json.js";
19
19
  import { correctionsProblems } from "./learn/index.js";
20
20
  import { linkCheck } from "./link-check.js";
21
+ import { frontMatter } from "./manifest.js";
21
22
  import { inputMessage } from "./run-manifest.js";
22
23
  import { shownUrl } from "./mcp-probe.js";
23
24
  import { isMonidName, MCP_SERVER_NAME, MCP_TOOL_NAME, mcpNameOf, mcpToolName, monidNameOf, parseToolName } from "./tool-names.js";
@@ -28,7 +29,7 @@ import { EMAIL_TOOLS } from "./email/names.js";
28
29
  import { CALENDAR_EVENTS } from "./calendar/names.js";
29
30
  import { nameMapOf, settingsKeyOf, shellToolOf } from "./tool-gate.js";
30
31
  import { builtinHarness } from "./harness-table.js";
31
- import { webShownOf } from "./timeline/index.js";
32
+ import { CALLS_PAGE_ROWS, webShownOf } from "./timeline/index.js";
32
33
  import { ASK_TOOL, BOUND_TOOLS } from "./tools.js";
33
34
  import { webFixtureOf } from "./web-fake.js";
34
35
  import { WEB_FETCH_TOOL } from "./web-fetch.js";
@@ -65,7 +66,6 @@ export const GRADER_NAME = "Template eval grader";
65
66
  export const EVAL_HARNESSES = "agentrun-eval-harnesses";
66
67
  /** An owner's data folder is the eval's own server's to open (EvalOptions.data): a named server keeps its own. */
67
68
  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";
68
- const FRONT = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
69
69
  const PROMPT_FIELDS = ["description", "runs", "max_cost_usd", "input"];
70
70
  const CASE_FIELDS = ["parameters", "grants", "mcp", "web", "monid", "learning", "now", "email", "calendar", "feed", "previous"];
71
71
  const GRADER_FIELDS = {
@@ -97,13 +97,15 @@ export class CaseError extends Error {
97
97
  this.problems = problems;
98
98
  }
99
99
  }
100
- /** A file's YAML front matter and body, read as templates.ts reads a package's (core schema, unique keys, no aliases). */
100
+ /** A file's YAML front matter and body, read as a package's are (manifest.ts); an empty one is a mapping with no keys. */
101
101
  function frontOf(text) {
102
- const match = FRONT.exec(text);
103
- if (!match)
102
+ const read = frontMatter(text);
103
+ if (!read)
104
104
  return { data: {}, body: text };
105
- const parsed = yamlOf(match[1]);
106
- return typeof parsed === "string" ? `its front matter ${parsed}` : isObject(parsed) ? { data: parsed, body: text.slice(match[0].length) } : "its front matter is not a mapping";
105
+ if ("problem" in read)
106
+ return `its front matter ${read.problem}`;
107
+ const data = read.data ?? {};
108
+ return isObject(data) ? { data, body: read.body } : "its front matter is not a mapping";
107
109
  }
108
110
  function yamlOf(text) {
109
111
  const doc = parseDocument(text, { schema: "core", merge: false, uniqueKeys: true, strict: true });
@@ -295,7 +297,7 @@ export function readCases(dir, names) {
295
297
  const problems = [];
296
298
  const missing = (names ?? []).filter((name) => !pkg.evals.includes(name));
297
299
  if (missing.length)
298
- throw new CaseError(dir, missing.map((name) => `evals/${name}: no such case (the package's are ${pkg.evals.join(", ") || "none"})`));
300
+ throw new CaseError(dir, missing.map((name) => `evals/${name}: no such case (the package's are ${[...pkg.evals].sort().join(", ") || "none"})`));
299
301
  const cases = [];
300
302
  for (const name of pkg.evals.filter((name) => !names?.length || names.includes(name))) {
301
303
  const at = `evals/${name}`;
@@ -706,8 +708,8 @@ export function outputVerdict(pkg, result) {
706
708
  return { grader: "output", type: "output", cost_usd: null, pass: why === undefined, reason: why === undefined ? `the answer's json meets ${pkg.output.schema}` : `the answer misses ${pkg.output.schema}: ${why}` };
707
709
  }
708
710
  /** The input a grader run gets for an llm grader: the rubric, the clock the run ran on when its case set one (the grader's
709
- * own run is on the real clock), the run's input, its answer (its target field marked when the grader names one), its
710
- * calls and, for a run that searched or fetched, the link check of its cited links (link-check.ts). Never another grader, the case's description or anything the case expects. */
711
+ * own run is on the real clock), the run's input, its answer (its target field marked when the grader names one), the
712
+ * files it left (fitFiles: whole ahead of its calls, which are cut first), its calls and, for a run that searched or fetched, the link check of its cited links (link-check.ts). Never another grader, the case's description or anything the case expects. */
711
713
  export function graderInput(grader, input, run, max = GRADER_PROMPT_MAX) {
712
714
  const target = grader.target ? targetOf(run.answer, grader.target) : undefined;
713
715
  const at = run.now === undefined ? undefined : instantOf(run.now);
@@ -721,12 +723,19 @@ export function graderInput(grader, input, run, max = GRADER_PROMPT_MAX) {
721
723
  // What the run did to its fake mailbox: the messages it added (a draft, a copy in Sent), moved or labelled, and sent.
722
724
  ...(run.mailbox ? [`<mailbox-after untrusted>\nThe run's email account was a fake mailbox (layout ${run.mailbox.after.layout}). What the run left in it:\n${mailboxText(run.mailbox.after)}\n</mailbox-after>`] : []),
723
725
  ];
724
- // Each call with its arguments (else its input's preview), its status and its output's head.
725
- const lines = run.calls.map((call, i) => ({
726
- head: `${i + 1}. ${call.tool}${call.arguments ? ` ${JSON.stringify(call.arguments)}` : call.preview ? ` (${call.preview})` : ""}${call.status ? ` -> ${call.status}` : ""}`,
727
- result: call.result ?? "",
728
- tool: call.name ?? call.tool,
729
- }));
726
+ // The files the run left, ahead of its calls. A call shows a file's bytes only in its arguments or its output, each cut
727
+ // where the timeline cuts it (a string of its arguments at 2,000 characters, its output at CALL_RESULT_CHARS, each
728
+ // ending "..."), and a cut call reads to a grader as a run that did less than its file holds.
729
+ const files = run.finalFiles ?? [];
730
+ const texts = files.filter((file) => file.text !== undefined);
731
+ // Each call with its arguments (else its input's preview), its status and its output's head; a call that names a file
732
+ // shown whole says where it is.
733
+ const lines = run.calls.map((call, i) => {
734
+ const head = `${i + 1}. ${call.tool}${call.arguments ? ` ${JSON.stringify(call.arguments)}` : call.preview ? ` (${call.preview})` : ""}${call.status ? ` -> ${call.status}` : ""}`;
735
+ 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 };
738
+ });
730
739
  // Each call a fake MCP server received, its arguments whole in its log: they are the part a cut may take.
731
740
  const mcpLines = run.mcpCalls.map((call, i) => ({ head: `${i + 1}. ${call.tool}`, result: JSON.stringify(call.arguments ?? {}) }));
732
741
  const wrap = (text) => `<tool-calls untrusted>\n${text}\n</tool-calls>`;
@@ -734,13 +743,18 @@ export function graderInput(grader, input, run, max = GRADER_PROMPT_MAX) {
734
743
  // A run that searched or fetched: each link its answer cites, matched against its web calls' urls in code (link-check.ts).
735
744
  const links = linkCheck(run.answer, run.calls);
736
745
  const linked = links === undefined ? [] : [`<link-check untrusted>\n${links}\n</link-check>`];
737
- // Both lists share the room the rubric, the task, the answer and the link check leave, each in proportion to its whole size.
738
- const room = max - [...before, wrap(""), ...linked, ...(mcpLines.length ? [wrapMcp("")] : [])].reduce((sum, part) => sum + part.length + 2, 0);
746
+ const wrapFiles = (text) => `<files untrusted>\nThe files in the run's work folder when it ended, each text file whole unless marked cut (a call below that shows one only in part shows a cut of it):\n${text}\n</files>`;
747
+ const room = max - [...before, wrap(""), ...linked, ...(mcpLines.length ? [wrapMcp("")] : []), ...(files.length ? [wrapFiles("")] : [])].reduce((sum, part) => sum + part.length + 2, 0);
739
748
  const wholeOf = (list) => list.reduce((sum, one) => sum + one.head.length + one.result.length + 3, 0);
740
749
  const [callsWhole, mcpWhole] = [wholeOf(lines), wholeOf(mcpLines)];
741
- const mcpRoom = callsWhole + mcpWhole <= room ? mcpWhole : Math.floor((room * mcpWhole) / Math.max(1, callsWhole + mcpWhole));
750
+ // The files come first: they take what they need of the room, but no more than leaves the calls a quarter of it (or
751
+ // all they need, when that is less), so a call's result is cut before a file is.
752
+ const shownFiles = files.length ? fitFiles(files, Math.max(0, room - Math.min(callsWhole + mcpWhole, Math.floor(room / 4)))) : undefined;
753
+ // Both call lists share the room the rest leave, each in proportion to its whole size.
754
+ const left = room - (shownFiles === undefined ? 0 : shownFiles.length);
755
+ const mcpRoom = callsWhole + mcpWhole <= left ? mcpWhole : Math.floor((left * mcpWhole) / Math.max(1, callsWhole + mcpWhole));
742
756
  const after = mcpLines.length ? [wrapMcp(fitCalls(mcpLines, mcpRoom, "argument list"))] : [];
743
- return [...before, wrap(lines.length ? fitCalls(lines, room - mcpRoom) : "(none)"), ...linked, ...after].join("\n\n");
757
+ return [...before, ...(shownFiles === undefined ? [] : [wrapFiles(shownFiles)]), wrap(lines.length ? fitCalls(lines, left - mcpRoom) : "(none)"), ...linked, ...after].join("\n\n");
744
758
  }
745
759
  /** A grader's calls, one line each (`head`, then `: <result>`), in at most `room` characters: whole when they fit; else
746
760
  * each result past a length L keeps its first two thirds and last third of L with its middle cut and marked, L the
@@ -754,14 +768,7 @@ export function fitCalls(lines, room, what = "result") {
754
768
  const whole = lines.map((one) => line(one.head, one.result)).join("\n");
755
769
  if (whole.length <= room)
756
770
  return whole;
757
- const said = (cut) => `(Cut to keep this prompt under its cap: ${cut}.)`;
758
- const middle = (text, keep) => {
759
- if (text.length <= keep)
760
- return text;
761
- const marker = ` [... ${text.length - keep} characters cut ...] `;
762
- const tail = Math.floor(keep / 3);
763
- return `${text.slice(0, keep - tail)}${marker}${text.slice(text.length - tail)}`;
764
- };
771
+ const said = saidCut;
765
772
  const webs = lines.map((one) => (one.tool ? webShownOf(one.tool, one.result) : undefined));
766
773
  const LONG = said(`each long ${what} keeps its head and tail, its middle cut where marked${webs.some(Boolean) ? "; a web_search keeps every result's url, title and date, and a web_fetch its url and title, their snippets and page text cut" : ""}`);
767
774
  // What a result cut to `keep` adds to its line, ": " included: the marker a cut adds is at most 40 characters, counted
@@ -812,9 +819,48 @@ export function fitCalls(lines, room, what = "result") {
812
819
  const dropped = heads.length - kept[0].length - kept[1].length;
813
820
  return [said(`every ${what} is left out, and ${dropped} call${dropped === 1 ? "" : "s"} in the middle`), ...kept[0], `[... ${dropped} call${dropped === 1 ? "" : "s"} cut ...]`, ...kept[1]].join("\n");
814
821
  }
815
- /** A grader run's answer read as its verdict: the last json block's (else the last JSON object's) {pass, reason}. */
822
+ /** A cut's note, on the first line of what it cut. */
823
+ const saidCut = (cut) => `(Cut to keep this prompt under its cap: ${cut}.)`;
824
+ /** `text` in at most `keep` characters and its marker: whole when it fits, else its first two thirds and last third of
825
+ * `keep`, its middle cut and marked in place with how much was cut (a marker of at most 40 characters). */
826
+ function middle(text, keep) {
827
+ if (text.length <= keep)
828
+ return text;
829
+ const marker = ` [... ${text.length - keep} characters cut ...] `;
830
+ const tail = Math.floor(keep / 3);
831
+ return `${text.slice(0, keep - tail)}${marker}${text.slice(text.length - tail)}`;
832
+ }
833
+ /** 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
+ * 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
+ * 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. */
837
+ export function fitFiles(files, room) {
838
+ const block = (file, text) => `<file path="${file.path}" bytes="${file.bytes}">\n${text}\n</file>`;
839
+ const texts = files.filter((file) => file.text !== undefined);
840
+ 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(", ")}`] : [];
842
+ const whole = [...texts.map((file) => block(file, file.text)), ...named].join("\n");
843
+ if (whole.length <= room)
844
+ return whole;
845
+ const LONG = saidCut("each long file keeps its head and tail, its middle cut where marked");
846
+ const size = (keep) => LONG.length + 1 + texts.reduce((sum, file) => sum + block(file, "").length + (file.text.length <= keep ? file.text.length : keep + 40) + 1, 0) + named.reduce((sum, line) => sum + line.length, 0);
847
+ if (texts.length && size(0) <= room) {
848
+ let [low, top] = [0, Math.max(...texts.map((file) => file.text.length))];
849
+ while (low < top) {
850
+ const mid = Math.ceil((low + top) / 2);
851
+ if (size(mid) <= room)
852
+ low = mid;
853
+ else
854
+ top = mid - 1;
855
+ }
856
+ return [LONG, ...texts.map((file) => block(file, middle(file.text, low))), ...named].join("\n");
857
+ }
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");
859
+ return list.length <= room ? list : room < 4 ? "" : `${list.slice(0, room - 4)} ...`;
860
+ }
861
+ /** A grader run's answer read as its verdict: its json block's (jsonBlockOf), else the last flat JSON object's, {pass, reason}. */
816
862
  export function verdictOf(answer) {
817
- const candidates = [lastJsonBlock(answer), ...[...answer.matchAll(/\{[^{}]*"pass"[^{}]*\}/g)].map((m) => m[0]).reverse()];
863
+ const candidates = [jsonBlockOf(answer), ...[...answer.matchAll(/\{[^{}]*"pass"[^{}]*\}/g)].map((m) => m[0]).reverse()];
818
864
  for (const text of candidates) {
819
865
  if (text === undefined)
820
866
  continue;
@@ -881,7 +927,7 @@ async function bytesOf(req) {
881
927
  return Buffer.concat(chunks);
882
928
  }
883
929
  /** A client of the v2 API at `baseUrl` (ending in /v2) with `token`. */
884
- function apiOf(baseUrl, token) {
930
+ export function apiOf(baseUrl, token) {
885
931
  return async (method, path, body, headers = {}, options = {}) => {
886
932
  const raw = typeof body === "string";
887
933
  // The console's page takes a write from its session only with a JSON body type, a body or not (page.ts answerPage):
@@ -902,6 +948,8 @@ function apiOf(baseUrl, token) {
902
948
  return { status: res.status, body: null };
903
949
  }
904
950
  const text = await res.text();
951
+ if (options.text)
952
+ return { status: res.status, body: text, headers: res.headers };
905
953
  let json = text;
906
954
  try {
907
955
  json = JSON.parse(text);
@@ -923,20 +971,36 @@ function expectOk(what, answered, ok = [200, 201, 202]) {
923
971
  throw new ApiFailure(`${what}: ${answered.status} ${typeof error?.message === "string" ? error.message : JSON.stringify(answered.body).slice(0, 300)}${fields}`);
924
972
  }
925
973
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
974
+ /** How long the run read that asks whether a runner holds a queued run may take. */
975
+ export const CLAIM_READ_TIMEOUT_MS = 10_000;
976
+ /** Whether a runner holds the run now (the run read's `claim`); undefined when the read fails, takes over
977
+ * CLAIM_READ_TIMEOUT_MS or is stopped by `signal` (the eval's stop): not known, so never a reason to cancel the run. */
978
+ async function heldNow(api, runId, signal) {
979
+ const timeout = AbortSignal.timeout(CLAIM_READ_TIMEOUT_MS);
980
+ const read = await api("GET", `/runs/${runId}`, undefined, {}, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout }).catch(() => undefined);
981
+ return read?.status === 200 && isObject(read.body) ? isObject(read.body.claim) : undefined;
982
+ }
926
983
  /** A run waited for: its rows until it ends (completed, failed, cancelled) or waits on a person (input_required), or
927
984
  * `deadline` passes (then it is cancelled). A stop of the eval (`signal`) cancels it too, and throws. */
928
985
  async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIMEOUT_MS) {
929
986
  const view = new Map();
930
987
  let after = 0;
931
- // A run nobody takes stays queued: given up on after queueTimeoutMs, by name, never left to the whole deadline.
932
- const queuedUntil = Date.now() + queueTimeoutMs;
988
+ const started = Date.now();
989
+ // A run nobody takes stays queued: given up on once it has gone queueTimeoutMs with no runner holding it, by name, never
990
+ // left to the whole deadline. A run's view reads queued until its first rows show, held or not (a slow start on a busy
991
+ // machine), so a queued page past the bound asks the run read whether a runner holds it now: one does, and the bound
992
+ // starts again from now, so a run a runner keeps holding is waited for to its own deadline. A read that doesn't answer
993
+ // (failed, stalled past its bound, or stopped) says neither: it is asked again at the next page, and the stop and the
994
+ // deadline still end the wait.
995
+ let queuedUntil = started + queueTimeoutMs;
933
996
  for (;;) {
934
997
  if (signal?.aborted) {
935
998
  await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
936
999
  signal.throwIfAborted();
937
1000
  }
938
- // calls=whole: each call's arguments and its output's head (tool_input, tool_result_text), which its graders read.
939
- const page = expectOk(`reading run ${runId}'s timeline`, await api("GET", `/runs/${runId}/timeline?after=${after}&wait_ms=5000&calls=whole`));
1001
+ // calls=whole: each call's arguments and its output, whole to CALL_RESULT_CHARS (tool_input, tool_result_text), which its graders read.
1002
+ // CALLS_PAGE_ROWS rows a page, the most a calls=whole page holds (an older server's default is 500).
1003
+ const page = expectOk(`reading run ${runId}'s timeline`, await api("GET", `/runs/${runId}/timeline?after=${after}&wait_ms=5000&calls=whole&limit=${CALLS_PAGE_ROWS}`));
940
1004
  if (page.reset)
941
1005
  view.clear();
942
1006
  for (const id of page.drop ?? [])
@@ -953,12 +1017,17 @@ async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIME
953
1017
  return { status, rows, waiting: typeof waiting?.summary === "string" ? waiting.summary : "it waits on a person" };
954
1018
  }
955
1019
  if (status === "queued" && Date.now() > queuedUntil) {
956
- await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
957
- return { status: "timed_out", rows, why: `the run stayed queued for ${Math.round(queueTimeoutMs / 1000)} s: no runner took it (state ${String(page.state)}), and it was cancelled` };
1020
+ const held = await heldNow(api, runId, signal);
1021
+ if (held === true)
1022
+ queuedUntil = Date.now() + queueTimeoutMs;
1023
+ else if (held === false) {
1024
+ await api("POST", `/runs/${runId}/cancel`, {}).catch(() => undefined);
1025
+ return { status: "timed_out", rows, why: `the run stayed queued for ${Math.round(queueTimeoutMs / 1000)} s with no runner holding it, and it was cancelled` };
1026
+ }
958
1027
  }
959
1028
  if (Date.now() > deadline) {
960
1029
  await api("POST", `/runs/${runId}/cancel`, {});
961
- return { status: "timed_out", rows, why: `the run took longer than ${Math.round((deadline - (queuedUntil - queueTimeoutMs)) / 1000)} s (state ${String(page.state)} when the wait gave up) and was cancelled` };
1030
+ return { status: "timed_out", rows, why: `the run took longer than ${Math.round((deadline - started) / 1000)} s (state ${String(page.state)} when the wait gave up) and was cancelled` };
962
1031
  }
963
1032
  if (page.has_more !== true && page.unchanged === true)
964
1033
  await sleep(250);
@@ -968,7 +1037,7 @@ async function waitRun(api, runId, deadline, signal, queueTimeoutMs = QUEUE_TIME
968
1037
  * shell tool held to bash's setting (bash_background, bash_output, ...) keeps its own name, so its grader sees it. A
969
1038
  * call on a saved server `toolkits` names ({<saved server>: <the package's toolkit>}, a need an owner's server filled
970
1039
  * under another name) is named on the package's toolkit, as the package's graders name it. Each with its arguments and
971
- * its output's head as the rows of a calls=whole read carry them (tool_input, tool_result_text), else its previews. */
1040
+ * its output as the rows of a calls=whole read carry them (tool_input, tool_result_text), else its previews. */
972
1041
  export function callsOf(rows, harness, toolkits = {}) {
973
1042
  const results = new Map(rows.filter((row) => row.kind === "tool_result" && row.tool_use_id).map((row) => [String(row.tool_use_id), row]));
974
1043
  // The rows are a server's, read over its API: the names are the built-in harness's, the only facts known here.
@@ -981,28 +1050,73 @@ export function callsOf(rows, harness, toolkits = {}) {
981
1050
  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 };
982
1051
  });
983
1052
  }
984
- /** Every file path of a run's work folder (the files route, page by page). */
1053
+ /** Every file of a run's work folder (the files route, page by page). */
985
1054
  async function filesOf(api, runId) {
986
- const paths = [];
1055
+ const files = [];
987
1056
  for (let cursor = null;;) {
988
1057
  const page = await api("GET", `/runs/${runId}/files${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`);
989
1058
  if (page.status !== 200 || !isObject(page.body))
990
- return paths;
991
- for (const file of page.body.files ?? [])
1059
+ return files;
1060
+ for (const file of page.body.files ?? []) {
992
1061
  if (typeof file.path === "string")
993
- paths.push(file.path);
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 });
1063
+ }
994
1064
  cursor = typeof page.body.next_cursor === "string" ? page.body.next_cursor : null;
995
1065
  if (!cursor)
996
- return paths;
1066
+ return files;
997
1067
  }
998
1068
  }
1069
+ const filePath = (runId, path) => `/runs/${runId}/files/${path.split("/").map(encodeURIComponent).join("/")}`;
1070
+ /** A type a file's bytes are text in: text/*, JSON and NDJSON. A file the server gives no type (an extension it does not
1071
+ * know: .srt, .vtt, .yaml) is read too: the server answers its text when its bytes are UTF-8 with no NUL, else 415. */
1072
+ const TEXT_TYPE = /^(text\/|application\/(json|x-ndjson)\b)/;
1073
+ /** How long one read of a run's final file may take, its body included: a server that stalls mid-file leaves that file's
1074
+ * text out, and the eval goes on. */
1075
+ export const FILE_READ_TIMEOUT_MS = 10_000;
1076
+ /** How long all of a run's final file reads may take together: past it, the files not yet read are listed by size alone. */
1077
+ export const FILE_READS_TIMEOUT_MS = 30_000;
1078
+ /** A run's final files for its llm graders: each text file's whole text, read smallest first while the texts read stay
1079
+ * within GRADER_PROMPT_MAX UTF-8 bytes in all (one grader input holds that many characters, and a character is at least
1080
+ * a byte), every other file by its size alone. Each is read under the run's own cut, on the server that holds its
1081
+ * secrets (`?cut=run`, run-reads-over-store.ts cutRunFile): every value its timeline's calls are cut of, and every secret
1082
+ * shape, is "[redacted]" in the text a grader sees. An answer without the cut's mark (`x-agentrun-cut: run`: a server
1083
+ * that doesn't know the cut and would serve the raw bytes) leaves the text out. A read that fails, is refused (403, 413,
1084
+ * 415), takes longer than `readTimeoutMs`, or would pass the budget leaves that file's text out, never the grade, and
1085
+ * the files after it are still read; past FILE_READS_TIMEOUT_MS in all, the rest are left out. In the listing's order. */
1086
+ export async function finalFilesOf(api, runId, listed, signal, readTimeoutMs = FILE_READ_TIMEOUT_MS) {
1087
+ const texts = new Map();
1088
+ let left = GRADER_PROMPT_MAX;
1089
+ const until = Date.now() + Math.max(FILE_READS_TIMEOUT_MS, readTimeoutMs);
1090
+ for (const file of [...listed].filter((one) => !one.unreadable && (one.type === null || TEXT_TYPE.test(one.type))).sort((a, b) => a.bytes - b.bytes)) {
1091
+ if (file.bytes > left)
1092
+ continue;
1093
+ signal?.throwIfAborted();
1094
+ const remaining = until - Date.now();
1095
+ if (remaining <= 0)
1096
+ break;
1097
+ const bound = AbortSignal.timeout(Math.min(readTimeoutMs, remaining));
1098
+ const read = await api("GET", `${filePath(runId, file.path)}?cut=run`, undefined, {}, { text: true, signal: signal ? AbortSignal.any([signal, bound]) : bound }).catch((error) => {
1099
+ if (signal?.aborted)
1100
+ throw error;
1101
+ return undefined;
1102
+ });
1103
+ if (read?.status !== 200 || read.headers?.get("x-agentrun-cut") !== "run" || typeof read.body !== "string")
1104
+ continue;
1105
+ const bytes = Buffer.byteLength(read.body);
1106
+ if (bytes > left)
1107
+ continue;
1108
+ texts.set(file.path, read.body);
1109
+ left -= bytes;
1110
+ }
1111
+ return listed.map((file) => ({ path: file.path, bytes: file.bytes, ...(texts.has(file.path) ? { text: texts.get(file.path) } : {}) }));
1112
+ }
999
1113
  /** Each path a file_exists grader names that the run's work folder holds, read one by one (GET /runs/{id}/files/{path}):
1000
1114
  * the listing is capped (its `truncated`), so a file past its cap or depth is never taken for absent. Only the status
1001
1115
  * is read: the file's body is cancelled unread, whatever its size. */
1002
1116
  async function presentOf(api, runId, paths) {
1003
1117
  const present = [];
1004
1118
  for (const path of new Set(paths)) {
1005
- const read = await api("GET", `/runs/${runId}/files/${path.split("/").map(encodeURIComponent).join("/")}`, undefined, {}, { statusOnly: true });
1119
+ const read = await api("GET", filePath(runId, path), undefined, {}, { statusOnly: true });
1006
1120
  if (read.status === 200)
1007
1121
  present.push(path);
1008
1122
  }
@@ -1107,7 +1221,7 @@ export async function evalTemplate(options) {
1107
1221
  const { withoutFaux } = await import("./model.js");
1108
1222
  const serveOptions = options.serve ?? {};
1109
1223
  // Its run lines go to stderr: stdout is the eval's report.
1110
- const beside = await runnerBeside(data, { mcpLoopback: serve.localInstall, mcpOwn: serve.own, evalFakes: (agentId) => fakes.get(agentId), harnessInstall, onLine: (line) => console.error(line), ...(serveOptions.faux ? { env: { ...withoutFaux(process.env), ...fauxEnvOf({ data: data, ...serveOptions }) } } : {}) }).catch(async (error) => {
1224
+ const beside = await runnerBeside(data, { mcpLoopback: serve.localInstall, mcpOwn: serve.own, ollamaHost: serve.ollamaHost, evalFakes: (agentId) => fakes.get(agentId), harnessInstall, onLine: (line) => console.error(line), ...(serveOptions.faux ? { env: { ...withoutFaux(process.env), ...fauxEnvOf({ data: data, ...serveOptions }) } } : {}) }).catch(async (error) => {
1111
1225
  await closeServe();
1112
1226
  removeTree(scratch);
1113
1227
  throw error;
@@ -1436,10 +1550,16 @@ async function runOnce(ctx, one, n, fakes, mail, feeds) {
1436
1550
  made.triggers.add(one.trigger_id);
1437
1551
  }
1438
1552
  await deleteTriggers(api, made, true);
1439
- if (via !== undefined && !kept)
1440
- throw new ApiFailure(`the apply made no trigger named ${via}`);
1441
1553
  if (kept)
1442
1554
  made.triggers.add(kept);
1555
+ // A server under AGENTRUN_RUN_KEYS=1 takes a key it lacks from each run, and says so in the apply's warning at
1556
+ // secrets.<NAME>; an eval's runs carry no keys, so each would be refused. The eval stops before any, as for a case that
1557
+ // does not check (its agent removed with the case).
1558
+ const owed = (Array.isArray(applied.warnings) ? applied.warnings : []).flatMap((warning) => (isObject(warning) && warning.reason === "not_set_up_here" && typeof warning.field === "string" && warning.field.startsWith("secrets.") ? [warning.field.slice("secrets.".length)] : []));
1559
+ if (owed.length)
1560
+ throw new CaseError(ctx.options.dir, [`the server takes ${owed.join(" and ")} from each run (AGENTRUN_RUN_KEYS=1), and an eval's runs carry no keys: run it without --server, or on a server that holds ${owed.length > 1 ? "them" : "it"}`]);
1561
+ if (via !== undefined && !kept)
1562
+ throw new ApiFailure(`the apply made no trigger named ${via}`);
1443
1563
  const agent = expectOk(`reading the agent ${agentId}`, await api("GET", `/agents/${encodeURIComponent(agentId)}`));
1444
1564
  // The saved server the apply gave each need ({toolkit: server}; null for a need it left unset).
1445
1565
  const used = Object.fromEntries(Object.entries(isObject(applied.servers) ? applied.servers : {}).filter((entry) => typeof entry[1] === "string"));
@@ -1532,14 +1652,15 @@ async function ranOnce(ctx, one, n, fakes, agent, agentId, runId, used, fired) {
1532
1652
  stopped();
1533
1653
  const result = isObject(view.result) ? view.result : {};
1534
1654
  const harness = isObject(agent.definition) && typeof agent.definition.harness === "string" ? agent.definition.harness : "pi";
1655
+ const listed = await filesOf(api, runId);
1535
1656
  const record = {
1536
1657
  answer: typeof result.final_answer === "string" ? result.final_answer : "",
1537
1658
  calls: callsOf(ended.rows, harness, Object.fromEntries(Object.entries(used).map(([toolkit, server]) => [server, toolkit]))),
1538
1659
  mcpCalls: fakes.flatMap((fake) => fake.calls.map((call) => ({ ...call }))),
1539
1660
  files: await (async () => {
1540
- const listed = await filesOf(api, runId);
1661
+ const paths = listed.map((file) => file.path);
1541
1662
  const named = one.graders.flatMap((grader) => (grader.type === "file_exists" ? [grader.path] : []));
1542
- return [...listed, ...(await presentOf(api, runId, named.filter((path) => !listed.includes(path))))];
1663
+ return [...paths, ...(await presentOf(api, runId, named.filter((path) => !paths.includes(path))))];
1543
1664
  })(),
1544
1665
  ...(one.now !== undefined ? { now: one.now } : {}),
1545
1666
  ...(mailbox ? { mailbox } : {}),
@@ -1560,6 +1681,9 @@ async function ranOnce(ctx, one, n, fakes, agent, agentId, runId, used, fired) {
1560
1681
  : !graded ? `the run ended ${ended.status}${pending ? ` (${pending})` : ""}${isObject(view.error) && typeof view.error.message === "string" ? `: ${view.error.message}` : ""}`
1561
1682
  : undefined;
1562
1683
  const output = ended.status === "completed" ? outputVerdict(ctx.pkg, view.result) : undefined;
1684
+ // The files it left, read whole for its llm graders: only a run they grade, so a case of other graders reads none.
1685
+ if (graded && one.graders.some((grader) => grader.type === "llm"))
1686
+ record.finalFiles = await finalFilesOf(api, runId, listed, options.signal, options.fileReadTimeoutMs);
1563
1687
  const graders = output ? [output] : [];
1564
1688
  for (const grader of one.graders) {
1565
1689
  stopped();
@@ -8,7 +8,8 @@ import { packageSha256 } from "./agent-package.js";
8
8
  import { ApiError, invalid } from "./errors.js";
9
9
  import { UPLOAD_PREFIX } from "./store/index.js";
10
10
  import { fetchPackageFiles, ImportRefused, IMPORT_LIMITS, parseSource, resolveSha } from "./template-source.js";
11
- import { MANIFEST, manifestName, memoryFiles, PackageError, readPackage } from "./templates.js";
11
+ import { manifestOf } from "./manifest.js";
12
+ import { MANIFEST, memoryFiles, PackageError, readPackage } from "./templates.js";
12
13
  import { isObject, unknownFields } from "./validate.js";
13
14
  /** The settings key that holds the GitHub accounts this server's owner trusts as publishers, lower-cased. */
14
15
  export const TRUSTED_PUBLISHERS = "templates.trusted_publishers";
@@ -163,7 +164,8 @@ async function uploadTemplate(deps, raw, dryRun) {
163
164
  let files;
164
165
  try {
165
166
  files = uploadFiles(raw);
166
- const id = `${UPLOAD_PREFIX}${manifestName(files.get(MANIFEST)?.toString("utf8") ?? "") ?? ""}`;
167
+ const name = manifestOf(files.get(MANIFEST)?.toString("utf8") ?? "")?.name;
168
+ const id = `${UPLOAD_PREFIX}${typeof name === "string" ? name : ""}`;
167
169
  pkg = importedPackage(id, { source: id, sha: uploadSha(files), publisher: "" }, files);
168
170
  }
169
171
  catch (error) {
@@ -32,6 +32,11 @@ export declare const INPUT_TYPES: readonly ["string", "number", "integer", "bool
32
32
  * formats it knows. cron and timezone are for the form alone (a schedule picker, a zone choice); where a parameter fills
33
33
  * a schedule, the schedule's own check reads the value at apply. */
34
34
  export declare const INPUT_FORMATS: readonly ["uri", "email", "hostname", "date", "date-time", "uuid", "cron", "timezone"];
35
+ /** An input's or a parameter's keys: what a form and a JSON Schema say of one field, in the order an export writes them
36
+ * (agent-package.ts). */
37
+ export declare const INPUT_KEYS: readonly ["type", "title", "description", "pattern", "format", "minLength", "maxLength", "minimum", "maximum", "enum", "examples", "default", "required", "items"];
38
+ /** A list input's `items`: a scalar's keys alone. */
39
+ export declare const ITEM_KEYS: readonly ["type", "pattern", "format", "minLength", "maxLength", "minimum", "maximum", "enum"];
35
40
  /** The keys a package may need: those Settings saves (a tool's or a model provider's), each one a run is handed. */
36
41
  export declare const PACKAGE_SECRETS: readonly string[];
37
42
  /** A package's bounds: each file, all its files together (POST /agents' own body limit), and how many it holds. */
@@ -41,9 +46,6 @@ export declare const MAX_PACKAGE_FILES = 256;
41
46
  /** A file of a package's evals/ (a case's fake MCP server fixture, say), which no agent is given: its own bound, apart
42
47
  * from the agent's files' limits above. The answer's schema is given to the agent, so under evals/ too it keeps those. */
43
48
  export declare const MAX_EVAL_FILE_BYTES: number;
44
- /** The `name` agent.md's front matter gives (`text`), as text, or undefined: what an upload's folder is named before
45
- * readPackage checks it whole (the name read as readPackage's front matter reads it). */
46
- export declare function manifestName(text: string): string | undefined;
47
49
  /** An MCP server a package uses, by where it comes from (`source`, `toolkit`), never by the name an owner saves it under:
48
50
  * inside the package its tools are `mcp:<toolkit>/<tool>`. `tools`, those the agent uses and the package asks the owner to
49
51
  * grant (a consent screen shows each, with `reason`), and `allow`, those of them expected to run without asking (reads);
package/dist/templates.js CHANGED
@@ -9,6 +9,7 @@ import { basename, join } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { parseDocument } from "yaml";
11
11
  import { invalid } from "./errors.js";
12
+ import { frontMatter } from "./manifest.js";
12
13
  import { DOCKER_IMAGE_FIX, needsIssues } from "./computer-needs.js";
13
14
  // Where a package's MCP tools come from (a Composio toolkit, GitHub's MCP server, or any other server by its address): a
14
15
  // saved MCP server records one too, and apply maps each need to a server whose record matches.
@@ -55,10 +56,11 @@ export const INPUT_TYPES = [...SCALAR_TYPES, "array"];
55
56
  * formats it knows. cron and timezone are for the form alone (a schedule picker, a zone choice); where a parameter fills
56
57
  * a schedule, the schedule's own check reads the value at apply. */
57
58
  export const INPUT_FORMATS = ["uri", "email", "hostname", "date", "date-time", "uuid", "cron", "timezone"];
58
- /** An input's or a parameter's keys: what a form and a JSON Schema say of one field. */
59
- const INPUT_KEYS = ["type", "required", "pattern", "enum", "format", "default", "description", "title", "examples", "minimum", "maximum", "minLength", "maxLength", "items"];
59
+ /** An input's or a parameter's keys: what a form and a JSON Schema say of one field, in the order an export writes them
60
+ * (agent-package.ts). */
61
+ export const INPUT_KEYS = ["type", "title", "description", "pattern", "format", "minLength", "maxLength", "minimum", "maximum", "enum", "examples", "default", "required", "items"];
60
62
  /** A list input's `items`: a scalar's keys alone. */
61
- const ITEM_KEYS = ["type", "pattern", "enum", "format", "minimum", "maximum", "minLength", "maxLength"];
63
+ export const ITEM_KEYS = ["type", "pattern", "format", "minLength", "maxLength", "minimum", "maximum", "enum"];
62
64
  const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
63
65
  const PARAMETER = /^[a-z][a-z0-9_]{0,63}$/;
64
66
  /** The keys a package may need: those Settings saves (a tool's or a model provider's), each one a run is handed. */
@@ -85,24 +87,6 @@ const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[
85
87
  const PLACEHOLDER = /\$\{parameters\.([^}]*)\}/g;
86
88
  /** Text that is one placeholder alone: it takes the parameter's value with its type (a pin's, a trigger's input's). */
87
89
  const WHOLE = /^\$\{parameters\.([^}]*)\}$/;
88
- const FRONT = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
89
- /** The `name` agent.md's front matter gives (`text`), as text, or undefined: what an upload's folder is named before
90
- * readPackage checks it whole (the name read as readPackage's front matter reads it). */
91
- export function manifestName(text) {
92
- const match = FRONT.exec(text);
93
- if (!match)
94
- return undefined;
95
- const doc = parseDocument(match[1], { schema: "core", merge: false, uniqueKeys: true, strict: true });
96
- if (doc.errors.length)
97
- return undefined;
98
- try {
99
- const data = doc.toJS({ maxAliasCount: 0 });
100
- return isObject(data) && typeof data.name === "string" ? data.name : undefined;
101
- }
102
- catch {
103
- return undefined;
104
- }
105
- }
106
90
  /** A package's model choices at most, a choice label's length, and a warning's or a note's. */
107
91
  const MAX_CHOICES = 3;
108
92
  const MAX_CHOICE_LABEL = 40;
@@ -531,9 +515,12 @@ export function readPackage(from, { evalFixtures = true } = {}) {
531
515
  const dir = src.where;
532
516
  const problems = [];
533
517
  const bad = (where, message) => void problems.push(`${where}: ${message}`);
518
+ /** The entries of the folder at `sub`, every read of a folder's entries here: a hidden file or folder (.env,
519
+ * .DS_Store, .cache/) is no part of a package, at its top or anywhere under it, so it is left out, never refused. */
520
+ const entries = (sub) => src.entries(sub).filter((entry) => !entry.name.startsWith("."));
534
521
  /** The regular files under `sub`, by path from it with forward slashes; a link or any other kind of entry is a
535
522
  * problem (a package is read from disk, and a link would carry a file from outside it into an agent). */
536
- const files = (sub) => src.entries(sub).sort((a, b) => (a.name < b.name ? -1 : 1)).flatMap((entry) => {
523
+ const files = (sub) => entries(sub).sort((a, b) => (a.name < b.name ? -1 : 1)).flatMap((entry) => {
537
524
  const path = sub ? `${sub}/${entry.name}` : entry.name;
538
525
  if (entry.isDirectory())
539
526
  return files(path);
@@ -546,25 +533,17 @@ export function readPackage(from, { evalFixtures = true } = {}) {
546
533
  /** A file's YAML front matter and body. */
547
534
  const front = (path, required = true) => {
548
535
  const content = text(path);
549
- const match = FRONT.exec(content);
550
- if (!match) {
536
+ const read = frontMatter(content);
537
+ if (!read) {
551
538
  if (required)
552
539
  bad(path, "has no YAML front matter between --- lines");
553
540
  return required ? undefined : { data: {}, body: content };
554
541
  }
555
- const doc = parseDocument(match[1], { schema: "core", merge: false, uniqueKeys: true, strict: true });
556
- if (doc.errors.length)
557
- return bad(path, `its front matter is not YAML: ${doc.errors[0].message.split("\n")[0]}`), undefined;
558
- let data;
559
- try {
560
- data = doc.toJS({ maxAliasCount: 0 });
561
- }
562
- catch (error) {
563
- return bad(path, `its front matter is refused: ${error.message}`), undefined;
564
- }
565
- if (!isObject(data))
542
+ if ("problem" in read)
543
+ return bad(path, `its front matter ${read.problem}`), undefined;
544
+ if (!isObject(read.data))
566
545
  return bad(path, "its front matter is not a mapping"), undefined;
567
- return { data, body: content.slice(match[0].length) };
546
+ return { data: read.data, body: read.body };
568
547
  };
569
548
  const list = (value, field, test = (item) => item !== "") => {
570
549
  if (value === undefined)
@@ -582,7 +561,7 @@ export function readPackage(from, { evalFixtures = true } = {}) {
582
561
  throw new PackageError(dir, ["it is not a folder: a package is one"]);
583
562
  if (kind(MANIFEST) !== "file")
584
563
  throw new PackageError(dir, [`${MANIFEST}: missing: a package is a folder with agent.md (its manifest in the front matter, the agent's instructions in the body)`]);
585
- for (const entry of src.entries("")) {
564
+ for (const entry of entries("")) {
586
565
  if (entry.isDirectory() && !["skills", "rules", "evals"].includes(entry.name))
587
566
  bad(`${entry.name}/`, "a package's folders are skills/, rules/ and evals/");
588
567
  }
@@ -883,7 +862,7 @@ export function readPackage(from, { evalFixtures = true } = {}) {
883
862
  });
884
863
  // skills/<name>/SKILL.md, each named as its folder and described, as Agent Skills are; rules/*.md beside each.
885
864
  const skills = {};
886
- const skillDirs = kind("skills") === "dir" ? src.entries("skills") : [];
865
+ const skillDirs = kind("skills") === "dir" ? entries("skills") : [];
887
866
  for (const entry of skillDirs) {
888
867
  if (!entry.isDirectory() || !NAME.test(entry.name)) {
889
868
  bad(`skills/${entry.name}`, "skills/ holds only skill folders, each named in lowercase letters, digits and dashes");
@@ -900,7 +879,7 @@ export function readPackage(from, { evalFixtures = true } = {}) {
900
879
  for (const path of own)
901
880
  skills[`${entry.name}/${path}`] = text(`skills/${entry.name}/${path}`);
902
881
  }
903
- const rules = kind("rules") === "dir" ? src.entries("rules") : [];
882
+ const rules = kind("rules") === "dir" ? entries("rules") : [];
904
883
  if (rules.length && !skillDirs.length)
905
884
  bad("rules/", "rules ship beside each skill's SKILL.md, and the package has no skill");
906
885
  const ruleNames = [];
@@ -924,7 +903,7 @@ export function readPackage(from, { evalFixtures = true } = {}) {
924
903
  // evals/<case>/: prompt.md (the run's input), graders/*.md (each its type in its front matter), case.yaml and
925
904
  // fixtures/ if it has them. The layout only: no eval runs here.
926
905
  const evals = [];
927
- for (const entry of kind("evals") === "dir" ? src.entries("evals") : []) {
906
+ for (const entry of kind("evals") === "dir" ? entries("evals") : []) {
928
907
  const at = `evals/${entry.name}`;
929
908
  if (!entry.isDirectory() || !NAME.test(entry.name)) {
930
909
  bad(at, "evals/ holds only case folders, each named in lowercase letters, digits and dashes");
@@ -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";