@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30

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 (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,147 @@
1
+ // pdf_pages: a document's first pages as PNG files in the run's work directory, and its text, for a workflow's call node
2
+ // `via: "tool"`. The document is a file name under the server's documents directory (`--documents`,
3
+ // AGENTRUN_SERVE_DOCUMENTS) or the run's work directory, confined to it. Pages are drawn by poppler's pdftoppm into
4
+ // `work/pages/<stem>/<dpi>/<n>.png`, the stem the document's own (pagesStem), at the asked dpi lowered so a page's long
5
+ // side stays within MAX_PAGE_PX (Jev's image limit); the dpi used is in the answer and the path, so a draw at another
6
+ // dpi never replaces an image an earlier receipt points to. A PNG or JPEG passes through as its one page, scaled down
7
+ // with ffmpeg when a side is over the cap. The image refs it answers are work-relative, the form a decision node's
8
+ // `images` takes.
9
+ import { execFile } from "node:child_process";
10
+ import { createHash } from "node:crypto";
11
+ import { copyFile, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat } from "node:fs/promises";
12
+ import { basename, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
+ import { promisify } from "node:util";
14
+ export const PDF_PAGES_TOOL = "pdf_pages";
15
+ /** The read-only directory a run's documents are read from: the server's `--documents`. */
16
+ export const DOCUMENTS_ENV = "AGENTRUN_SERVE_DOCUMENTS";
17
+ const TEXT_CAP = 20_000;
18
+ const MAX_PAGES = 50;
19
+ /** The longest side a drawn page may have, in pixels: Jev's image limit (1568 per side; 1569 is refused). */
20
+ export const MAX_PAGE_PX = 1568;
21
+ const run = promisify(execFile);
22
+ const inside = (base, path) => {
23
+ const rel = relative(base, path);
24
+ return rel !== "" && !rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel);
25
+ };
26
+ /** `path` under `base`, symlinks resolved, or undefined when it is not a file there. */
27
+ async function confined(base, path) {
28
+ const root = await realpath(base).catch(() => undefined);
29
+ if (!root)
30
+ return undefined;
31
+ const asked = resolve(root, path);
32
+ if (!inside(root, asked))
33
+ return undefined;
34
+ const real = await realpath(asked).catch(() => undefined);
35
+ if (!real || !inside(root, real))
36
+ return undefined;
37
+ return (await stat(real)).isFile() ? real : undefined;
38
+ }
39
+ /** Where a document named `path` is, the documents directory first, then the run's work directory: the file, which of
40
+ * the two holds it, and its path below that one, links resolved (`confined`'s check, so never outside it). */
41
+ async function locate(path, where) {
42
+ if (typeof path !== "string" || !path.trim())
43
+ throw new Error("pdf_pages: path is a file name");
44
+ if (isAbsolute(path))
45
+ throw new Error(`pdf_pages: path ${path} is absolute; name a file under the documents or the run's work directory`);
46
+ for (const [base, dir] of [["documents", where.documents], ["work", where.work]]) {
47
+ if (!dir)
48
+ continue;
49
+ const found = await confined(dir, path);
50
+ if (found)
51
+ return { file: found, base, rel: relative(await realpath(dir), found) };
52
+ }
53
+ throw new Error(`pdf_pages: no file ${path} under the documents${where.documents ? "" : " (this server has no --documents)"} or the run's work directory`);
54
+ }
55
+ /** Where a document named `path` is: the documents directory first, then the run's work directory. */
56
+ export async function documentPath(path, where) {
57
+ return (await locate(path, where)).file;
58
+ }
59
+ /** The one directory name a document's pages are drawn under, in `work/pages/`: its path below the documents (or work)
60
+ * directory without the extension, each run of other characters than letters, digits, `.`, `_` and `-` (a `/` too)
61
+ * made `_`, cut to its last 48 characters with no leading dot, then `-` and 12 hex characters of the sha256 of which
62
+ * directory and that path. So two documents of one file name in different folders never share a page, the same file
63
+ * always draws under the same name (through a link too), and the name is never a separator, `.` or `..`. */
64
+ export function pagesStem({ base, rel }) {
65
+ const path = rel.split(sep).join("/");
66
+ const readable = path.slice(0, path.length - extname(path).length).replace(/[^A-Za-z0-9._-]+/g, "_").slice(-48).replace(/^\.+/, "") || "doc";
67
+ return `${readable}-${createHash("sha256").update(`${base}:${path}`).digest("hex").slice(0, 12)}`;
68
+ }
69
+ const integer = (value, fallback, min, max, name) => {
70
+ if (value === undefined || value === null)
71
+ return fallback;
72
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max)
73
+ throw new Error(`pdf_pages: ${name} is an integer from ${min} to ${max}`);
74
+ return value;
75
+ };
76
+ /** The pages and text of the document `args.path`, drawn into `where.work`. */
77
+ export async function pdfPages(args, where) {
78
+ const located = await locate(args.path, where);
79
+ const file = located.file;
80
+ const maxPages = integer(args.maxPages, 3, 1, MAX_PAGES, "maxPages");
81
+ const dpi = integer(args.dpi, 110, 36, 300, "dpi");
82
+ const name = basename(file);
83
+ const ext = extname(name).toLowerCase();
84
+ const stem = pagesStem(located);
85
+ const signal = where.signal;
86
+ if ([".png", ".jpg", ".jpeg"].includes(ext)) {
87
+ const dir = join(where.work, "pages", stem);
88
+ await mkdir(dir, { recursive: true });
89
+ const out = `1${ext === ".png" ? ".png" : ".jpg"}`;
90
+ const { imageDimensions } = await import("@parcha/agentrun-dsl");
91
+ const size = imageDimensions(new Uint8Array(await readFile(file)));
92
+ if (size && Math.max(size.width, size.height) > MAX_PAGE_PX) {
93
+ const scale = size.width >= size.height ? `${MAX_PAGE_PX}:-2` : `-2:${MAX_PAGE_PX}`;
94
+ await run("ffmpeg", ["-v", "error", "-y", "-i", file, "-vf", `scale=${scale}`, "-frames:v", "1", join(dir, out)], { signal, maxBuffer: 1 << 20 }).catch((error) => {
95
+ throw new Error(`pdf_pages: ${name} is ${size.width}x${size.height}, over ${MAX_PAGE_PX} px on a side, and ffmpeg did not scale it: ${error.message.split("\n")[0]}`);
96
+ });
97
+ }
98
+ else
99
+ await copyFile(file, join(dir, out));
100
+ return { name, pageCount: 1, dpi: null, pages: [{ page: 1, image: `pages/${stem}/${out}` }], text: "" };
101
+ }
102
+ const info = await run("pdfinfo", [file], { signal, maxBuffer: 1 << 20 }).catch((error) => {
103
+ throw new Error(`pdf_pages: ${name} is not a PDF poppler reads: ${error.message.split("\n")[0]}`);
104
+ });
105
+ const pageCount = Number(/^Pages:\s+(\d+)/m.exec(info.stdout)?.[1] ?? 0);
106
+ const last = Math.min(maxPages, Math.max(pageCount, 1));
107
+ // The largest side of the pages drawn, in points (1/72 in), and the dpi that keeps it within MAX_PAGE_PX.
108
+ const sizes = await run("pdfinfo", ["-f", "1", "-l", String(last), file], { signal, maxBuffer: 1 << 20 }).then((r) => r.stdout, () => info.stdout);
109
+ const points = Math.max(0, ...[...sizes.matchAll(/size:\s+([\d.]+) x ([\d.]+) pts/g)].flatMap((m) => [Number(m[1]), Number(m[2])]));
110
+ // Two pixels short of the cap: pdftoppm rounds a page's size up.
111
+ const used = points > 0 ? Math.max(1, Math.min(dpi, Math.floor(((MAX_PAGE_PX - 2) * 72) / points))) : dpi;
112
+ const dir = join(where.work, "pages", stem, String(used));
113
+ await mkdir(dir, { recursive: true });
114
+ // pdftoppm pads its page numbers to the document's page count: drawn apart, then named by page.
115
+ const temp = await mkdtemp(join(dir, ".draw-"));
116
+ try {
117
+ await run("pdftoppm", ["-png", "-r", String(used), "-f", "1", "-l", String(last), file, join(temp, "p")], { signal, maxBuffer: 1 << 20 });
118
+ const drawn = (await readdir(temp)).filter((f) => /^p-\d+\.png$/.test(f)).map((f) => ({ f, page: Number(/(\d+)\.png$/.exec(f)[1]) })).sort((a, b) => a.page - b.page);
119
+ const pages = [];
120
+ for (const { f, page } of drawn) {
121
+ await rename(join(temp, f), join(dir, `${page}.png`));
122
+ pages.push({ page, image: `pages/${stem}/${used}/${page}.png` });
123
+ }
124
+ const { stdout } = await run("pdftotext", ["-l", String(last), "-enc", "UTF-8", file, "-"], { signal, maxBuffer: 16 << 20 });
125
+ const text = stdout.length > TEXT_CAP ? `${stdout.slice(0, TEXT_CAP - 1)}…` : stdout;
126
+ return { name, pageCount, dpi: used, pages, text };
127
+ }
128
+ finally {
129
+ await rm(temp, { recursive: true, force: true });
130
+ }
131
+ }
132
+ const IMAGE_TYPES = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif" };
133
+ const MAX_IMAGE_BYTES = 16 << 20;
134
+ /** A decision node's image by its ref, a path under the run's work directory (a page pdf_pages drew), confined to it. */
135
+ export const imageLoader = (work) => async (ref) => {
136
+ const mime = IMAGE_TYPES[extname(String(ref)).toLowerCase()];
137
+ if (!mime)
138
+ throw new Error(`the image ${ref} is not a PNG, JPEG, WebP or GIF file`);
139
+ if (typeof ref !== "string" || isAbsolute(ref))
140
+ throw new Error(`the image ${ref} is not a path under the run's work directory`);
141
+ const file = await confined(work, ref);
142
+ if (!file)
143
+ throw new Error(`the run's work directory has no file ${ref}`);
144
+ if ((await stat(file)).size > MAX_IMAGE_BYTES)
145
+ throw new Error(`the image ${ref} is over 16 MiB`);
146
+ return { bytes: new Uint8Array(await readFile(file)), mime };
147
+ };
@@ -0,0 +1,69 @@
1
+ import { type BoxId, type BoxOffer } from "./boxes.js";
2
+ import { type InputIssue } from "./errors.js";
3
+ export declare const PLACE_MODES: readonly ["runner", "sandbox"];
4
+ export type PlaceMode = (typeof PLACE_MODES)[number];
5
+ export declare const DEFAULT_PLACE_MODE: PlaceMode;
6
+ export type Place = {
7
+ mode: "runner";
8
+ } | {
9
+ mode: "sandbox";
10
+ box: BoxId;
11
+ };
12
+ /** The boxes runs execute in so far: Docker, Daytona and the VM box. */
13
+ export declare const RUN_BOXES: readonly BoxId[];
14
+ /** The boxes this server gives runs, from what its registry set up at its start (boxes.ts): a box runs execute in
15
+ * that the registry has, and no other. */
16
+ export declare function boxAvailability(registry: readonly BoxOffer[]): BoxOffer[];
17
+ /** The place a new agentic definition that names none is saved with: the Docker box where this server has it, ready or
18
+ * preparing (its first run waits for the image); else none, so the agent runs on the runner as it did before, with
19
+ * `reason` saying why, in docker's own words. A workflow is never given one. */
20
+ export declare function newAgentPlace(registry: readonly BoxOffer[]): {
21
+ place: Place;
22
+ } | {
23
+ reason: string;
24
+ };
25
+ /** The tools a new agent in the default box is given when its definition names none: a shell. A definition that names its
26
+ * tools, an empty list included, keeps exactly those. */
27
+ export declare const NEW_AGENT_TOOLS: readonly string[];
28
+ /** Why a sandbox-only tool (bash) cannot run on this server: no box runs execute in is available, each with its reason.
29
+ * Undefined when one is. */
30
+ export declare function noBoxReason(registry: readonly BoxOffer[]): string | undefined;
31
+ /** The start banner's words on the boxes: which are ready for a sandbox agent's tools, which are still preparing (an
32
+ * available box whose `state` says so, with its reason: what it is pulling), then why each box is not that
33
+ * AGENTRUN_BOXES lists (`listed`), or, when none is ready or preparing, each box runs execute in, with what to do. */
34
+ export declare function boxesLine(registry: readonly BoxOffer[], listed: ReadonlySet<BoxId>, allow?: readonly string[] | "none"): string;
35
+ /** `places` in capabilities: the modes a revision may name, where a revision that names none runs (`default`: the runner,
36
+ * for a revision saved with no place), the place a new agent is saved with (`default_place`, with `default_reason` when
37
+ * it is the runner), each box, and the hosts a box whose `network` is `allowlist` reaches (`allow`, run-box.ts
38
+ * boxAllowOf; empty for `none`). */
39
+ export declare const placesOf: (registry: readonly BoxOffer[], allow?: readonly string[] | "none") => {
40
+ boxes: BoxOffer[];
41
+ allow: string[];
42
+ default_place: Place;
43
+ modes: ("runner" | "sandbox")[];
44
+ default: "runner";
45
+ } | {
46
+ boxes: BoxOffer[];
47
+ allow: string[];
48
+ default_place: Place;
49
+ default_reason: string;
50
+ modes: ("runner" | "sandbox")[];
51
+ default: "runner";
52
+ };
53
+ /** A run's place: its revision's, else this host's default. */
54
+ export declare const resolvePlace: (revision: Place | undefined) => Place;
55
+ /** The place a run kept (its serve.json), or runner for a run kept before runs had one. */
56
+ export declare function storedPlace(value: unknown): Place;
57
+ /** Where a box binds the run's work/, and where its tools start. */
58
+ export declare const BOX_WORK = "/run/agentrun/run/work";
59
+ /** The boxes that cannot bind a run's work/, being on another machine: its work/ is seeded at the box's making and
60
+ * pulled back (run-box.ts). */
61
+ export declare const REMOTE_BOXES: readonly BoxId[];
62
+ export declare const remotePlace: (place: Place) => boolean;
63
+ /** The run's work/ as its agent's tools see it: on the runner, `<runDir>/work`; in any box, BOX_WORK. */
64
+ export declare const agentWorkDir: (runDir: string, place: Place) => string;
65
+ /** `place` as a definition writes it, to copy: `"place": {"mode": "sandbox", "box": "docker"}`. */
66
+ export declare const placeFix: (place: Place) => string;
67
+ /** What is wrong with `place` as a definition gives it, as issues at `field`. Each names its fix: the field to remove,
68
+ * or the place to copy, the one it most likely meant. */
69
+ export declare function placeIssues(place: unknown, field: string): InputIssue[];
package/dist/place.js ADDED
@@ -0,0 +1,137 @@
1
+ // Where a revision's runs execute: `runner` (no box and no shell) or `sandbox` (the agent's file and shell tools run in
2
+ // the named box, while its loop, its log and every key stay on the server). A revision keeps the place it names, an
3
+ // explicit runner included, since the default is this host's; one that names none keeps none, so a revision written
4
+ // before this field keeps its id. Which boxes this server has is said in capabilities, and a revision whose box it does
5
+ // not have saves with a warning and is refused at run time. A run runs in its revision's place, else this host's
6
+ // default, and keeps the place it resolved to: a run request names none. Runs execute in Docker and in Daytona, for
7
+ // now: every other box says it does not run yet. A harness's own tools in the box, when they come, are an option of
8
+ // sandbox, never a third mode.
9
+ //
10
+ // The box is a new agent's default machine: an agentic definition that names no place is saved, at its create, with the
11
+ // Docker box as its place wherever this server has docker (ready, or preparing), and with bash when it names no tools
12
+ // (newAgentPlace). The place is written on the revision then, never resolved at run time, so a revision saved with none
13
+ // (before this, or where docker was not there) runs on the runner, whatever the server has now.
14
+ import { join } from "node:path";
15
+ import { BOX_IDS, VM_PROVIDER } from "./boxes.js";
16
+ import { sentence } from "./errors.js";
17
+ export const PLACE_MODES = ["runner", "sandbox"];
18
+ export const DEFAULT_PLACE_MODE = "runner";
19
+ /** The boxes runs execute in so far: Docker, Daytona and the VM box. */
20
+ export const RUN_BOXES = ["docker", "daytona", VM_PROVIDER.id];
21
+ /** The boxes this server gives runs, from what its registry set up at its start (boxes.ts): a box runs execute in
22
+ * that the registry has, and no other. */
23
+ export function boxAvailability(registry) {
24
+ return BOX_IDS.map((id) => {
25
+ const offer = registry.find((o) => o.id === id);
26
+ if (!offer)
27
+ return { id, available: false, reason: `${id} is not set up on this server` };
28
+ if (!offer.available || RUN_BOXES.includes(id))
29
+ return { ...offer };
30
+ return { id, available: false, reason: `runs in the ${id} box are not available yet: use the ${RUN_BOXES.join(" or ")} box` };
31
+ });
32
+ }
33
+ /** The place a new agentic definition that names none is saved with: the Docker box where this server has it, ready or
34
+ * preparing (its first run waits for the image); else none, so the agent runs on the runner as it did before, with
35
+ * `reason` saying why, in docker's own words. A workflow is never given one. */
36
+ export function newAgentPlace(registry) {
37
+ const docker = boxAvailability(registry).find((box) => box.id === "docker");
38
+ if (docker?.available)
39
+ return { place: { mode: "sandbox", box: "docker" } };
40
+ return { reason: `new agents run on the runner, because the docker box is unavailable here: ${docker?.reason ?? "it is not set up"}` };
41
+ }
42
+ /** The tools a new agent in the default box is given when its definition names none: a shell. A definition that names its
43
+ * tools, an empty list included, keeps exactly those. */
44
+ export const NEW_AGENT_TOOLS = Object.freeze(["bash"]);
45
+ /** Why a sandbox-only tool (bash) cannot run on this server: no box runs execute in is available, each with its reason.
46
+ * Undefined when one is. */
47
+ export function noBoxReason(registry) {
48
+ const boxes = boxAvailability(registry).filter((box) => RUN_BOXES.includes(box.id));
49
+ if (boxes.some((box) => box.available))
50
+ return undefined;
51
+ return `no box is set up on this server: ${boxes.map((box) => `${box.id} is unavailable (${box.reason ?? "no reason given"})`).join("; ")}`;
52
+ }
53
+ /** The start banner's words on the boxes: which are ready for a sandbox agent's tools, which are still preparing (an
54
+ * available box whose `state` says so, with its reason: what it is pulling), then why each box is not that
55
+ * AGENTRUN_BOXES lists (`listed`), or, when none is ready or preparing, each box runs execute in, with what to do. */
56
+ export function boxesLine(registry, listed, allow = "none") {
57
+ const boxes = boxAvailability(registry);
58
+ const preparing = (box) => box.state === "preparing";
59
+ const ready = boxes.filter((box) => box.available && !preparing(box)).map((box) => box.id);
60
+ const coming = boxes.filter((box) => box.available && preparing(box));
61
+ const said = [
62
+ ...(ready.length ? [`${new Intl.ListFormat("en", { type: "conjunction" }).format(ready)} ${ready.length === 1 ? "is" : "are"} ready, so sandbox agents run their tools there.`] : []),
63
+ ...coming.map((box) => sentence(`${box.id} is preparing${box.reason ? ` (${box.reason})` : ""}`)),
64
+ ];
65
+ const none = !said.length;
66
+ const why = boxes.filter((box) => !box.available && (listed.has(box.id) || (none && RUN_BOXES.includes(box.id))));
67
+ // What an available box's programs reach, as capabilities say (`network`, `network_reason`, `places.allow`).
68
+ const hosts = new Intl.ListFormat("en", { type: "conjunction" }).format(allow === "none" ? [] : allow);
69
+ const reach = boxes.filter((box) => box.available && box.network).map((box) => box.network === "allowlist" ? sentence(`${box.id} boxes reach only ${hosts}`) : sentence(`${box.id} boxes have no network${box.network_reason ? `: ${box.network_reason}` : ""}`));
70
+ return ["Boxes:", ...(none ? ["none is ready, so sandbox agents do not run here."] : said), ...reach, ...why.map((box) => sentence(`${box.id}: ${box.reason ?? "not available"}`))].join(" ");
71
+ }
72
+ /** `places` in capabilities: the modes a revision may name, where a revision that names none runs (`default`: the runner,
73
+ * for a revision saved with no place), the place a new agent is saved with (`default_place`, with `default_reason` when
74
+ * it is the runner), each box, and the hosts a box whose `network` is `allowlist` reaches (`allow`, run-box.ts
75
+ * boxAllowOf; empty for `none`). */
76
+ export const placesOf = (registry, allow = "none") => {
77
+ const fresh = newAgentPlace(registry);
78
+ return { modes: [...PLACE_MODES], default: DEFAULT_PLACE_MODE, ...("place" in fresh ? { default_place: fresh.place } : { default_place: { mode: "runner" }, default_reason: fresh.reason }), boxes: boxAvailability(registry).map(stated), allow: allow === "none" ? [] : [...allow] };
79
+ };
80
+ /** A box with its state: what the server set (a Docker box whose image is coming is `preparing`), else `ready` when it
81
+ * is available and `unavailable` when not; and, on an available box, its network as the server set it, with
82
+ * `network_reason` when it is none for a cause of its own. */
83
+ const stated = ({ state, network, network_reason, ...offer }) => ({
84
+ ...offer,
85
+ state: offer.available ? (state ?? "ready") : "unavailable",
86
+ ...(offer.available && network ? { network } : {}),
87
+ ...(offer.available && network === "none" && network_reason ? { network_reason } : {}),
88
+ });
89
+ /** A run's place: its revision's, else this host's default. */
90
+ export const resolvePlace = (revision) => revision ?? { mode: "runner" };
91
+ /** The place a run kept (its serve.json), or runner for a run kept before runs had one. */
92
+ export function storedPlace(value) {
93
+ if (!isObject(value) || value.mode !== "sandbox" || !listed(BOX_IDS, value.box))
94
+ return { mode: "runner" };
95
+ return { mode: "sandbox", box: value.box };
96
+ }
97
+ /** Where a box binds the run's work/, and where its tools start. */
98
+ export const BOX_WORK = "/run/agentrun/run/work";
99
+ /** The boxes that cannot bind a run's work/, being on another machine: its work/ is seeded at the box's making and
100
+ * pulled back (run-box.ts). */
101
+ export const REMOTE_BOXES = ["daytona", VM_PROVIDER.id];
102
+ export const remotePlace = (place) => place.mode === "sandbox" && REMOTE_BOXES.includes(place.box);
103
+ /** The run's work/ as its agent's tools see it: on the runner, `<runDir>/work`; in any box, BOX_WORK. */
104
+ export const agentWorkDir = (runDir, place) => (place.mode === "runner" ? join(runDir, "work") : BOX_WORK);
105
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
106
+ const listed = (options, value) => typeof value === "string" && options.includes(value);
107
+ /** `place` as a definition writes it, to copy: `"place": {"mode": "sandbox", "box": "docker"}`. */
108
+ export const placeFix = (place) => `"place": ${place.mode === "runner" ? '{"mode": "runner"}' : `{"mode": "sandbox", "box": "${place.box}"}`}`;
109
+ /** The option of `options` that `value` names in any case, if any. */
110
+ const named = (options, value) => (typeof value === "string" ? options.find((option) => option === value.trim().toLowerCase()) : undefined);
111
+ /** The place a definition most likely meant by a `place` that is none: the runner when that is all it names, else a
112
+ * sandbox on the box it names (as its box, or as its mode), or on the first box runs execute in. */
113
+ function meant(place) {
114
+ const box = isObject(place) ? named(BOX_IDS, place.box) ?? named(BOX_IDS, place.mode) : named(BOX_IDS, place);
115
+ if (!box && named(PLACE_MODES, isObject(place) ? place.mode : place) === "runner")
116
+ return { mode: "runner" };
117
+ return { mode: "sandbox", box: box ?? RUN_BOXES[0] };
118
+ }
119
+ /** What is wrong with `place` as a definition gives it, as issues at `field`. Each names its fix: the field to remove,
120
+ * or the place to copy, the one it most likely meant. */
121
+ export function placeIssues(place, field) {
122
+ const bad = (reason, message, fix = placeFix(meant(place))) => [{ field, reason, message, fix }];
123
+ if (!isObject(place))
124
+ return bad("wrong_type", `${field} is an object: {mode}, or {mode, box}`);
125
+ const extra = Object.keys(place).filter((key) => key !== "mode" && key !== "box");
126
+ if (extra.length)
127
+ return bad("not_allowed", `${field} keeps only mode and box, not ${extra.join(" or ")}`, `Remove ${extra.map((key) => `${field}.${key}`).join(" and ")}.`);
128
+ if (!listed(PLACE_MODES, place.mode))
129
+ return bad(place.mode === undefined ? "missing" : "not_an_option", `${field}.mode is one of ${PLACE_MODES.join(", ")}`);
130
+ if (place.mode === "runner")
131
+ return place.box === undefined ? [] : bad("not_allowed", "a runner place uses no box", `Remove ${field}.box.`);
132
+ if (place.box === undefined)
133
+ return bad("missing", `a sandbox place names its box: one of ${BOX_IDS.join(", ")}`);
134
+ if (!listed(BOX_IDS, place.box))
135
+ return bad("not_an_option", `${field}.box is one of ${BOX_IDS.join(", ")}`);
136
+ return [];
137
+ }
@@ -0,0 +1,20 @@
1
+ /** Where the token came from: made at this start (printed this once), kept in DIR/.token, or the environment's. */
2
+ export type TokenSource = "made" | "file" | "env";
3
+ /** The banner's lines. The token is printed only when this start made it; else where it is. `publicUrl` is the address
4
+ * people open (AGENTRUN_PUBLIC_URL), which the base URL and the link use. With `accounts` the page is the owner's
5
+ * password, so its link holds no token. `boxes`: which boxes are ready, in words (Serve's boxesLine), last. */
6
+ export declare function banner(o: {
7
+ url: string;
8
+ baseUrl: string;
9
+ data: string;
10
+ token: string;
11
+ source: TokenSource;
12
+ listen?: string;
13
+ publicUrl?: string;
14
+ accounts?: boolean;
15
+ boxes?: string;
16
+ }): string[];
17
+ /** One log line. */
18
+ export declare const logLine: (event: string, fields?: Record<string, string | number>) => string;
19
+ /** A duration as pi-durable-disk's --drain-timeout takes it ("8s", "500ms", "1m"), in milliseconds; undefined when it is not one. */
20
+ export declare function durationMs(text: string): number | undefined;
package/dist/print.js ADDED
@@ -0,0 +1,29 @@
1
+ // What the server prints on stdout: its banner at start, and one line per request, per run start and end, and per
2
+ // refused credential (logfmt: `at=<time> event=<name> key=value ...`). No line holds a token or any part of one.
3
+ import { join } from "node:path";
4
+ /** The banner's lines. The token is printed only when this start made it; else where it is. `publicUrl` is the address
5
+ * people open (AGENTRUN_PUBLIC_URL), which the base URL and the link use. With `accounts` the page is the owner's
6
+ * password, so its link holds no token. `boxes`: which boxes are ready, in words (Serve's boxesLine), last. */
7
+ export function banner(o) {
8
+ const where = o.source === "env" ? "$AGENTRUN_TOKEN" : `<in ${join(o.data, ".token")}>`;
9
+ const key = o.source === "made" ? o.token : where;
10
+ return [
11
+ `agentrun-serve on ${o.baseUrl} (agent store in ${o.data}${o.listen ? `, listening on ${o.listen}` : ""})`,
12
+ `AGENTRUN_BASE_URL=${o.publicUrl ? `${o.publicUrl}/v2` : o.baseUrl}`,
13
+ `AGENTRUN_API_KEY=${key}`,
14
+ // Encoded: a "+" in a token reads as a space in a query string.
15
+ o.accounts ? `Open ${o.publicUrl ?? o.url}/` : `Open ${o.publicUrl ?? o.url}/?token=${o.source === "made" ? encodeURIComponent(o.token) : where}`,
16
+ ...(o.boxes ? [o.boxes] : []),
17
+ ];
18
+ }
19
+ const value = (v) => {
20
+ const text = String(v);
21
+ return /^[^\s"=]+$/.test(text) ? text : `"${text.replace(/[\s"]+/g, " ").trim()}"`;
22
+ };
23
+ /** One log line. */
24
+ export const logLine = (event, fields = {}) => [`at=${new Date().toISOString()}`, `event=${event}`, ...Object.entries(fields).map(([k, v]) => `${k}=${value(v)}`)].join(" ");
25
+ /** A duration as pi-durable-disk's --drain-timeout takes it ("8s", "500ms", "1m"), in milliseconds; undefined when it is not one. */
26
+ export function durationMs(text) {
27
+ const m = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(text.trim());
28
+ return m ? Math.round(Number(m[1]) * { ms: 1, s: 1_000, m: 60_000 }[m[2]]) : undefined;
29
+ }
@@ -0,0 +1,40 @@
1
+ import { type Problem } from "./learn/index.js";
2
+ import { type Turn } from "./learning.js";
3
+ export type Proposed = {
4
+ state: "proposed";
5
+ notes: number;
6
+ skills: number;
7
+ workflows: number;
8
+ left?: Problem[];
9
+ } | {
10
+ state: "dropped";
11
+ reason: "empty";
12
+ } | {
13
+ state: "dropped";
14
+ reason: "unparsed";
15
+ detail: string;
16
+ } | {
17
+ state: "dropped";
18
+ reason: "checker";
19
+ problems: Problem[];
20
+ };
21
+ /** What a run's end-of-run turn answered (`turn`, as its directory kept it), parsed, checked against its seed `seed` (its
22
+ * pin) and kept in `runDir` as its proposal, with what the user said in the run as the grader reads it (each message
23
+ * cut of the host's secrets, then to GRADE_CAPS.askedMessage); or `empty` when it gave nothing, `unparsed` when its
24
+ * answer is out of format, or `checker` with the problems, printable. A note, skill or draft the answer gives with the
25
+ * very text the seed holds is no change, and `MEMORY.md` is the host's (the checker ignores it). A skill is laid at
26
+ * `skills/<name>/SKILL.md`; a draft at `workflows/<name>/workflow.json`, with the README.md the host writes from the
27
+ * description its block gives. `outcome`, how the run's job ended (only a completed run adds or changes a skill);
28
+ * `tools`, those a draft may name (tools.ts learnedWorkflowTools); `refuse`: this host's secrets. In the agent's
29
+ * queue. */
30
+ export declare const proposeRun: (input: {
31
+ data: string;
32
+ agentId: string;
33
+ runDir: string;
34
+ seed: string;
35
+ turn: Turn;
36
+ refuse: readonly string[];
37
+ outcome?: string;
38
+ tools?: readonly string[];
39
+ gated?: Readonly<Record<string, string>>;
40
+ }) => Promise<Proposed>;
@@ -0,0 +1,112 @@
1
+ // Learning, after a run: the notes its end-of-run turn answered with, and a skill or a workflow draft beside them, are read
2
+ // by the host (learn/reflect.ts parseReflection), checked against the commit the run started from (learn/check.ts
3
+ // checkProposal), and kept in the run's own directory as its proposal (`learning-proposal.json`), or dropped. The answer
4
+ // is read from what the run's directory kept as the run settled (learning.ts keepTurn), never from the run's work or its
5
+ // rows, which a follow-up may change; and no file the run wrote is read at all, in `.learning/` or anywhere. In the
6
+ // agent's queue. Nothing is written to git here, and nothing is written at all before the checks pass: what they refuse
7
+ // (a note holding a secret among them) is never kept anywhere.
8
+ import { join } from "node:path";
9
+ import { checkProposal, draftFiles, unstorable, GRADE_CAPS, learnedStatus, parseReflection, redactSecrets, SKILLS_DIR, WORKFLOWS_DIR } from "./learn/index.js";
10
+ import { homeOf, writeDurable } from "./files.js";
11
+ import { activeOf, agentFolder, git, PROPOSAL, readBlobs, readSeed, withAgentRepo } from "./learning.js";
12
+ /** The rules that refuse a proposal whole, whatever item they name: its counts and caps, a path outside what a run may
13
+ * write, a deletion, the folder's index full, anything that must never be stored (a secret, a character a reader does
14
+ * not see), which says the run's answer is not to be trusted for any item, and text that is not UTF-8, which cannot be
15
+ * read for one. Every other problem is its item's alone; unstorable reads every item's text whole first. */
16
+ const WHOLE = new Set(["too_many_files", "too_many_notes", "too_many_skills", "too_many_workflows", "outside", "deleted", "index_full", "secret_value", "secret_shape", "invisible_unicode", "encoding"]);
17
+ /** The item a changed file belongs to: a draft's two files are one item (its folder), every other file is itself. */
18
+ const itemOf = (path) => (path.startsWith(`${WORKFLOWS_DIR}/`) ? path.split("/").slice(0, 2).join("/") : path);
19
+ /** `text`'s first `max` UTF-16 units, never half a character. */
20
+ const cut = (text, max) => (text.length <= max ? text : [...text].reduce((out, ch) => (out.length + ch.length > max ? out : out + ch), ""));
21
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
22
+ /** The skills and drafts on the seed `sha`: every path under skills/ and workflows/, and the text of each regular file of
23
+ * them `wanted` names (one that is not UTF-8 is left out, so an answer that gives it is a change). */
24
+ async function seedFiles(home, repo, sha, wanted) {
25
+ const listed = (await git(home, repo, ["ls-tree", "-r", "-z", sha, "--", SKILLS_DIR, WORKFLOWS_DIR])).toString("utf8").split("\0").filter(Boolean).map((entry) => {
26
+ const [mode, type, oid] = entry.slice(0, entry.indexOf("\t")).split(" ");
27
+ return { mode, type, oid: oid, path: entry.slice(entry.indexOf("\t") + 1) };
28
+ });
29
+ const read = listed.filter((entry) => entry.mode === "100644" && entry.type === "blob" && wanted.includes(entry.path));
30
+ const blobs = await readBlobs(home, repo, read.map((entry) => entry.oid));
31
+ const texts = new Map();
32
+ read.forEach((entry, i) => {
33
+ try {
34
+ texts.set(entry.path, utf8.decode(blobs[i]));
35
+ }
36
+ catch {
37
+ // Not UTF-8: no text the answer can give again.
38
+ }
39
+ });
40
+ return { files: listed.map((entry) => entry.path), texts };
41
+ }
42
+ /** What a run's end-of-run turn answered (`turn`, as its directory kept it), parsed, checked against its seed `seed` (its
43
+ * pin) and kept in `runDir` as its proposal, with what the user said in the run as the grader reads it (each message
44
+ * cut of the host's secrets, then to GRADE_CAPS.askedMessage); or `empty` when it gave nothing, `unparsed` when its
45
+ * answer is out of format, or `checker` with the problems, printable. A note, skill or draft the answer gives with the
46
+ * very text the seed holds is no change, and `MEMORY.md` is the host's (the checker ignores it). A skill is laid at
47
+ * `skills/<name>/SKILL.md`; a draft at `workflows/<name>/workflow.json`, with the README.md the host writes from the
48
+ * description its block gives. `outcome`, how the run's job ended (only a completed run adds or changes a skill);
49
+ * `tools`, those a draft may name (tools.ts learnedWorkflowTools); `refuse`: this host's secrets. In the agent's
50
+ * queue. */
51
+ export const proposeRun = (input) => withAgentRepo(input.data, input.agentId, async () => {
52
+ const home = homeOf(input.data, input.agentId);
53
+ const repo = await agentFolder(input.data, input.agentId);
54
+ const seed = await readSeed(home, repo, input.seed);
55
+ const parsed = parseReflection(input.turn.answer);
56
+ if (!parsed.ok)
57
+ return parsed.reason === "empty" ? { state: "dropped", reason: "empty" } : { state: "dropped", reason: "unparsed", detail: parsed.detail };
58
+ // Each skill and draft as the folder would hold it; a draft is its two files, given together or not at all.
59
+ const given = [
60
+ ...(parsed.skills ?? []).map(({ name, text }) => [{ file: `${SKILLS_DIR}/${name}/SKILL.md`, text }]),
61
+ ...(parsed.workflows ?? []).map(({ name, text }) => {
62
+ const { json, readme } = draftFiles(name, text);
63
+ return [{ file: `${WORKFLOWS_DIR}/${name}/workflow.json`, text: json }, { file: `${WORKFLOWS_DIR}/${name}/README.md`, text: readme }];
64
+ }),
65
+ ];
66
+ const held = given.length ? await seedFiles(home, repo, input.seed, given.flat().map(({ file }) => file)) : { files: [], texts: new Map() };
67
+ const files = given.filter((group) => group.some(({ file, text }) => held.texts.get(file) !== text)).flat();
68
+ const changes = [
69
+ ...parsed.notes.filter(({ file, text }) => seed.notes[file] !== text).map(({ file, text }) => ({ path: file, status: seed.files.includes(file) ? "modified" : "added", mode: "100644", bytes: Buffer.from(text) })),
70
+ ...files.map(({ file, text }) => ({ path: file, status: held.files.includes(file) ? "modified" : "added", mode: "100644", bytes: Buffer.from(text) })),
71
+ ];
72
+ // The workflow DSL reads a draft, and is loaded only when there is one to read.
73
+ const dsl = files.some(({ file }) => file.endsWith("/workflow.json")) ? await import("@parcha/agentrun-dsl") : undefined;
74
+ // A skill or a draft whose seed text has a status is a person's call (retired, or waiting for their OK): never changed.
75
+ const kept = [...held.texts].filter(([file, text]) => (file.endsWith("/SKILL.md") || file.endsWith("/README.md")) && learnedStatus(text) !== "active").map(([file]) => file);
76
+ const check = (some) => checkProposal({ base: { files: [...seed.files, ...held.files], active: activeOf(seed) }, changes: some, refuseValues: input.refuse, ...(kept.length ? { kept } : {}), ...(input.outcome === undefined ? {} : { outcome: input.outcome }), ...(input.tools ? { tools: input.tools } : {}), ...(input.gated ? { gated: input.gated } : {}), ...(dsl ? { dsl } : {}) });
77
+ // A verdict per item from the checks too: the items a problem names are left out (a draft's two files together),
78
+ // and the rest is checked again; a problem that names no item, or one that refuses the whole (WHOLE), drops it all,
79
+ // as does a rest the checks still refuse.
80
+ let checked = check(changes);
81
+ let left = [];
82
+ let passing = files;
83
+ if (checked.problems.length) {
84
+ const named = new Set(changes.map(({ path }) => itemOf(path)));
85
+ if (checked.problems.some((problem) => WHOLE.has(problem.rule) || problem.path === undefined || !named.has(itemOf(problem.path))))
86
+ return { state: "dropped", reason: "checker", problems: checked.problems };
87
+ // Before any item is kept from an answer the checks refuse: every name and text it gave, read whole. Something
88
+ // that must never be stored anywhere in it (in an item the checks refused unread, too) refuses it all.
89
+ const never = unstorable(changes, input.refuse);
90
+ if (never.length)
91
+ return { state: "dropped", reason: "checker", problems: [...checked.problems, ...never] };
92
+ const out = new Set(checked.problems.map((problem) => itemOf(problem.path)));
93
+ const rest = changes.filter(({ path }) => !out.has(itemOf(path)));
94
+ const again = rest.length ? check(rest) : undefined;
95
+ // A rest the checks refuse again: its own problems are what keeps it out, said with the first pass's.
96
+ if (!again || again.problems.length)
97
+ return { state: "dropped", reason: "checker", problems: [...checked.problems, ...(again?.problems ?? [])] };
98
+ left = checked.problems;
99
+ checked = again;
100
+ passing = files.filter(({ file }) => !out.has(itemOf(file)));
101
+ }
102
+ if (!checked.notes.length && !passing.length)
103
+ return { state: "dropped", reason: "empty" };
104
+ // Each message cut of the host's secrets whole first, and only then shortened: a secret the cut fell inside would
105
+ // leave a part of itself that no longer matches. The whole message is read, however long (a message is bounded by
106
+ // the run's own request limits), so a long one is not lost to the grader as one "[redacted]".
107
+ const asked = input.turn.asked.map((message) => cut(redactSecrets(message, input.refuse, Number.POSITIVE_INFINITY), GRADE_CAPS.askedMessage));
108
+ const proposal = { seed: input.seed, notes: checked.notes.map(({ file, text }) => ({ file, text })), ...(passing.length ? { files: passing } : {}), asked };
109
+ await writeDurable(join(input.runDir, PROPOSAL), `${JSON.stringify(proposal)}\n`);
110
+ const count = (suffix) => passing.filter(({ file }) => file.endsWith(suffix)).length;
111
+ return { state: "proposed", notes: proposal.notes.length, skills: count("/SKILL.md"), workflows: count("/workflow.json"), ...(left.length ? { left } : {}) };
112
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ // Node 22 prints an ExperimentalWarning when node:sqlite loads (Node 24 prints none). It isn't the server's to show:
2
+ // the server's stderr is its own lines, one per failure (a refused start is exactly one), and its runs' processes
3
+ // start with --no-warnings=ExperimentalWarning for the same reason. The CLI imports this before anything loads
4
+ // node:sqlite (after the secrets' read, which loads none).
5
+ // Every other warning prints as Node prints it.
6
+ const printers = process.listeners("warning");
7
+ process.removeAllListeners("warning");
8
+ process.on("warning", (warning) => {
9
+ if (warning.name === "ExperimentalWarning" && /\bSQLite\b/.test(warning.message))
10
+ return;
11
+ for (const print of printers)
12
+ print(warning);
13
+ });
14
+ export {};
@@ -0,0 +1,22 @@
1
+ import type { Models } from "@earendil-works/pi-ai";
2
+ import type { DurableRun } from "@parcha/pi-durable-disk";
3
+ import { type RefusalFigures } from "./cap.js";
4
+ /** Whether the run in `root` (its directory) was cancelled: the mark serve's cancel writes there first. */
5
+ export declare const cancelledIn: (root: string) => () => boolean;
6
+ /** How long a mark that carries a hold (a lost or failed request's end, an unreadable cost's) may take to reach the store
7
+ * before the request fails loudly (END_NOT_WRITTEN): 15 s. A lost mark is waited for before the retry is sent, so a
8
+ * commit queued behind a large entry on a slow disk (seconds) past 1 s let the retry leave, and its answer reach pi,
9
+ * with no mark in the store: a crash then read the request at the answer's own usage. Such a mark is written only on a
10
+ * path already lost or failed, so the wait costs latency there and nowhere else; 15 s holds such a commit with room to
11
+ * spare, and still fails a store that has stopped within a turn's patience, never a turn held without bound. */
12
+ export declare const END_MARK_WAIT_MS = 15000;
13
+ /** `models` with each generation request marked before it leaves, once `open` hands over the run (its Harness). Once
14
+ * `cancelled` says the run was cancelled, no request is sent: each is refused here, before it is marked, or after its
15
+ * mark when the cancel came while the mark waited, and then its start is withdrawn (an end mark, `unsent`). */
16
+ export declare function markRequests<M extends Models>(models: M, cancelled?: () => boolean, { holdMarkWaitMs }?: {
17
+ holdMarkWaitMs?: number;
18
+ }): Promise<{
19
+ models: M;
20
+ open(run: DurableRun): void;
21
+ refused(figures?: RefusalFigures): Promise<void>;
22
+ }>;