@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.29
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.
- package/CHANGELOG.md +560 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +1723 -2
- package/dist/adapters.d.ts +205 -0
- package/dist/adapters.js +459 -0
- package/dist/agents.d.ts +124 -0
- package/dist/agents.js +302 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +324 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +283 -0
- package/dist/box-relay.d.ts +42 -0
- package/dist/box-relay.js +222 -0
- package/dist/boxes.d.ts +54 -0
- package/dist/boxes.js +182 -0
- package/dist/cap.d.ts +224 -0
- package/dist/cap.js +721 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +31 -0
- package/dist/coding-tools.js +81 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
- package/dist/console/assets/index-BN7oVcO4.js +445 -0
- package/dist/console/assets/index-By-jkqki.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +11 -0
- package/dist/decision-rows.js +116 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +72 -0
- package/dist/errors.js +66 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +60 -0
- package/dist/files.js +153 -0
- package/dist/grade.d.ts +96 -0
- package/dist/grade.js +348 -0
- package/dist/graph-view.d.ts +100 -0
- package/dist/graph-view.js +212 -0
- package/dist/harness-app.d.ts +38 -0
- package/dist/harness-app.js +626 -0
- package/dist/harness.d.ts +53 -0
- package/dist/harness.js +74 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +20 -0
- package/dist/host-tools.js +140 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +81 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +129 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1221 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +36 -0
- package/dist/key-check.js +108 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +187 -0
- package/dist/learn/check.d.ts +99 -0
- package/dist/learn/check.js +259 -0
- package/dist/learn/grade.d.ts +79 -0
- package/dist/learn/grade.js +433 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +146 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +167 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +111 -0
- package/dist/learn/skills.d.ts +84 -0
- package/dist/learn/skills.js +198 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +304 -0
- package/dist/learning-run.js +797 -0
- package/dist/learning-words.d.ts +73 -0
- package/dist/learning-words.js +171 -0
- package/dist/learning.d.ts +377 -0
- package/dist/learning.js +801 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +115 -0
- package/dist/mcp-servers.js +445 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +184 -0
- package/dist/model.js +484 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4805 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1417 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +46 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +68 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +46 -0
- package/dist/place.js +105 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +38 -0
- package/dist/propose.js +82 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +14 -0
- package/dist/request-start.js +226 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +134 -0
- package/dist/run-box.js +440 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +80 -0
- package/dist/runnable.js +162 -0
- package/dist/runs.d.ts +840 -0
- package/dist/runs.js +2279 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +50 -0
- package/dist/secrets.js +140 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +626 -0
- package/dist/server.js +1756 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/skills.d.ts +31 -0
- package/dist/skills.js +68 -0
- package/dist/stats.d.ts +101 -0
- package/dist/stats.js +82 -0
- package/dist/tool-keys.d.ts +151 -0
- package/dist/tool-keys.js +273 -0
- package/dist/tool-plane.d.ts +143 -0
- package/dist/tool-plane.js +242 -0
- package/dist/tools.d.ts +147 -0
- package/dist/tools.js +253 -0
- package/dist/turn-end.d.ts +23 -0
- package/dist/turn-end.js +14 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +55 -0
- package/dist/validate.js +175 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +182 -0
- package/dist/webhooks.js +487 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +94 -4
- 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
|
+
};
|
package/dist/place.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
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. */
|
|
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
|
+
/** Why a sandbox-only tool (bash) cannot run on this server: no box runs execute in is available, each with its reason.
|
|
18
|
+
* Undefined when one is. */
|
|
19
|
+
export declare function noBoxReason(registry: readonly BoxOffer[]): string | undefined;
|
|
20
|
+
/** The start banner's words on the boxes: which are ready for a sandbox agent's tools, which are still preparing (an
|
|
21
|
+
* available box whose `state` says so, with its reason: what it is pulling), then why each box is not that
|
|
22
|
+
* AGENTRUN_BOXES lists (`listed`), or, when none is ready or preparing, each box runs execute in, with what to do. */
|
|
23
|
+
export declare function boxesLine(registry: readonly BoxOffer[], listed: ReadonlySet<BoxId>): string;
|
|
24
|
+
/** `places` in capabilities: the modes a revision may name, this host's default, and each box. */
|
|
25
|
+
export declare const placesOf: (registry: readonly BoxOffer[]) => {
|
|
26
|
+
modes: ("runner" | "sandbox")[];
|
|
27
|
+
default: "runner";
|
|
28
|
+
boxes: BoxOffer[];
|
|
29
|
+
};
|
|
30
|
+
/** A run's place: its revision's, else this host's default. */
|
|
31
|
+
export declare const resolvePlace: (revision: Place | undefined) => Place;
|
|
32
|
+
/** The place a run kept (its serve.json), or runner for a run kept before runs had one. */
|
|
33
|
+
export declare function storedPlace(value: unknown): Place;
|
|
34
|
+
/** Where a box binds the run's work/, and where its tools start. */
|
|
35
|
+
export declare const BOX_WORK = "/run/agentrun/run/work";
|
|
36
|
+
/** The boxes that cannot bind a run's work/, being on another machine: its work/ is seeded at the box's making and
|
|
37
|
+
* pulled back (run-box.ts). */
|
|
38
|
+
export declare const REMOTE_BOXES: readonly BoxId[];
|
|
39
|
+
export declare const remotePlace: (place: Place) => boolean;
|
|
40
|
+
/** The run's work/ as its agent's tools see it: on the runner, `<runDir>/work`; in any box, BOX_WORK. */
|
|
41
|
+
export declare const agentWorkDir: (runDir: string, place: Place) => string;
|
|
42
|
+
/** `place` as a definition writes it, to copy: `"place": {"mode": "sandbox", "box": "docker"}`. */
|
|
43
|
+
export declare const placeFix: (place: Place) => string;
|
|
44
|
+
/** What is wrong with `place` as a definition gives it, as issues at `field`. Each names its fix: the field to remove,
|
|
45
|
+
* or the place to copy, the one it most likely meant. */
|
|
46
|
+
export declare function placeIssues(place: unknown, field: string): InputIssue[];
|
package/dist/place.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
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
|
+
import { join } from "node:path";
|
|
10
|
+
import { BOX_IDS } from "./boxes.js";
|
|
11
|
+
import { sentence } from "./errors.js";
|
|
12
|
+
export const PLACE_MODES = ["runner", "sandbox"];
|
|
13
|
+
export const DEFAULT_PLACE_MODE = "runner";
|
|
14
|
+
/** The boxes runs execute in so far. */
|
|
15
|
+
export const RUN_BOXES = ["docker", "daytona"];
|
|
16
|
+
/** The boxes this server gives runs, from what its registry set up at its start (boxes.ts): a box runs execute in
|
|
17
|
+
* that the registry has, and no other. */
|
|
18
|
+
export function boxAvailability(registry) {
|
|
19
|
+
return BOX_IDS.map((id) => {
|
|
20
|
+
const offer = registry.find((o) => o.id === id);
|
|
21
|
+
if (!offer)
|
|
22
|
+
return { id, available: false, reason: `${id} is not set up on this server` };
|
|
23
|
+
if (!offer.available || RUN_BOXES.includes(id))
|
|
24
|
+
return { ...offer };
|
|
25
|
+
return { id, available: false, reason: `runs in the ${id} box are not available yet: use the ${RUN_BOXES.join(" or ")} box` };
|
|
26
|
+
});
|
|
27
|
+
}
|
|
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 function noBoxReason(registry) {
|
|
31
|
+
const boxes = boxAvailability(registry).filter((box) => RUN_BOXES.includes(box.id));
|
|
32
|
+
if (boxes.some((box) => box.available))
|
|
33
|
+
return undefined;
|
|
34
|
+
return `no box is set up on this server: ${boxes.map((box) => `${box.id} is unavailable (${box.reason ?? "no reason given"})`).join("; ")}`;
|
|
35
|
+
}
|
|
36
|
+
/** The start banner's words on the boxes: which are ready for a sandbox agent's tools, which are still preparing (an
|
|
37
|
+
* available box whose `state` says so, with its reason: what it is pulling), then why each box is not that
|
|
38
|
+
* AGENTRUN_BOXES lists (`listed`), or, when none is ready or preparing, each box runs execute in, with what to do. */
|
|
39
|
+
export function boxesLine(registry, listed) {
|
|
40
|
+
const boxes = boxAvailability(registry);
|
|
41
|
+
const preparing = (box) => box.state === "preparing";
|
|
42
|
+
const ready = boxes.filter((box) => box.available && !preparing(box)).map((box) => box.id);
|
|
43
|
+
const coming = boxes.filter((box) => box.available && preparing(box));
|
|
44
|
+
const said = [
|
|
45
|
+
...(ready.length ? [`${new Intl.ListFormat("en", { type: "conjunction" }).format(ready)} ${ready.length === 1 ? "is" : "are"} ready, so sandbox agents run their tools there.`] : []),
|
|
46
|
+
...coming.map((box) => sentence(`${box.id} is preparing${box.reason ? ` (${box.reason})` : ""}`)),
|
|
47
|
+
];
|
|
48
|
+
const none = !said.length;
|
|
49
|
+
const why = boxes.filter((box) => !box.available && (listed.has(box.id) || (none && RUN_BOXES.includes(box.id))));
|
|
50
|
+
return ["Boxes:", ...(none ? ["none is ready, so sandbox agents do not run here."] : said), ...why.map((box) => sentence(`${box.id}: ${box.reason ?? "not available"}`))].join(" ");
|
|
51
|
+
}
|
|
52
|
+
/** `places` in capabilities: the modes a revision may name, this host's default, and each box. */
|
|
53
|
+
export const placesOf = (registry) => ({ modes: [...PLACE_MODES], default: DEFAULT_PLACE_MODE, boxes: boxAvailability(registry).map(stated) });
|
|
54
|
+
/** A box with its state: what the server set (a Docker box whose image is coming is `preparing`), else `ready` when it
|
|
55
|
+
* is available and `unavailable` when not. */
|
|
56
|
+
const stated = ({ state, ...offer }) => ({ ...offer, state: offer.available ? (state ?? "ready") : "unavailable" });
|
|
57
|
+
/** A run's place: its revision's, else this host's default. */
|
|
58
|
+
export const resolvePlace = (revision) => revision ?? { mode: "runner" };
|
|
59
|
+
/** The place a run kept (its serve.json), or runner for a run kept before runs had one. */
|
|
60
|
+
export function storedPlace(value) {
|
|
61
|
+
if (!isObject(value) || value.mode !== "sandbox" || !listed(BOX_IDS, value.box))
|
|
62
|
+
return { mode: "runner" };
|
|
63
|
+
return { mode: "sandbox", box: value.box };
|
|
64
|
+
}
|
|
65
|
+
/** Where a box binds the run's work/, and where its tools start. */
|
|
66
|
+
export const BOX_WORK = "/run/agentrun/run/work";
|
|
67
|
+
/** The boxes that cannot bind a run's work/, being on another machine: its work/ is seeded at the box's making and
|
|
68
|
+
* pulled back (run-box.ts). */
|
|
69
|
+
export const REMOTE_BOXES = ["daytona"];
|
|
70
|
+
export const remotePlace = (place) => place.mode === "sandbox" && REMOTE_BOXES.includes(place.box);
|
|
71
|
+
/** The run's work/ as its agent's tools see it: on the runner, `<runDir>/work`; in any box, BOX_WORK. */
|
|
72
|
+
export const agentWorkDir = (runDir, place) => (place.mode === "runner" ? join(runDir, "work") : BOX_WORK);
|
|
73
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
74
|
+
const listed = (options, value) => typeof value === "string" && options.includes(value);
|
|
75
|
+
/** `place` as a definition writes it, to copy: `"place": {"mode": "sandbox", "box": "docker"}`. */
|
|
76
|
+
export const placeFix = (place) => `"place": ${place.mode === "runner" ? '{"mode": "runner"}' : `{"mode": "sandbox", "box": "${place.box}"}`}`;
|
|
77
|
+
/** The option of `options` that `value` names in any case, if any. */
|
|
78
|
+
const named = (options, value) => (typeof value === "string" ? options.find((option) => option === value.trim().toLowerCase()) : undefined);
|
|
79
|
+
/** The place a definition most likely meant by a `place` that is none: the runner when that is all it names, else a
|
|
80
|
+
* sandbox on the box it names (as its box, or as its mode), or on the first box runs execute in. */
|
|
81
|
+
function meant(place) {
|
|
82
|
+
const box = isObject(place) ? named(BOX_IDS, place.box) ?? named(BOX_IDS, place.mode) : named(BOX_IDS, place);
|
|
83
|
+
if (!box && named(PLACE_MODES, isObject(place) ? place.mode : place) === "runner")
|
|
84
|
+
return { mode: "runner" };
|
|
85
|
+
return { mode: "sandbox", box: box ?? RUN_BOXES[0] };
|
|
86
|
+
}
|
|
87
|
+
/** What is wrong with `place` as a definition gives it, as issues at `field`. Each names its fix: the field to remove,
|
|
88
|
+
* or the place to copy, the one it most likely meant. */
|
|
89
|
+
export function placeIssues(place, field) {
|
|
90
|
+
const bad = (reason, message, fix = placeFix(meant(place))) => [{ field, reason, message, fix }];
|
|
91
|
+
if (!isObject(place))
|
|
92
|
+
return bad("wrong_type", `${field} is an object: {mode}, or {mode, box}`);
|
|
93
|
+
const extra = Object.keys(place).filter((key) => key !== "mode" && key !== "box");
|
|
94
|
+
if (extra.length)
|
|
95
|
+
return bad("not_allowed", `${field} keeps only mode and box, not ${extra.join(" or ")}`, `Remove ${extra.map((key) => `${field}.${key}`).join(" and ")}.`);
|
|
96
|
+
if (!listed(PLACE_MODES, place.mode))
|
|
97
|
+
return bad(place.mode === undefined ? "missing" : "not_an_option", `${field}.mode is one of ${PLACE_MODES.join(", ")}`);
|
|
98
|
+
if (place.mode === "runner")
|
|
99
|
+
return place.box === undefined ? [] : bad("not_allowed", "a runner place uses no box", `Remove ${field}.box.`);
|
|
100
|
+
if (place.box === undefined)
|
|
101
|
+
return bad("missing", `a sandbox place names its box: one of ${BOX_IDS.join(", ")}`);
|
|
102
|
+
if (!listed(BOX_IDS, place.box))
|
|
103
|
+
return bad("not_an_option", `${field}.box is one of ${BOX_IDS.join(", ")}`);
|
|
104
|
+
return [];
|
|
105
|
+
}
|
package/dist/print.d.ts
ADDED
|
@@ -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,38 @@
|
|
|
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
|
+
} | {
|
|
9
|
+
state: "dropped";
|
|
10
|
+
reason: "empty";
|
|
11
|
+
} | {
|
|
12
|
+
state: "dropped";
|
|
13
|
+
reason: "unparsed";
|
|
14
|
+
detail: string;
|
|
15
|
+
} | {
|
|
16
|
+
state: "dropped";
|
|
17
|
+
reason: "checker";
|
|
18
|
+
problems: Problem[];
|
|
19
|
+
};
|
|
20
|
+
/** What a run's end-of-run turn answered (`turn`, as its directory kept it), parsed, checked against its seed `seed` (its
|
|
21
|
+
* pin) and kept in `runDir` as its proposal, with what the user said in the run as the grader reads it (each message
|
|
22
|
+
* cut of the host's secrets, then to GRADE_CAPS.askedMessage); or `empty` when it gave nothing, `unparsed` when its
|
|
23
|
+
* answer is out of format, or `checker` with the problems, printable. A note, skill or draft the answer gives with the
|
|
24
|
+
* very text the seed holds is no change, and `MEMORY.md` is the host's (the checker ignores it). A skill is laid at
|
|
25
|
+
* `skills/<name>/SKILL.md`; a draft at `workflows/<name>/workflow.json`, with the README.md the host writes from the
|
|
26
|
+
* description its block gives. `outcome`, how the run's job ended (only a completed run adds or changes a skill);
|
|
27
|
+
* `tools`, those a draft may name (tools.ts learnedWorkflowTools); `refuse`: this host's secrets. In the agent's
|
|
28
|
+
* queue. */
|
|
29
|
+
export declare const proposeRun: (input: {
|
|
30
|
+
data: string;
|
|
31
|
+
agentId: string;
|
|
32
|
+
runDir: string;
|
|
33
|
+
seed: string;
|
|
34
|
+
turn: Turn;
|
|
35
|
+
refuse: readonly string[];
|
|
36
|
+
outcome?: string;
|
|
37
|
+
tools?: readonly string[];
|
|
38
|
+
}) => Promise<Proposed>;
|
package/dist/propose.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
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, 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
|
+
/** `text`'s first `max` UTF-16 units, never half a character. */
|
|
13
|
+
const cut = (text, max) => (text.length <= max ? text : [...text].reduce((out, ch) => (out.length + ch.length > max ? out : out + ch), ""));
|
|
14
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
15
|
+
/** The skills and drafts on the seed `sha`: every path under skills/ and workflows/, and the text of each regular file of
|
|
16
|
+
* them `wanted` names (one that is not UTF-8 is left out, so an answer that gives it is a change). */
|
|
17
|
+
async function seedFiles(home, repo, sha, wanted) {
|
|
18
|
+
const listed = (await git(home, repo, ["ls-tree", "-r", "-z", sha, "--", SKILLS_DIR, WORKFLOWS_DIR])).toString("utf8").split("\0").filter(Boolean).map((entry) => {
|
|
19
|
+
const [mode, type, oid] = entry.slice(0, entry.indexOf("\t")).split(" ");
|
|
20
|
+
return { mode, type, oid: oid, path: entry.slice(entry.indexOf("\t") + 1) };
|
|
21
|
+
});
|
|
22
|
+
const read = listed.filter((entry) => entry.mode === "100644" && entry.type === "blob" && wanted.includes(entry.path));
|
|
23
|
+
const blobs = await readBlobs(home, repo, read.map((entry) => entry.oid));
|
|
24
|
+
const texts = new Map();
|
|
25
|
+
read.forEach((entry, i) => {
|
|
26
|
+
try {
|
|
27
|
+
texts.set(entry.path, utf8.decode(blobs[i]));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// Not UTF-8: no text the answer can give again.
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
return { files: listed.map((entry) => entry.path), texts };
|
|
34
|
+
}
|
|
35
|
+
/** What a run's end-of-run turn answered (`turn`, as its directory kept it), parsed, checked against its seed `seed` (its
|
|
36
|
+
* pin) and kept in `runDir` as its proposal, with what the user said in the run as the grader reads it (each message
|
|
37
|
+
* cut of the host's secrets, then to GRADE_CAPS.askedMessage); or `empty` when it gave nothing, `unparsed` when its
|
|
38
|
+
* answer is out of format, or `checker` with the problems, printable. A note, skill or draft the answer gives with the
|
|
39
|
+
* very text the seed holds is no change, and `MEMORY.md` is the host's (the checker ignores it). A skill is laid at
|
|
40
|
+
* `skills/<name>/SKILL.md`; a draft at `workflows/<name>/workflow.json`, with the README.md the host writes from the
|
|
41
|
+
* description its block gives. `outcome`, how the run's job ended (only a completed run adds or changes a skill);
|
|
42
|
+
* `tools`, those a draft may name (tools.ts learnedWorkflowTools); `refuse`: this host's secrets. In the agent's
|
|
43
|
+
* queue. */
|
|
44
|
+
export const proposeRun = (input) => withAgentRepo(input.data, input.agentId, async () => {
|
|
45
|
+
const home = homeOf(input.data, input.agentId);
|
|
46
|
+
const repo = await agentFolder(input.data, input.agentId);
|
|
47
|
+
const seed = await readSeed(home, repo, input.seed);
|
|
48
|
+
const parsed = parseReflection(input.turn.answer);
|
|
49
|
+
if (!parsed.ok)
|
|
50
|
+
return parsed.reason === "empty" ? { state: "dropped", reason: "empty" } : { state: "dropped", reason: "unparsed", detail: parsed.detail };
|
|
51
|
+
// Each skill and draft as the folder would hold it; a draft is its two files, given together or not at all.
|
|
52
|
+
const given = [
|
|
53
|
+
...(parsed.skills ?? []).map(({ name, text }) => [{ file: `${SKILLS_DIR}/${name}/SKILL.md`, text }]),
|
|
54
|
+
...(parsed.workflows ?? []).map(({ name, text }) => {
|
|
55
|
+
const { json, readme } = draftFiles(name, text);
|
|
56
|
+
return [{ file: `${WORKFLOWS_DIR}/${name}/workflow.json`, text: json }, { file: `${WORKFLOWS_DIR}/${name}/README.md`, text: readme }];
|
|
57
|
+
}),
|
|
58
|
+
];
|
|
59
|
+
const held = given.length ? await seedFiles(home, repo, input.seed, given.flat().map(({ file }) => file)) : { files: [], texts: new Map() };
|
|
60
|
+
const files = given.filter((group) => group.some(({ file, text }) => held.texts.get(file) !== text)).flat();
|
|
61
|
+
const changes = [
|
|
62
|
+
...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) })),
|
|
63
|
+
...files.map(({ file, text }) => ({ path: file, status: held.files.includes(file) ? "modified" : "added", mode: "100644", bytes: Buffer.from(text) })),
|
|
64
|
+
];
|
|
65
|
+
// The workflow DSL reads a draft, and is loaded only when there is one to read.
|
|
66
|
+
const dsl = files.some(({ file }) => file.endsWith("/workflow.json")) ? await import("@parcha/agentrun-dsl") : undefined;
|
|
67
|
+
// A skill or a draft whose seed text has a status is a person's call (retired, or waiting for their OK): never changed.
|
|
68
|
+
const kept = [...held.texts].filter(([file, text]) => (file.endsWith("/SKILL.md") || file.endsWith("/README.md")) && learnedStatus(text) !== "active").map(([file]) => file);
|
|
69
|
+
const checked = checkProposal({ base: { files: [...seed.files, ...held.files], active: activeOf(seed) }, changes, refuseValues: input.refuse, ...(kept.length ? { kept } : {}), ...(input.outcome === undefined ? {} : { outcome: input.outcome }), ...(input.tools ? { tools: input.tools } : {}), ...(dsl ? { dsl } : {}) });
|
|
70
|
+
if (checked.problems.length)
|
|
71
|
+
return { state: "dropped", reason: "checker", problems: checked.problems };
|
|
72
|
+
if (!checked.notes.length && !files.length)
|
|
73
|
+
return { state: "dropped", reason: "empty" };
|
|
74
|
+
// Each message cut of the host's secrets whole first, and only then shortened: a secret the cut fell inside would
|
|
75
|
+
// leave a part of itself that no longer matches. The whole message is read, however long (a message is bounded by
|
|
76
|
+
// the run's own request limits), so a long one is not lost to the grader as one "[redacted]".
|
|
77
|
+
const asked = input.turn.asked.map((message) => cut(redactSecrets(message, input.refuse, Number.POSITIVE_INFINITY), GRADE_CAPS.askedMessage));
|
|
78
|
+
const proposal = { seed: input.seed, notes: checked.notes.map(({ file, text }) => ({ file, text })), ...(files.length ? { files } : {}), asked };
|
|
79
|
+
await writeDurable(join(input.runDir, PROPOSAL), `${JSON.stringify(proposal)}\n`);
|
|
80
|
+
const count = (suffix) => files.filter(({ file }) => file.endsWith(suffix)).length;
|
|
81
|
+
return { state: "proposed", notes: proposal.notes.length, skills: count("/SKILL.md"), workflows: count("/workflow.json") };
|
|
82
|
+
});
|
|
@@ -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,14 @@
|
|
|
1
|
+
import type { Models } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { DurableRun } from "@parcha/pi-durable-disk";
|
|
3
|
+
/** Whether the run in `root` (its directory) was cancelled: the mark serve's cancel writes there first. */
|
|
4
|
+
export declare const cancelledIn: (root: string) => () => boolean;
|
|
5
|
+
/** How long a request's result waits for its end mark to be written, so it lands before pi's entry for the request. */
|
|
6
|
+
export declare const END_MARK_WAIT_MS = 1000;
|
|
7
|
+
/** `models` with each generation request marked before it leaves, once `open` hands over the run (its Harness). Once
|
|
8
|
+
* `cancelled` says the run was cancelled, no request is sent: each is refused here, before it is marked, or after its
|
|
9
|
+
* mark when the cancel came while the mark waited, and then its start is withdrawn (an end mark, `unsent`). */
|
|
10
|
+
export declare function markRequests<M extends Models>(models: M, cancelled?: () => boolean): Promise<{
|
|
11
|
+
models: M;
|
|
12
|
+
open(run: DurableRun): void;
|
|
13
|
+
refused(): Promise<void>;
|
|
14
|
+
}>;
|