@parcha/agentrun-serve 0.0.0-bootstrap.0 → 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 +1724 -0
- 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 +96 -1
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/uploads.js
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
// Uploads: a file reserved (POST /v2/files) and its bytes sent (PUT /v2/files/{file_id}), or sent in one call (POST
|
|
2
|
+
// /v2/files?path=..., the bytes the body); listed, read and deleted; and the ready files a run names (`file_ids`) copied
|
|
3
|
+
// into its workspace before its process starts. Each file is `<data>/files/<file_id>/`: its bytes
|
|
4
|
+
// (`bytes`) and its record (`file.json`, the contract's File), both 0600, the record written whole. A ready file's bytes
|
|
5
|
+
// never change, and a run gets a copy of them, never a link: nothing a run does reaches the upload, and the run's file
|
|
6
|
+
// reads (workspace.ts) refuse a file with a second link.
|
|
7
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
+
import { createReadStream } from "node:fs";
|
|
9
|
+
import { lstat, mkdir, open, readdir, rename, rm, unlink } from "node:fs/promises";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { pipeline } from "node:stream/promises";
|
|
12
|
+
import { ApiError, invalid } from "./errors.js";
|
|
13
|
+
import { readJson, serialBy, tempOf, writeDurable } from "./files.js";
|
|
14
|
+
import { ID, unknownFields } from "./validate.js";
|
|
15
|
+
import { typeOf } from "./workspace.js";
|
|
16
|
+
/** `limits.max_upload_bytes`: the largest file a reservation names and a PUT sends. */
|
|
17
|
+
export const MAX_UPLOAD_BYTES = 50 * 2 ** 20;
|
|
18
|
+
/** `limits.max_files_per_run`: the most files one run names (the contract's `RunCreate.file_ids` takes at most 100). */
|
|
19
|
+
export const MAX_FILES_PER_RUN = 20;
|
|
20
|
+
/** Where a run finds its files: `work/inputs/<path>`, each file's `path` with its folders. */
|
|
21
|
+
export const INPUTS_DIR = "inputs";
|
|
22
|
+
/** The data directory's folder of uploads. */
|
|
23
|
+
export const UPLOADS_DIR = "files";
|
|
24
|
+
const RECORD = "file.json";
|
|
25
|
+
const BYTES = "bytes";
|
|
26
|
+
/** The `upload.expires_at` the answer to a reservation gives, which the contract requires: advisory, not enforced in this
|
|
27
|
+
* release. A later PUT is still taken, and nothing deletes an upload. */
|
|
28
|
+
const UPLOAD_WINDOW_MS = 86_400_000;
|
|
29
|
+
/** The longest name one path segment takes on disk (NAME_MAX), in bytes. */
|
|
30
|
+
const NAME_MAX = 255;
|
|
31
|
+
/** The longest path the system opens (PATH_MAX), in bytes with its NUL: 1024 on macOS, 4096 elsewhere. */
|
|
32
|
+
const PATH_MAX = process.platform === "darwin" ? 1024 : 4096;
|
|
33
|
+
/** A run id's room in a run's copy of a file: a UUIDv7's 36 characters. */
|
|
34
|
+
const RUN_ID_ROOM = "x".repeat(36);
|
|
35
|
+
/** The room a run's copy may add to each segment: a suffix, at most one past the most files a run names. */
|
|
36
|
+
const SUFFIX_ROOM = `-${MAX_FILES_PER_RUN + 1}`.length;
|
|
37
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
38
|
+
/** The temp files this module writes, by their exact names (files.ts tempOf: `<name>.<pid>.<12 hex digits>.tmp`): a file
|
|
39
|
+
* sent in one call, as its bytes arrive, under the root; a PUT's bytes, in its file's folder. */
|
|
40
|
+
const INCOMING_TEMP = /^\.incoming\.\d+\.[0-9a-f]{12}\.tmp$/;
|
|
41
|
+
const BYTES_TEMP = /^bytes\.\d+\.[0-9a-f]{12}\.tmp$/;
|
|
42
|
+
const FIELDS = ["path", "size_bytes", "content_type", "sha256"];
|
|
43
|
+
/** What a file sent in one call takes in the query: its path, and when given its type and the hash its bytes must have. */
|
|
44
|
+
const QUERY = ["path", "content_type", "sha256"];
|
|
45
|
+
/** A request's types that say only "bytes", never the file's own: curl's `--data-binary` default and octet-stream. */
|
|
46
|
+
const GENERIC_TYPES = new Set(["application/octet-stream", "application/x-www-form-urlencoded"]);
|
|
47
|
+
/** Where a file's bytes go: its own PUT, as a path from the server's root, so it resolves against the server's address
|
|
48
|
+
* as given (`http://host:port`) or as the contract's `/v2` server URL alike. */
|
|
49
|
+
export const uploadUrl = (id) => `/v2/files/${id}`;
|
|
50
|
+
/** Test seams, tests only: as a run's copy starts, with the run's work/, before any file is copied; and as a file sent in
|
|
51
|
+
* one call writes its record, with the file's folder, its bytes in place. */
|
|
52
|
+
export const uploadTestHooks = {};
|
|
53
|
+
/** A UUIDv7, the form of the agent store's agent and run ids: 48 bits of Unix milliseconds, then random bits, so ids
|
|
54
|
+
* sort by creation time. The store mints its own inside it and exports no minter. */
|
|
55
|
+
function uuidv7(now = Date.now()) {
|
|
56
|
+
const bytes = randomBytes(16);
|
|
57
|
+
bytes.writeUIntBE(now, 0, 6);
|
|
58
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x70;
|
|
59
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
60
|
+
const hex = bytes.toString("hex");
|
|
61
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
62
|
+
}
|
|
63
|
+
/** Why `path` is not the contract's FilePathString (relative, `/` between segments, no empty segment and none that starts
|
|
64
|
+
* with `.`, no backslash or NUL, at most 1024 characters), or a segment is longer than a name on disk; undefined when it
|
|
65
|
+
* is one. */
|
|
66
|
+
export function pathProblem(path) {
|
|
67
|
+
if (path.length === 0 || [...path].length > 1024)
|
|
68
|
+
return "path is 1 to 1024 characters";
|
|
69
|
+
if (path.includes("\\") || path.includes("\0"))
|
|
70
|
+
return "path holds a backslash or a NUL";
|
|
71
|
+
const segments = path.split("/");
|
|
72
|
+
if (segments.some((s) => s === ""))
|
|
73
|
+
return "path has an empty segment: a leading, trailing or double /";
|
|
74
|
+
if (segments.some((s) => s.startsWith(".")))
|
|
75
|
+
return "path has a segment that starts with . (., .. or a dot-name)";
|
|
76
|
+
if (segments.some((s) => Buffer.byteLength(s) > NAME_MAX))
|
|
77
|
+
return `path has a segment longer than ${NAME_MAX} bytes`;
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
/** What a request sent, as its JSON (a string quoted), cut to 40 characters (an ellipsis the 40th when it is longer):
|
|
81
|
+
* by code points, so a surrogate pair is never split. A value JSON.stringify cannot write (nested past the stack, as a
|
|
82
|
+
* parsed body can be) is named as such: describing a bad value never fails the refusal. */
|
|
83
|
+
const shown = (value) => {
|
|
84
|
+
let json;
|
|
85
|
+
try {
|
|
86
|
+
json = JSON.stringify(value) ?? String(value);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return "a value too deep to show";
|
|
90
|
+
}
|
|
91
|
+
const chars = [...json];
|
|
92
|
+
return chars.length > 40 ? `${chars.slice(0, 39).join("")}\u2026` : chars.join("");
|
|
93
|
+
};
|
|
94
|
+
/** `name` for the first, then `name-2`, `name-3`, ... before its extension (`report-2.pdf`), cut to fit a name on disk:
|
|
95
|
+
* its stem first, down to one character, then its extension. */
|
|
96
|
+
export function suffixed(name, n) {
|
|
97
|
+
if (n === 1)
|
|
98
|
+
return name;
|
|
99
|
+
const dot = name.lastIndexOf(".");
|
|
100
|
+
let stem = [...(dot > 0 ? name.slice(0, dot) : name)];
|
|
101
|
+
let ext = [...(dot > 0 ? name.slice(dot) : "")];
|
|
102
|
+
const fits = () => Buffer.byteLength(`${stem.join("")}-${n}${ext.join("")}`) <= NAME_MAX;
|
|
103
|
+
while (!fits() && stem.length > 1)
|
|
104
|
+
stem = stem.slice(0, -1);
|
|
105
|
+
while (!fits() && ext.length > 0)
|
|
106
|
+
ext = ext.slice(0, -1);
|
|
107
|
+
return `${stem.join("")}-${n}${ext.join("")}`;
|
|
108
|
+
}
|
|
109
|
+
/** Writes all of `chunk`, or throws: a short write (a disk nearly full) never passes as whole. */
|
|
110
|
+
async function writeAll(handle, chunk) {
|
|
111
|
+
for (let at = 0; at < chunk.length;) {
|
|
112
|
+
const { bytesWritten } = await handle.write(chunk, at, chunk.length - at);
|
|
113
|
+
if (bytesWritten <= 0)
|
|
114
|
+
throw new Error(`wrote ${at} of ${chunk.length} bytes`);
|
|
115
|
+
at += bytesWritten;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const isFile = (value) => value !== null && typeof value.file_id === "string" && typeof value.path === "string" && Number.isSafeInteger(value.size_bytes) && typeof value.content_type === "string" && (value.status === "pending" || value.status === "ready");
|
|
119
|
+
export class Uploads {
|
|
120
|
+
root;
|
|
121
|
+
/** The commit of each file's bytes in progress: one at a time per file, so of two PUTs at once one makes it ready and
|
|
122
|
+
* the other is checked against it. */
|
|
123
|
+
commits = new Map();
|
|
124
|
+
/** `root`: `<data>/files`. */
|
|
125
|
+
constructor(root) {
|
|
126
|
+
this.root = root;
|
|
127
|
+
}
|
|
128
|
+
/** Why `path` cannot be a file's path here: not the contract's FilePathString, a segment longer than a name on disk,
|
|
129
|
+
* or a run's copy of it (`<data>/runs/<run id>/work/inputs/<path>`, room for a suffix on each segment included) longer
|
|
130
|
+
* than a path the system opens. Undefined when it can. */
|
|
131
|
+
problemOf(path) {
|
|
132
|
+
const problem = pathProblem(path);
|
|
133
|
+
if (problem)
|
|
134
|
+
return problem;
|
|
135
|
+
const longest = Buffer.byteLength(join(dirname(this.root), "runs", RUN_ID_ROOM, "work", INPUTS_DIR, path)) + path.split("/").length * SUFFIX_ROOM + 1;
|
|
136
|
+
return longest > PATH_MAX ? `path is too long for this server's disk: a run's copy of it would take up to ${longest} bytes, over ${PATH_MAX}` : undefined;
|
|
137
|
+
}
|
|
138
|
+
/** The file `id`, or null when there is none. */
|
|
139
|
+
async get(id) {
|
|
140
|
+
if (!ID.test(id))
|
|
141
|
+
return null;
|
|
142
|
+
const record = await readJson(join(this.root, id, RECORD));
|
|
143
|
+
return isFile(record) && record.file_id === id ? record : null;
|
|
144
|
+
}
|
|
145
|
+
/** Every file's id, newest first: a UUIDv7 sorts by its time. The files' list reads them a page at a time. */
|
|
146
|
+
async ids() {
|
|
147
|
+
const names = await readdir(this.root).catch(() => []);
|
|
148
|
+
return names.filter((name) => ID.test(name)).sort().reverse();
|
|
149
|
+
}
|
|
150
|
+
/** At a start, under the data directory's lock (one server per data directory, so no PUT of this server is in flight):
|
|
151
|
+
* removes the temp files a crash left, by the exact names this module writes them under. That is `.incoming.*.tmp`
|
|
152
|
+
* under the root, and `bytes.*.tmp` in a folder named as a file's id. Each goes only when lstat says it is a regular
|
|
153
|
+
* file: a link or anything else named like one stays, nothing is followed, and only those folders are entered, one
|
|
154
|
+
* level. A file's bytes and its record are never touched: a folder left with only its temp keeps the rest, as after a
|
|
155
|
+
* failed PUT. A root that is not a real directory (a link to storage another server may share) is not swept at all: the
|
|
156
|
+
* lock covers this data directory, not where a link goes. Answers how many it removed. */
|
|
157
|
+
async sweep() {
|
|
158
|
+
if (!(await lstat(this.root).catch(() => null))?.isDirectory())
|
|
159
|
+
return 0;
|
|
160
|
+
let removed = 0;
|
|
161
|
+
const drop = async (path) => {
|
|
162
|
+
if (!(await lstat(path).catch(() => null))?.isFile())
|
|
163
|
+
return;
|
|
164
|
+
await unlink(path).then(() => void removed++, () => undefined);
|
|
165
|
+
};
|
|
166
|
+
for (const name of await readdir(this.root).catch(() => [])) {
|
|
167
|
+
if (INCOMING_TEMP.test(name))
|
|
168
|
+
await drop(join(this.root, name));
|
|
169
|
+
else if (ID.test(name) && (await lstat(join(this.root, name)).catch(() => null))?.isDirectory()) {
|
|
170
|
+
for (const inner of await readdir(join(this.root, name)).catch(() => []))
|
|
171
|
+
if (BYTES_TEMP.test(inner))
|
|
172
|
+
await drop(join(this.root, name, inner));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return removed;
|
|
176
|
+
}
|
|
177
|
+
/** Deletes the file `id`, pending or ready, or 404. A run that copied it keeps its copy. In turn with a PUT's commit, so
|
|
178
|
+
* a PUT that ends after the delete answers 404 and makes nothing. */
|
|
179
|
+
async remove(id) {
|
|
180
|
+
await this.exclusive(id, async () => {
|
|
181
|
+
if (!(await this.get(id)))
|
|
182
|
+
throw new ApiError("not_found", `no file ${id}: GET /v2/files lists the files this server keeps`);
|
|
183
|
+
await rm(join(this.root, id), { recursive: true, force: true });
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/** The answer to a reservation, and to a file sent in one call. `upload.expires_at` is advisory (UPLOAD_WINDOW_MS). */
|
|
187
|
+
answer(file) {
|
|
188
|
+
return { file, upload: { method: "PUT", url: uploadUrl(file.file_id), expires_at: new Date(Date.parse(file.created_at) + UPLOAD_WINDOW_MS).toISOString() } };
|
|
189
|
+
}
|
|
190
|
+
/** POST /v2/files?path=...: the body is the file's bytes, whatever its type but a multipart form (415, with the call
|
|
191
|
+
* that works). The query takes `path`, and `content_type` and `sha256` when given; the length is the body's and the hash
|
|
192
|
+
* its own. The type is `content_type`, else the request's when it names one (not octet-stream, not curl's form type),
|
|
193
|
+
* else the path's extension's, else octet-stream. The bytes stream to a dot-named file of their own under the root,
|
|
194
|
+
* never held whole; over MAX_UPLOAD_BYTES is 413, a `sha256` they do not have 422. Nothing is made until `commit`. */
|
|
195
|
+
async take(query, requestType, body) {
|
|
196
|
+
const type = String(requestType ?? "").trim();
|
|
197
|
+
if (/^multipart\//i.test(type))
|
|
198
|
+
throw new ApiError("unsupported_media_type", "A multipart form is not taken: send the file's bytes as the body, as `curl --data-binary @plan.md \"$AGENTRUN_BASE_URL/files?path=plan.md\"` does.");
|
|
199
|
+
const issues = [...new Set(query.keys())].filter((key) => !QUERY.includes(key)).map((key) => ({ field: key, reason: "not_allowed", message: `A file sent in one call takes path, content_type and sha256 in the query; ${key} is not one.` }));
|
|
200
|
+
for (const key of QUERY)
|
|
201
|
+
if (query.getAll(key).length > 1)
|
|
202
|
+
issues.push({ field: key, reason: "duplicate", message: `${key} is given more than once` });
|
|
203
|
+
const path = query.get("path");
|
|
204
|
+
// An empty one is none.
|
|
205
|
+
const named = query.get("content_type") || null;
|
|
206
|
+
const sha = query.get("sha256");
|
|
207
|
+
if (path === null)
|
|
208
|
+
issues.push({ field: "path", reason: "missing", message: "Name the file: POST /v2/files?path=<its path> with its bytes as the body, or a JSON reservation {path, size_bytes} and then PUT /v2/files/<id>.", fix: "Add ?path=<the file's name> to the URL." });
|
|
209
|
+
if (sha !== null && !SHA256.test(sha))
|
|
210
|
+
issues.push({ field: "sha256", reason: "bad_format", message: "sha256 is 64 lowercase hex digits" });
|
|
211
|
+
if (issues.length)
|
|
212
|
+
throw invalid(issues);
|
|
213
|
+
const problem = this.problemOf(path);
|
|
214
|
+
if (problem)
|
|
215
|
+
throw new ApiError("invalid_file_path", problem);
|
|
216
|
+
const given = type && !GENERIC_TYPES.has(type.split(";")[0].trim().toLowerCase()) ? type : undefined;
|
|
217
|
+
const contentType = named ?? given ?? typeOf(path) ?? "application/octet-stream";
|
|
218
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
219
|
+
const temp = tempOf(join(this.root, ".incoming"));
|
|
220
|
+
const handle = await open(temp, "wx", 0o600);
|
|
221
|
+
try {
|
|
222
|
+
const hash = createHash("sha256");
|
|
223
|
+
let size = 0;
|
|
224
|
+
// Read to its end, as a PUT's: the client gets the refusal, not a reset; nothing past the limit is written.
|
|
225
|
+
for await (const chunk of body) {
|
|
226
|
+
size += chunk.length;
|
|
227
|
+
hash.update(chunk);
|
|
228
|
+
if (size <= MAX_UPLOAD_BYTES)
|
|
229
|
+
await writeAll(handle, chunk);
|
|
230
|
+
}
|
|
231
|
+
if (size > MAX_UPLOAD_BYTES)
|
|
232
|
+
throw new ApiError("payload_too_large", `the body is over ${MAX_UPLOAD_BYTES} bytes, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
|
|
233
|
+
const sha256 = hash.digest("hex");
|
|
234
|
+
if (sha !== null && sha !== sha256)
|
|
235
|
+
throw invalid([{ field: "sha256", reason: "invalid", message: `The body's SHA-256 is ${sha256}; the query names ${sha}.` }]);
|
|
236
|
+
await handle.sync();
|
|
237
|
+
await handle.close();
|
|
238
|
+
const fingerprint = { sent_in_one_call: true, path: path, content_type: contentType, size_bytes: size, sha256 };
|
|
239
|
+
let made = false;
|
|
240
|
+
return {
|
|
241
|
+
fingerprint,
|
|
242
|
+
commit: async () => {
|
|
243
|
+
const now = Date.now();
|
|
244
|
+
const file = { file_id: uuidv7(now), path: path, size_bytes: size, content_type: contentType, sha256, status: "ready", created_at: new Date(now).toISOString(), expires_at: null };
|
|
245
|
+
const dir = join(this.root, file.file_id);
|
|
246
|
+
await mkdir(dir, { mode: 0o700 });
|
|
247
|
+
try {
|
|
248
|
+
await rename(temp, join(dir, BYTES));
|
|
249
|
+
made = true;
|
|
250
|
+
await uploadTestHooks.beforeRecord?.(dir);
|
|
251
|
+
await writeDurable(join(dir, RECORD), `${JSON.stringify(file)}\n`);
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
// No record, no file: its folder and bytes go too, so nothing is left that the API cannot list or delete.
|
|
255
|
+
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
return this.answer(file);
|
|
259
|
+
},
|
|
260
|
+
discard: async () => {
|
|
261
|
+
if (!made)
|
|
262
|
+
await unlink(temp).catch(() => undefined);
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
await handle.close().catch(() => undefined);
|
|
268
|
+
await unlink(temp).catch(() => undefined);
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
/** POST /v2/files: the body checked as the contract's FileCreate, then a pending file; with where to send its bytes. */
|
|
273
|
+
async reserve(body) {
|
|
274
|
+
const issues = unknownFields(body, FIELDS);
|
|
275
|
+
if (typeof body.path !== "string")
|
|
276
|
+
issues.push({ field: "path", reason: body.path === undefined ? "missing" : "wrong_type", message: "path is the file's relative path, a string" });
|
|
277
|
+
if (!(Number.isSafeInteger(body.size_bytes) && body.size_bytes >= 0))
|
|
278
|
+
issues.push({ field: "size_bytes", reason: body.size_bytes === undefined ? "missing" : "wrong_type", message: "size_bytes is the file's length in bytes, an integer 0 or more" });
|
|
279
|
+
if (body.content_type !== undefined && typeof body.content_type !== "string")
|
|
280
|
+
issues.push({ field: "content_type", reason: "wrong_type", message: "content_type is a string" });
|
|
281
|
+
if (body.sha256 !== undefined && !(typeof body.sha256 === "string" && SHA256.test(body.sha256)))
|
|
282
|
+
issues.push({ field: "sha256", reason: typeof body.sha256 === "string" ? "bad_format" : "wrong_type", message: "sha256 is 64 lowercase hex digits" });
|
|
283
|
+
if (issues.length)
|
|
284
|
+
throw invalid(issues);
|
|
285
|
+
const problem = this.problemOf(body.path);
|
|
286
|
+
if (problem)
|
|
287
|
+
throw new ApiError("invalid_file_path", problem);
|
|
288
|
+
if (body.size_bytes > MAX_UPLOAD_BYTES)
|
|
289
|
+
throw new ApiError("payload_too_large", `size_bytes is over ${MAX_UPLOAD_BYTES}, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
|
|
290
|
+
const now = Date.now();
|
|
291
|
+
const file = {
|
|
292
|
+
file_id: uuidv7(now),
|
|
293
|
+
path: body.path,
|
|
294
|
+
size_bytes: body.size_bytes,
|
|
295
|
+
// Named, or by the path's extension as a run's files are served (`plan.md` is text/markdown), else octet-stream.
|
|
296
|
+
content_type: body.content_type ?? typeOf(body.path) ?? "application/octet-stream",
|
|
297
|
+
sha256: body.sha256 ?? null,
|
|
298
|
+
status: "pending",
|
|
299
|
+
created_at: new Date(now).toISOString(),
|
|
300
|
+
expires_at: null,
|
|
301
|
+
};
|
|
302
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
303
|
+
await mkdir(join(this.root, file.file_id), { mode: 0o700 });
|
|
304
|
+
await writeDurable(join(this.root, file.file_id, RECORD), `${JSON.stringify(file)}\n`);
|
|
305
|
+
return this.answer(file);
|
|
306
|
+
}
|
|
307
|
+
/** PUT /v2/files/{file_id}: `body` is the bytes, streamed to a file of their own beside the record, never held whole.
|
|
308
|
+
* Their length must be the reserved `size_bytes` and their hash the reserved `sha256` when one was given (422 at that
|
|
309
|
+
* field), and they are at most MAX_UPLOAD_BYTES (413). Then they are renamed into place and the file is ready. A
|
|
310
|
+
* ready file's bytes are checked the same way against its own and kept: the same bytes again change nothing. */
|
|
311
|
+
async receive(id, body) {
|
|
312
|
+
const file = await this.get(id);
|
|
313
|
+
if (!file)
|
|
314
|
+
throw new ApiError("not_found", `no file ${id}`);
|
|
315
|
+
const dir = join(this.root, id);
|
|
316
|
+
const temp = file.status === "pending" ? tempOf(join(dir, BYTES)) : undefined;
|
|
317
|
+
// A DELETE that lands between the read above and this open has taken the folder: the file is gone, a 404. Any other
|
|
318
|
+
// failure of the open stays the server's own.
|
|
319
|
+
const handle = temp
|
|
320
|
+
? await open(temp, "wx", 0o600).catch((error) => {
|
|
321
|
+
if (error.code === "ENOENT")
|
|
322
|
+
throw new ApiError("not_found", `no file ${id}: it was deleted as its bytes arrived`);
|
|
323
|
+
throw error;
|
|
324
|
+
})
|
|
325
|
+
: undefined;
|
|
326
|
+
let closed = false;
|
|
327
|
+
let kept = false;
|
|
328
|
+
try {
|
|
329
|
+
const hash = createHash("sha256");
|
|
330
|
+
let size = 0;
|
|
331
|
+
// An oversized body is read to its end before the refusal, so the client gets the answer and not a reset; only the
|
|
332
|
+
// reserved length is ever written.
|
|
333
|
+
for await (const chunk of body) {
|
|
334
|
+
size += chunk.length;
|
|
335
|
+
hash.update(chunk);
|
|
336
|
+
if (handle && size <= file.size_bytes)
|
|
337
|
+
await writeAll(handle, chunk);
|
|
338
|
+
}
|
|
339
|
+
if (size > MAX_UPLOAD_BYTES)
|
|
340
|
+
throw new ApiError("payload_too_large", `the body is over ${MAX_UPLOAD_BYTES} bytes, this server's largest upload`, { details: { limit: "max_upload_bytes" } });
|
|
341
|
+
const sha256 = hash.digest("hex");
|
|
342
|
+
const mismatch = (held) => size !== held.size_bytes
|
|
343
|
+
? invalid([{ field: "size_bytes", reason: "invalid", message: `The body is ${size} bytes; the file was reserved with size_bytes ${held.size_bytes}.` }])
|
|
344
|
+
: held.sha256 !== null && held.sha256 !== sha256
|
|
345
|
+
? invalid([{ field: "sha256", reason: "invalid", message: `The body's SHA-256 is ${sha256}; the file ${held.status === "ready" ? "is ready with" : "was reserved with"} ${held.sha256}.` }])
|
|
346
|
+
: undefined;
|
|
347
|
+
const wrong = mismatch(file);
|
|
348
|
+
if (wrong)
|
|
349
|
+
throw wrong;
|
|
350
|
+
// Ready already: read again in turn with a DELETE, which may have removed it while these bytes arrived.
|
|
351
|
+
if (!handle || !temp)
|
|
352
|
+
return await this.exclusive(id, async () => {
|
|
353
|
+
const now = await this.get(id);
|
|
354
|
+
if (!now)
|
|
355
|
+
throw new ApiError("not_found", `no file ${id}: it was deleted while its bytes arrived`);
|
|
356
|
+
const other = mismatch(now);
|
|
357
|
+
if (other)
|
|
358
|
+
throw other;
|
|
359
|
+
return now;
|
|
360
|
+
});
|
|
361
|
+
await handle.sync();
|
|
362
|
+
closed = true;
|
|
363
|
+
await handle.close();
|
|
364
|
+
return await this.exclusive(id, async () => {
|
|
365
|
+
// Read again: another PUT may have made it ready meanwhile, with these bytes or others, or a DELETE removed it.
|
|
366
|
+
const now = await this.get(id);
|
|
367
|
+
if (!now)
|
|
368
|
+
throw new ApiError("not_found", `no file ${id}: it was deleted while its bytes arrived`);
|
|
369
|
+
if (now.status === "ready") {
|
|
370
|
+
const other = mismatch(now);
|
|
371
|
+
if (other)
|
|
372
|
+
throw other;
|
|
373
|
+
return now;
|
|
374
|
+
}
|
|
375
|
+
await rename(temp, join(dir, BYTES));
|
|
376
|
+
kept = true;
|
|
377
|
+
const ready = { ...now, sha256, status: "ready" };
|
|
378
|
+
await writeDurable(join(dir, RECORD), `${JSON.stringify(ready)}\n`);
|
|
379
|
+
return ready;
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
finally {
|
|
383
|
+
if (!closed)
|
|
384
|
+
await handle?.close().catch(() => undefined);
|
|
385
|
+
if (temp && !kept)
|
|
386
|
+
await unlink(temp).catch(() => undefined);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** `work` in turn for file `id`. The chain holds only settled turns, so one that failed never fails the next. */
|
|
390
|
+
exclusive(id, work) {
|
|
391
|
+
return serialBy(this.commits, id, work);
|
|
392
|
+
}
|
|
393
|
+
/** A run's `file_ids`: each a file that is ready, none twice, at most MAX_FILES_PER_RUN, or 422 at `file_ids`. */
|
|
394
|
+
async readyFiles(ids) {
|
|
395
|
+
const issues = [];
|
|
396
|
+
if (ids.length > MAX_FILES_PER_RUN)
|
|
397
|
+
issues.push({ field: "file_ids", reason: "too_many", message: `A run names at most ${MAX_FILES_PER_RUN} files here (limits.max_files_per_run); this names ${ids.length}.` });
|
|
398
|
+
else if (new Set(ids).size !== ids.length)
|
|
399
|
+
issues.push({ field: "file_ids", reason: "duplicate", message: "file_ids names one file twice" });
|
|
400
|
+
if (issues.length)
|
|
401
|
+
throw invalid(issues);
|
|
402
|
+
const files = [];
|
|
403
|
+
for (const [i, id] of ids.entries()) {
|
|
404
|
+
const field = `file_ids[${i}]`;
|
|
405
|
+
if (typeof id !== "string" || !ID.test(id)) {
|
|
406
|
+
issues.push({ field, reason: "wrong_type", message: `${field} is ${shown(id)}, not a file id: use the file_id an upload answered (POST /v2/files answers it under file.file_id).` });
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
const file = await this.get(id);
|
|
410
|
+
const problem = file?.status === "ready" ? this.problemOf(file.path) : undefined;
|
|
411
|
+
if (!file)
|
|
412
|
+
issues.push({ field, reason: "not_an_option", message: `There is no file ${id}: reserve it with POST /v2/files.` });
|
|
413
|
+
else if (file.status !== "ready")
|
|
414
|
+
issues.push({ field, reason: "invalid", message: `The file ${id} is not ready: send its bytes with PUT /v2/files/${id} first.` });
|
|
415
|
+
else if (problem)
|
|
416
|
+
issues.push({ field, reason: "invalid", message: `The file ${id} cannot be copied into a run here: ${problem}.` });
|
|
417
|
+
else
|
|
418
|
+
files.push(file);
|
|
419
|
+
}
|
|
420
|
+
if (issues.length)
|
|
421
|
+
throw invalid(issues);
|
|
422
|
+
return files;
|
|
423
|
+
}
|
|
424
|
+
/** Copies `files` into `work/inputs/`, each at its `path` with its folders, in order, before the run's process exists:
|
|
425
|
+
* a name taken already (the same path twice, or a file where another's folder goes) gets the next free suffix
|
|
426
|
+
* (`notes-2.txt`, `docs-2/`), the same for the same files in the same order. Each copy is a new file, made as the
|
|
427
|
+
* agent store makes a run's skill files (its mode from the umask): never a link to the upload. */
|
|
428
|
+
async copyInto(work, files) {
|
|
429
|
+
await uploadTestHooks.beforeCopy?.(work);
|
|
430
|
+
const base = join(work, INPUTS_DIR);
|
|
431
|
+
await mkdir(base, { recursive: true });
|
|
432
|
+
for (const file of files) {
|
|
433
|
+
const segments = file.path.split("/");
|
|
434
|
+
let dir = base;
|
|
435
|
+
for (const segment of segments.slice(0, -1))
|
|
436
|
+
dir = join(dir, await folderIn(dir, segment));
|
|
437
|
+
await copyIn(dir, segments.at(-1), join(this.root, file.file_id, BYTES));
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
/** The folder `name` in `dir`, made or one already there, or the first suffixed name free of a file. */
|
|
442
|
+
async function folderIn(dir, name) {
|
|
443
|
+
for (let n = 1;; n++) {
|
|
444
|
+
const candidate = suffixed(name, n);
|
|
445
|
+
try {
|
|
446
|
+
await mkdir(join(dir, candidate));
|
|
447
|
+
return candidate;
|
|
448
|
+
}
|
|
449
|
+
catch (error) {
|
|
450
|
+
if (error.code !== "EEXIST")
|
|
451
|
+
throw error;
|
|
452
|
+
}
|
|
453
|
+
if ((await lstat(join(dir, candidate))).isDirectory())
|
|
454
|
+
return candidate;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/** A copy of `source` in `dir` as `name`, or the first suffixed name nothing holds. Created exclusive, so it is a new
|
|
458
|
+
* file and never what a name already pointed at. */
|
|
459
|
+
async function copyIn(dir, name, source) {
|
|
460
|
+
for (let n = 1;; n++) {
|
|
461
|
+
const candidate = suffixed(name, n);
|
|
462
|
+
let handle;
|
|
463
|
+
try {
|
|
464
|
+
handle = await open(join(dir, candidate), "wx");
|
|
465
|
+
}
|
|
466
|
+
catch (error) {
|
|
467
|
+
if (error.code === "EEXIST")
|
|
468
|
+
continue;
|
|
469
|
+
throw error;
|
|
470
|
+
}
|
|
471
|
+
await pipeline(createReadStream(source), handle.createWriteStream());
|
|
472
|
+
return candidate;
|
|
473
|
+
}
|
|
474
|
+
}
|
package/dist/usage.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type Learning, type LearningReason, type Tokens } from "./learning.js";
|
|
2
|
+
/** On a line written since they were kept (learning.ts Learning): `seed_notes`, how many notes the run started from;
|
|
3
|
+
* `answered_at` and `job_cost_usd`, when its job's answer was final and what it had cost then, once it looked back;
|
|
4
|
+
* `look_back_usd`, what looking back cost (0 when it did not; null when unknown). */
|
|
5
|
+
export type Outcome = {
|
|
6
|
+
run: string;
|
|
7
|
+
agent: string;
|
|
8
|
+
state: "merged" | "dropped";
|
|
9
|
+
reason: LearningReason | null;
|
|
10
|
+
at: string;
|
|
11
|
+
cost: number | null;
|
|
12
|
+
tokens: Tokens | null;
|
|
13
|
+
seed_notes?: number;
|
|
14
|
+
answered_at?: string;
|
|
15
|
+
job_cost_usd?: number | null;
|
|
16
|
+
look_back_usd?: number | null;
|
|
17
|
+
};
|
|
18
|
+
type Ended = Learning & {
|
|
19
|
+
state: "merged" | "dropped";
|
|
20
|
+
};
|
|
21
|
+
/** Whether a run's learning has ended: merged or dropped, which never moves again. */
|
|
22
|
+
export declare const ended: (learning: Learning | undefined | null) => learning is Ended;
|
|
23
|
+
/** The line of run `run` of agent `agent`, whose learning ended as `learning` says. */
|
|
24
|
+
export declare const outcomeOf: (run: string, agent: string, learning: Ended) => Outcome;
|
|
25
|
+
/** Every run's line, by run (its first): a line cut short by a crash, or out of shape, is skipped. */
|
|
26
|
+
export declare function outcomes(data: string): Promise<Map<string, Outcome>>;
|
|
27
|
+
/** Writes one run's line. A line starts on a line of its own, so one a crash cut short spoils nothing after it. */
|
|
28
|
+
export declare const record: (data: string, outcome: Outcome) => Promise<void>;
|
|
29
|
+
export {};
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// The learning ledger, `<data>/learning-usage.jsonl`: one line per run whose learning ended (merged or dropped), written
|
|
2
|
+
// once its serve.json holds that end. GET /v2/stats counts from it how the runs that tried to learn fared, and GET
|
|
3
|
+
// /usage's `learning` meter reads from it what learning spent outside any run, so neither opens a run's files. A line
|
|
4
|
+
// holds the run, its agent, how its learning ended and when, how many notes it started from, when its answer was final
|
|
5
|
+
// and what its job and its look-back cost (GET /v2/agents/{id}/learning's `impact` reads these), and what its grade
|
|
6
|
+
// spent on the host after the run (the
|
|
7
|
+
// grader on the agent's model, and the injection screen when Jev is its judge), which is in no run's journal and no
|
|
8
|
+
// run's total: `cost` in dollars and `tokens`, each null when unknown, never 0, and 0 when nothing was graded. A run's
|
|
9
|
+
// learning ends once and never moves again, so a line is read once per run: one written again (a restart that found
|
|
10
|
+
// its run's end saved and its line maybe missing) is not counted twice.
|
|
11
|
+
import { appendFile, readFile } from "node:fs/promises";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { LEARNING_REASONS, NO_TOKENS } from "./learning.js";
|
|
14
|
+
import { isObject } from "./validate.js";
|
|
15
|
+
const ledger = (data) => join(data, "learning-usage.jsonl");
|
|
16
|
+
/** Whether a run's learning has ended: merged or dropped, which never moves again. */
|
|
17
|
+
export const ended = (learning) => learning?.state === "merged" || learning?.state === "dropped";
|
|
18
|
+
/** The line of run `run` of agent `agent`, whose learning ended as `learning` says. */
|
|
19
|
+
export const outcomeOf = (run, agent, learning) => ({
|
|
20
|
+
run, agent, state: learning.state, reason: learning.reason, at: learning.at,
|
|
21
|
+
...(learning.cost_usd ? { cost: learning.cost_usd.grade, tokens: learning.tokens?.grade ?? null } : { cost: 0, tokens: { ...NO_TOKENS } }),
|
|
22
|
+
...(isCount(learning.seed_notes) ? { seed_notes: learning.seed_notes } : {}),
|
|
23
|
+
...(learning.answered_at === undefined ? { look_back_usd: 0 } : { answered_at: learning.answered_at, job_cost_usd: learning.job_cost_usd ?? null, look_back_usd: learning.look_back_usd ?? null }),
|
|
24
|
+
});
|
|
25
|
+
const isUsd = (value) => value === null || (typeof value === "number" && Number.isFinite(value) && value >= 0);
|
|
26
|
+
const isCount = (value) => Number.isSafeInteger(value) && value >= 0;
|
|
27
|
+
/** Every run's line, by run (its first): a line cut short by a crash, or out of shape, is skipped. */
|
|
28
|
+
export async function outcomes(data) {
|
|
29
|
+
const text = await readFile(ledger(data), "utf8").catch((error) => (error.code === "ENOENT" ? "" : Promise.reject(error)));
|
|
30
|
+
const out = new Map();
|
|
31
|
+
for (const line of text.split("\n")) {
|
|
32
|
+
let entry;
|
|
33
|
+
try {
|
|
34
|
+
entry = JSON.parse(line);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (!isObject(entry) || typeof entry.run !== "string" || typeof entry.agent !== "string" || typeof entry.at !== "string")
|
|
40
|
+
continue;
|
|
41
|
+
if ((entry.state !== "merged" && entry.state !== "dropped") || !(entry.reason === null || LEARNING_REASONS.includes(entry.reason)))
|
|
42
|
+
continue;
|
|
43
|
+
if (!(entry.cost === null || typeof entry.cost === "number"))
|
|
44
|
+
continue;
|
|
45
|
+
if (entry.seed_notes !== undefined && !isCount(entry.seed_notes))
|
|
46
|
+
delete entry.seed_notes;
|
|
47
|
+
if (entry.answered_at !== undefined && (typeof entry.answered_at !== "string" || !Date.parse(entry.answered_at)))
|
|
48
|
+
delete entry.answered_at;
|
|
49
|
+
for (const key of ["job_cost_usd", "look_back_usd"])
|
|
50
|
+
if (entry[key] !== undefined && !isUsd(entry[key]))
|
|
51
|
+
delete entry[key];
|
|
52
|
+
if (!out.has(entry.run))
|
|
53
|
+
out.set(entry.run, entry);
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
/** Writes one run's line. A line starts on a line of its own, so one a crash cut short spoils nothing after it. */
|
|
58
|
+
export const record = (data, outcome) => appendFile(ledger(data), `\n${JSON.stringify(outcome)}\n`, { mode: 0o600 });
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type InputIssue } from "./errors.js";
|
|
2
|
+
export declare const ID: RegExp;
|
|
3
|
+
export type Json = Record<string, unknown>;
|
|
4
|
+
export declare const isObject: (value: unknown) => value is Json;
|
|
5
|
+
/** JSON with every object's keys sorted, so two equal values read the same. */
|
|
6
|
+
export declare const stable: (value: unknown) => string;
|
|
7
|
+
export declare const DEFINITION_FIELDS: string[];
|
|
8
|
+
/** Why a field a definition may have elsewhere has no place in an agent store's revision. */
|
|
9
|
+
export declare const NOT_KEPT: Record<string, string>;
|
|
10
|
+
/** `provider/model-id`. */
|
|
11
|
+
export declare const MODEL_REF: RegExp;
|
|
12
|
+
/** A body's fields that `allowed` does not name, each as the 422's not_allowed issue. */
|
|
13
|
+
export declare const unknownFields: (body: object, allowed: readonly string[]) => InputIssue[];
|
|
14
|
+
/** The skills a revision's files hold: each `<name>/SKILL.md`, by name, sorted. */
|
|
15
|
+
export declare const skillNames: (files: Iterable<string>) => string[];
|
|
16
|
+
/**
|
|
17
|
+
* A definition as `POST /agents` and `PUT .../definition` take it: what one revision of an agent keeps. `instructions`
|
|
18
|
+
* makes an agentic revision, `workflow` (an agentrun-dsl workflow) a workflow revision. `creating` asks for a name.
|
|
19
|
+
*/
|
|
20
|
+
export declare function definitionIssues(definition: unknown, { at, creating }?: {
|
|
21
|
+
at?: string | undefined;
|
|
22
|
+
creating?: boolean | undefined;
|
|
23
|
+
}): InputIssue[];
|
|
24
|
+
/** A definition's skill names against the files its revision holds: each named skill has its SKILL.md, and each
|
|
25
|
+
* SKILL.md is named. */
|
|
26
|
+
export declare function skillIssues(named: unknown, files: Iterable<string>): InputIssue[];
|
|
27
|
+
export type DefinitionBody = {
|
|
28
|
+
definition: Json;
|
|
29
|
+
skills?: Record<string, string>;
|
|
30
|
+
note?: string;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* `{definition, skills?, note?}`, as `POST /agents` and `PUT .../definition` take it. `skills` are the revision's skill
|
|
34
|
+
* files (absent on an edit: the current revision's); `note` says what the revision changes. Throws `422 input_invalid`
|
|
35
|
+
* naming every field that is wrong.
|
|
36
|
+
*/
|
|
37
|
+
export declare function checkDefinitionBody(body: Json, { creating }?: {
|
|
38
|
+
creating?: boolean | undefined;
|
|
39
|
+
}): DefinitionBody;
|
|
40
|
+
/** The default input schema: `{content: string}`. */
|
|
41
|
+
export declare const DEFAULT_INPUT_SCHEMA: {
|
|
42
|
+
type: string;
|
|
43
|
+
required: string[];
|
|
44
|
+
properties: {
|
|
45
|
+
content: {
|
|
46
|
+
type: string;
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* An object against a JSON Schema at its top level (a run's input against `input_schema`, a submitted output against
|
|
52
|
+
* `output_schema`): each required property present, each property of a declared type of that type. Deeper keywords
|
|
53
|
+
* are not checked here.
|
|
54
|
+
*/
|
|
55
|
+
export declare function inputIssues(input: Json, schema: Json, at?: string): InputIssue[];
|