@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +748 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +2190 -2
- package/dist/adapters.d.ts +234 -0
- package/dist/adapters.js +585 -0
- package/dist/agents.d.ts +130 -0
- package/dist/agents.js +308 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +384 -0
- package/dist/background.d.ts +28 -0
- package/dist/background.js +376 -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-egress.d.ts +98 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +285 -0
- package/dist/box-relay-vm.d.ts +80 -0
- package/dist/box-relay-vm.js +389 -0
- package/dist/box-relay.d.ts +45 -0
- package/dist/box-relay.js +227 -0
- package/dist/boxes.d.ts +72 -0
- package/dist/boxes.js +189 -0
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +332 -0
- package/dist/cap.js +992 -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 +35 -0
- package/dist/coding-tools.js +87 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
- package/dist/console/assets/index-34jfpIbQ.js +481 -0
- package/dist/console/assets/index-DUHbWcIP.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/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +19 -0
- package/dist/decision-rows.js +123 -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 +74 -0
- package/dist/errors.js +69 -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 +65 -0
- package/dist/files.js +158 -0
- package/dist/grade.d.ts +93 -0
- package/dist/grade.js +328 -0
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +102 -0
- package/dist/graph-view.js +219 -0
- package/dist/harness-app.d.ts +40 -0
- package/dist/harness-app.js +708 -0
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +56 -0
- package/dist/harness.js +77 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +30 -0
- package/dist/host-tools.js +154 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +85 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +133 -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 +1222 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +37 -0
- package/dist/key-check.js +112 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +191 -0
- package/dist/learn/check.d.ts +108 -0
- package/dist/learn/check.js +277 -0
- package/dist/learn/grade.d.ts +80 -0
- package/dist/learn/grade.js +445 -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 +147 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +213 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +131 -0
- package/dist/learn/skills.d.ts +97 -0
- package/dist/learn/skills.js +271 -0
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +306 -0
- package/dist/learning-run.js +819 -0
- package/dist/learning-words.d.ts +76 -0
- package/dist/learning-words.js +174 -0
- package/dist/learning.d.ts +418 -0
- package/dist/learning.js +946 -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 +118 -0
- package/dist/mcp-servers.js +450 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +186 -0
- package/dist/model.js +485 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4806 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1727 -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 +50 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +70 -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 +69 -0
- package/dist/place.js +137 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +40 -0
- package/dist/propose.js +112 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +22 -0
- package/dist/request-start.js +350 -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 +186 -0
- package/dist/run-box.js +590 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +83 -0
- package/dist/runnable.js +170 -0
- package/dist/runs.d.ts +1062 -0
- package/dist/runs.js +3020 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +62 -0
- package/dist/secrets.js +158 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +722 -0
- package/dist/server.js +2118 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +43 -0
- package/dist/skills.js +96 -0
- package/dist/stats.d.ts +106 -0
- package/dist/stats.js +103 -0
- package/dist/tool-gate.d.ts +266 -0
- package/dist/tool-gate.js +554 -0
- package/dist/tool-keys.d.ts +187 -0
- package/dist/tool-keys.js +315 -0
- package/dist/tool-plane.d.ts +228 -0
- package/dist/tool-plane.js +400 -0
- package/dist/tools.d.ts +202 -0
- package/dist/tools.js +372 -0
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +24 -0
- package/dist/turn-end.js +15 -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-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +57 -0
- package/dist/validate.js +184 -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 +189 -0
- package/dist/webhooks.js +503 -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 +100 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
package/dist/files.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// The small JSON files the server reads and writes beside the agent store.
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { closeSync, constants, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
|
4
|
+
import { open, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
/** The server's own file in each run's directory: the run's title, input and how it was asked to run. */
|
|
8
|
+
export const RUN_META = "serve.json";
|
|
9
|
+
/** A cancelled run's mark in its directory, written before its process is told: the run's process sends no model
|
|
10
|
+
* request once it is there, however the cancel and the process's start interleave. */
|
|
11
|
+
export const RUN_CANCELLED = "cancelled";
|
|
12
|
+
/** A run's launch mark in its directory, written before its process is spawned and removed once that process serves
|
|
13
|
+
* or exits: found at a start, the server went down while it launched the run. */
|
|
14
|
+
export const RUN_LAUNCHING = "launching";
|
|
15
|
+
/** Set in a run's process environment when the server opens the run for a person's follow-up to a run whose turn had
|
|
16
|
+
* ended (it answered, or the person stopped it): that open resumes no cut work, so it writes no "resumed" row (app.ts). */
|
|
17
|
+
export const FOLLOW_UP_OPEN_ENV = "AGENTRUN_FOLLOW_UP_OPEN";
|
|
18
|
+
/** The server's API token (`ar_local_...`), in the data directory, made at its first start when it is given none. */
|
|
19
|
+
export const TOKEN_FILE = ".token";
|
|
20
|
+
/** The server-wide door token, in the data directory: the door of a run an older server started takes it. */
|
|
21
|
+
export const DOOR_TOKEN_FILE = ".door-token";
|
|
22
|
+
/** A run's own door token, in its directory, made at its first launch and handed to its process alone (its
|
|
23
|
+
* `--serve-token-file`): the server's calls to that run's door carry it, and so do that run's calls to the box relay
|
|
24
|
+
* (box-relay.ts), which takes a call for a run only with that run's token. */
|
|
25
|
+
export const RUN_DOOR_TOKEN = "door-token";
|
|
26
|
+
/** Run directory `dir`'s own door token (RUN_DOOR_TOKEN), when it has one. */
|
|
27
|
+
export function runDoorToken(dir) {
|
|
28
|
+
try {
|
|
29
|
+
const token = readFileSync(join(dir, RUN_DOOR_TOKEN), "utf8").trim();
|
|
30
|
+
return token && !/\s/.test(token) ? token : undefined;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Why a run fails whose launch mark a start finds (`error.details.reason`, openapi.ts). */
|
|
37
|
+
export const LAUNCH_LOST = "server_lost_at_launch";
|
|
38
|
+
/** Why a run fails that the store has running with no serve.json: its server went down before it set the run up. */
|
|
39
|
+
export const SETUP_LOST = "server_lost_at_setup";
|
|
40
|
+
/** The server's data directory when none is given (`--data`): `agentrun/agents` under XDG_DATA_HOME, or ~/.local/share.
|
|
41
|
+
* The server, its import and reset-password default to it. `npx @parcha/agentrun` keeps its own, ~/.agentrun, and
|
|
42
|
+
* passes it as --data. */
|
|
43
|
+
export const defaultData = (env = process.env) => join(env.XDG_DATA_HOME || join(env.HOME || homedir(), ".local", "share"), "agentrun", "agents");
|
|
44
|
+
/** The server's own data directory, on its reading of the environment (startServe): an npx hint names it (adapters.ts
|
|
45
|
+
* npxLine). */
|
|
46
|
+
export const DATA_ENV = "AGENTRUN_SERVE_DATA";
|
|
47
|
+
export const HOMES_DIR = "homes";
|
|
48
|
+
/** Paths in an agent's home that only the host reads and writes (another component owns them): the home API reads and
|
|
49
|
+
* writes neither, and lists each by its name alone. `learning` (learning.ts, read through its own API) and `sign-ins`
|
|
50
|
+
* (sign-ins.ts: the agent's saved sign-ins, sealed pointers to its browser vendor's objects, shown without them on
|
|
51
|
+
* GET /agents/{id}). */
|
|
52
|
+
export const HOME_HOST_OWNED = ["learning", "sign-ins"];
|
|
53
|
+
/** An agent's home directory's name: its id in lower case, then 16 hex digits of the id's SHA-256. Ids that differ only
|
|
54
|
+
* in case get names that differ in any case, so on a disk that folds case (macOS's, by default) they never share one. */
|
|
55
|
+
export const homeKey = (agentId) => `${agentId.toLowerCase()}-${createHash("sha256").update(agentId, "utf8").digest("hex").slice(0, 16)}`;
|
|
56
|
+
export const homeOf = (data, agentId) => join(data, HOMES_DIR, homeKey(agentId));
|
|
57
|
+
/** The file parsed as JSON, or null when it is missing, unreadable, or not whole JSON (a half-written file). */
|
|
58
|
+
export const readJson = (path) => readFile(path, "utf8")
|
|
59
|
+
.then((text) => JSON.parse(text))
|
|
60
|
+
.catch(() => null);
|
|
61
|
+
/** A temporary file beside `path`, this write's own: two writes of one file at once never share one, so neither renames
|
|
62
|
+
* the other's away nor writes into the file the other renamed. */
|
|
63
|
+
export const tempOf = (path) => `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
64
|
+
/** Writes `text` to `path` whole: through a temporary file and a rename, so a reader never sees half of it. */
|
|
65
|
+
export async function writeWhole(path, text, mode = 0o600) {
|
|
66
|
+
const temp = `${path}.tmp`;
|
|
67
|
+
await writeFile(temp, text, { mode });
|
|
68
|
+
await rename(temp, path);
|
|
69
|
+
}
|
|
70
|
+
/** Syncs the directory `path`, so the entries made in it survive a crash of the machine. */
|
|
71
|
+
export async function syncDir(path) {
|
|
72
|
+
const dir = await open(path, constants.O_RDONLY | constants.O_DIRECTORY);
|
|
73
|
+
try {
|
|
74
|
+
await dir.sync();
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
await dir.close();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Writes `text` (or bytes) to `path` whole and durably: the temporary file is synced before the rename, and the
|
|
81
|
+
* directory after it, so once this resolves a crash, even of the machine, leaves the new text in place, never the old or
|
|
82
|
+
* none. `temp` is the temporary file, created only if nothing is there yet: a link planted at it is never written through.
|
|
83
|
+
* Answers the stats of the file it wrote, read before the rename: a write of `path` that lands after it is not them.
|
|
84
|
+
* `exact`: the file gets `mode` itself, whatever this process's umask takes away (set on its handle, never by path). */
|
|
85
|
+
export async function writeDurable(path, text, mode = 0o600, temp = tempOf(path), exact = false) {
|
|
86
|
+
// Its own temporary file: a box's record can be let go by two settlements at once (a run's archive and its agent's).
|
|
87
|
+
const bytes = typeof text === "string" ? Buffer.from(text) : text;
|
|
88
|
+
const file = await open(temp, "wx", mode);
|
|
89
|
+
let stats;
|
|
90
|
+
try {
|
|
91
|
+
if (exact)
|
|
92
|
+
await file.chmod(mode);
|
|
93
|
+
// Every byte, or an error: a short write (a disk nearly full) is never synced and renamed as if whole.
|
|
94
|
+
for (let at = 0; at < bytes.length;) {
|
|
95
|
+
const { bytesWritten } = await file.write(bytes, at, bytes.length - at);
|
|
96
|
+
if (bytesWritten <= 0)
|
|
97
|
+
throw new Error(`${temp}: wrote ${at} of ${bytes.length} bytes`);
|
|
98
|
+
at += bytesWritten;
|
|
99
|
+
}
|
|
100
|
+
await file.sync();
|
|
101
|
+
stats = await file.stat();
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
await file.close();
|
|
105
|
+
await unlink(temp).catch(() => { });
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
await file.close();
|
|
109
|
+
await rename(temp, path).catch(async (error) => {
|
|
110
|
+
await unlink(temp).catch(() => { });
|
|
111
|
+
throw error;
|
|
112
|
+
});
|
|
113
|
+
await syncDir(dirname(path));
|
|
114
|
+
return stats;
|
|
115
|
+
}
|
|
116
|
+
/** writeDurable, synchronously: on disk, the file and then its directory synced, when it returns. For a record that
|
|
117
|
+
* must be durable before the next line runs, with nothing between them that could let anything else happen first. */
|
|
118
|
+
export function writeDurableSync(path, text, mode = 0o600) {
|
|
119
|
+
const temp = `${path}.tmp`;
|
|
120
|
+
const bytes = Buffer.from(text);
|
|
121
|
+
const file = openSync(temp, "w", mode);
|
|
122
|
+
try {
|
|
123
|
+
// Every byte, or an error: a short write (a disk nearly full) is never synced and renamed as if whole.
|
|
124
|
+
for (let at = 0; at < bytes.length;) {
|
|
125
|
+
const written = writeSync(file, bytes, at, bytes.length - at);
|
|
126
|
+
if (written <= 0)
|
|
127
|
+
throw new Error(`${temp}: wrote ${at} of ${bytes.length} bytes`);
|
|
128
|
+
at += written;
|
|
129
|
+
}
|
|
130
|
+
fsyncSync(file);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
closeSync(file);
|
|
134
|
+
try {
|
|
135
|
+
unlinkSync(temp);
|
|
136
|
+
}
|
|
137
|
+
catch { }
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
closeSync(file);
|
|
141
|
+
renameSync(temp, path);
|
|
142
|
+
const dir = openSync(dirname(path), "r");
|
|
143
|
+
try {
|
|
144
|
+
fsyncSync(dir);
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
closeSync(dir);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** Runs `work` once every call queued before it under `key` in `queues` has settled: one at a time per key. The queue
|
|
151
|
+
* holds only settled turns, so one that failed never fails the next, and a key is dropped once its last turn settles. */
|
|
152
|
+
export function serialBy(queues, key, work) {
|
|
153
|
+
const turn = (queues.get(key) ?? Promise.resolve()).then(work);
|
|
154
|
+
const settled = turn.then(() => undefined, () => undefined);
|
|
155
|
+
queues.set(key, settled);
|
|
156
|
+
void settled.then(() => queues.get(key) === settled && queues.delete(key));
|
|
157
|
+
return turn;
|
|
158
|
+
}
|
package/dist/grade.d.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { type IndexEntry, type NoteText, type Problem, type Verdict } from "./learn/index.js";
|
|
2
|
+
import { claudeProvider } from "./adapters.js";
|
|
3
|
+
import { type Proposal, type Tokens } from "./learning.js";
|
|
4
|
+
/** Main as a grade reads it: its commit, every entry at its top, its notes' texts by file (any status), and each
|
|
5
|
+
* entry's object id. */
|
|
6
|
+
export type Main = {
|
|
7
|
+
sha: string;
|
|
8
|
+
files: string[];
|
|
9
|
+
texts: Map<string, string>;
|
|
10
|
+
oids: Map<string, string>;
|
|
11
|
+
};
|
|
12
|
+
/** What a grade spent: the grader's calls. The dollars, null when any call's are unknown, and the tokens,
|
|
13
|
+
* null when any call's are. */
|
|
14
|
+
export type GradeCost = {
|
|
15
|
+
usd: number | null;
|
|
16
|
+
tokens: Tokens | null;
|
|
17
|
+
};
|
|
18
|
+
export type Judged = {
|
|
19
|
+
cost: GradeCost;
|
|
20
|
+
} & ({
|
|
21
|
+
verdict: Verdict;
|
|
22
|
+
} | {
|
|
23
|
+
reason: "grade_failed";
|
|
24
|
+
error: Error;
|
|
25
|
+
});
|
|
26
|
+
/** The agentic revision the run ran: its standing instructions, and what its model is. */
|
|
27
|
+
export type Agent = {
|
|
28
|
+
instructions: string;
|
|
29
|
+
harness?: string;
|
|
30
|
+
model?: string;
|
|
31
|
+
thinking?: string;
|
|
32
|
+
};
|
|
33
|
+
/** What a grade reads of main: each active note as the index lists it, the whole text of the ones the proposal
|
|
34
|
+
* supersedes, and the blob each of those was on main then (`graded`, by file), which its merge checks. */
|
|
35
|
+
export type GradeMain = {
|
|
36
|
+
active: IndexEntry[];
|
|
37
|
+
superseded: NoteText[];
|
|
38
|
+
graded: Record<string, string>;
|
|
39
|
+
};
|
|
40
|
+
/** Main now, for run `runId`'s grade, in the agent's queue: merged already (a commit names the run), what stops its
|
|
41
|
+
* proposal joining main as it is now, or its active notes' index lines and the notes the proposal supersedes in full. */
|
|
42
|
+
export declare function readForGrade(data: string, agentId: string, runId: string, proposal: Proposal): Promise<{
|
|
43
|
+
merged: string;
|
|
44
|
+
} | {
|
|
45
|
+
problems: Problem[];
|
|
46
|
+
} | GradeMain>;
|
|
47
|
+
/** claude-agent's provider, as claudeProvider returns it. Without `auth`, it takes x-api-key, as the adapter does. */
|
|
48
|
+
export type RunProvider = ReturnType<typeof claudeProvider> & {
|
|
49
|
+
auth?: "x-api-key" | "bearer";
|
|
50
|
+
};
|
|
51
|
+
/** pi-ai's auth context for a grade on `provider`, the run's: its credential under the one variable pi-ai reads for its
|
|
52
|
+
* auth mode, and no other variable of serve's env. */
|
|
53
|
+
export declare function graderAuth(provider: RunProvider): {
|
|
54
|
+
env: (asked: string) => Promise<string | undefined>;
|
|
55
|
+
fileExists: () => Promise<boolean>;
|
|
56
|
+
};
|
|
57
|
+
/** The grader, on `gradeModel` when the server names one (gradeModelOf), given `asked`, what the user said in the run:
|
|
58
|
+
* its verdict, or why it gave none; with what it spent. Rejects only when `signal` (the server closing) aborts it: nothing
|
|
59
|
+
* is decided then. */
|
|
60
|
+
export declare function judgeProposal(input: {
|
|
61
|
+
runId: string;
|
|
62
|
+
agent: Agent;
|
|
63
|
+
main: GradeMain;
|
|
64
|
+
proposed: NoteText[];
|
|
65
|
+
files?: NoteText[];
|
|
66
|
+
asked?: readonly string[];
|
|
67
|
+
gradeModel?: string;
|
|
68
|
+
env: NodeJS.ProcessEnv;
|
|
69
|
+
signal: AbortSignal;
|
|
70
|
+
gradeTimeoutMs?: number;
|
|
71
|
+
}): Promise<Judged>;
|
|
72
|
+
/** `proposal` with only what `verdict` keeps (a verdict per item): each note, skill and draft (both its files) its item
|
|
73
|
+
* keeps or holds; the ones it drops are left out. A proposal with no verdict (a merge resumed on one kept before the
|
|
74
|
+
* grade read items) is as it is. */
|
|
75
|
+
export declare function keptProposal(proposal: Proposal, verdict?: Verdict): Proposal;
|
|
76
|
+
export declare function heldFiles(files: readonly NoteText[], verdict?: Verdict): NoteText[];
|
|
77
|
+
/** Merges run `runId`'s proposal into main as main is now, in the agent's queue, as `verdict` judged its notes: one commit
|
|
78
|
+
* on main (its parent main) that adds the new notes, each with its `origin` and a pending one with `status: pending`
|
|
79
|
+
* (in no index, so no run reads it, until a person approves it), marks each note a kept one supersedes (a pending
|
|
80
|
+
* note's wait for its approval), adds or changes the skill's and draft's files (heldFiles: a held one pending) and
|
|
81
|
+
* rebuilds MEMORY.md, its message `learning: <run>: merged`,
|
|
82
|
+
* `reason` and the run's Run-Id; moved onto main only from the commit it was made on, once more on a main that moved
|
|
83
|
+
* meanwhile. Then the checked-out files are main's. A run a commit on main already names is that commit. `problems`
|
|
84
|
+
* when main, as it is now, takes the notes no more (mergeProblems), or when a note the merge marks superseded is not
|
|
85
|
+
* the blob the grade read (`graded`, readForGrade's): a person changed it since, and their text stands. A note held for
|
|
86
|
+
* its owner's OK marks nothing (supersededBy), so what it names is not checked. `checkout` is why the files could not
|
|
87
|
+
* be brought in line, when they could not: main is merged all the same. */
|
|
88
|
+
export declare function mergeProposal(data: string, agentId: string, runId: string, proposal: Proposal, reason: string, graded: Readonly<Record<string, string>>, verdict?: Verdict): Promise<{
|
|
89
|
+
merged: string;
|
|
90
|
+
checkout: Error | undefined;
|
|
91
|
+
} | {
|
|
92
|
+
problems: Problem[];
|
|
93
|
+
}>;
|
package/dist/grade.js
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
// Learning, its grade and its merge: once a run's proposal passed the checks (propose.ts), one grader decides whether its
|
|
2
|
+
// new notes, and its skill and workflow draft, join the agent's main, and the host merges them.
|
|
3
|
+
// - The grader is learn/grade.ts' gradePrompt, asked as one bounded completion against main as it is now: each active
|
|
4
|
+
// note's index line, the whole text only of the notes the proposal supersedes, and what the user said in the run, so
|
|
5
|
+
// the prompt is bounded whatever the folder holds (GRADE_CAPS). It runs on the model the server names for grading
|
|
6
|
+
// (learning.ts gradeModelOf: `--grade-model`, else its strong tier), else on the agent's own. Its answer is read by parseVerdict,
|
|
7
|
+
// which fails closed. A
|
|
8
|
+
// call cut off at its bound spent what nobody knows: the grade's cost is then unknown, never $0. No injection screen
|
|
9
|
+
// runs before it: a page classifier cannot see where a note came from, and dropped a preference the user stated (it
|
|
10
|
+
// reads like an instruction); the grader's Planted question decides, with what the user said in view.
|
|
11
|
+
// - The merge is one host commit on main, made with plumbing on a temporary index: the new notes added, each note one of
|
|
12
|
+
// them supersedes marked, the skill's and draft's files added or changed (one the grader held, marked pending), and
|
|
13
|
+
// MEMORY.md rebuilt (buildIndex). Its message is `learning: <run id>: merged`, the verdict's
|
|
14
|
+
// reason and a `Run-Id` trailer, and main moves only from the commit it was made on (compare and swap), once more on a
|
|
15
|
+
// main that moved meanwhile. A run a commit on main already names is merged, never twice. The merge's own questions
|
|
16
|
+
// (learn/check.ts mergeProblems) are asked again of main as it is then, and each note superseded must still be the
|
|
17
|
+
// blob the grade read: one a person changed since is theirs, and nothing merges. The checked-out files are brought in
|
|
18
|
+
// line.
|
|
19
|
+
// The merge runs in the agent's queue; the grader never does, so no run's seed waits on a model.
|
|
20
|
+
import { rm } from "node:fs/promises";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
import { buildIndex, gradedItems, held, INDEX_FILE, learnedPlace, mergedNote, mergeProblems, parseNoteFile, supersede, supersededBy } from "./learn/index.js";
|
|
23
|
+
import { claudeModel, claudeProvider, codexModel, codexProvider } from "./adapters.js";
|
|
24
|
+
import { homeOf } from "./files.js";
|
|
25
|
+
import { FAUX_HARNESS_ENV } from "./harness.js";
|
|
26
|
+
import { agentFolder, checkOut, git, line, mainOf, NO_TOKENS, readBlobs, withAgentRepo } from "./learning.js";
|
|
27
|
+
import { completer } from "./llm.js";
|
|
28
|
+
import { openRouterOnly, runModels, thinkingOf } from "./model.js";
|
|
29
|
+
/** How long the grader may take (unless the server names another), and the most it may write. */
|
|
30
|
+
const GRADE_TIMEOUT_MS = 180_000;
|
|
31
|
+
const GRADE_MAX_TOKENS = 16_000;
|
|
32
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
33
|
+
/** The newest commit on main whose Run-Id trailer names the run, as git reads trailers. */
|
|
34
|
+
async function mergeOf(home, repo, main, runId) {
|
|
35
|
+
const out = (await git(home, repo, ["log", "--first-parent", "--format=%H %(trailers:key=Run-Id,valueonly,separator=%x2C)", main])).toString("utf8");
|
|
36
|
+
return out.split("\n").find((entry) => entry.slice(entry.indexOf(" ") + 1).split(",").includes(runId))?.split(" ")[0];
|
|
37
|
+
}
|
|
38
|
+
/** Main's top: every entry, and the text of each `.md` blob, read with plumbing. A blob that is not UTF-8 is left out. */
|
|
39
|
+
async function readMain(home, repo, sha) {
|
|
40
|
+
const listed = (await git(home, repo, ["ls-tree", "-z", sha])).toString("utf8").split("\0").filter(Boolean).map((entry) => {
|
|
41
|
+
const [mode, type, oid] = entry.slice(0, entry.indexOf("\t")).split(" ");
|
|
42
|
+
return { mode, type, oid: oid, path: entry.slice(entry.indexOf("\t") + 1) };
|
|
43
|
+
});
|
|
44
|
+
const blobs = listed.filter((entry) => entry.type === "blob" && entry.mode === "100644" && entry.path.endsWith(".md"));
|
|
45
|
+
const read = await readBlobs(home, repo, blobs.map((entry) => entry.oid));
|
|
46
|
+
const texts = new Map();
|
|
47
|
+
blobs.forEach((entry, i) => {
|
|
48
|
+
try {
|
|
49
|
+
texts.set(entry.path, utf8.decode(read[i]));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// Not UTF-8: no note of the folder's, and never read as one.
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
return { sha, files: listed.map((entry) => entry.path), texts, oids: new Map(listed.map((entry) => [entry.path, entry.oid])) };
|
|
56
|
+
}
|
|
57
|
+
/** Main's notes, parsed: the ones out of shape left out, as a run's seed leaves them. */
|
|
58
|
+
const notesOf = (main) => [...main.texts].flatMap(([file, text]) => {
|
|
59
|
+
const note = file === INDEX_FILE ? [] : parseNoteFile(file, text);
|
|
60
|
+
return Array.isArray(note) ? [] : [note];
|
|
61
|
+
});
|
|
62
|
+
/** The proposal's notes, parsed: each passed the checks, so one that does not parse is an error. */
|
|
63
|
+
const proposedOf = (proposal) => proposal.notes.map(({ file, text }) => {
|
|
64
|
+
const note = parseNoteFile(file, text);
|
|
65
|
+
if (Array.isArray(note))
|
|
66
|
+
throw new Error(`the proposal's ${file} is not a note`);
|
|
67
|
+
return note;
|
|
68
|
+
});
|
|
69
|
+
/** What stops the proposal joining `main` as it is now (learn/check.ts mergeProblems). */
|
|
70
|
+
const problemsOf = (main, notes) => mergeProblems({ files: main.files, active: notesOf(main).filter((note) => note.status === "active") }, notes);
|
|
71
|
+
/** Main now, for run `runId`'s grade, in the agent's queue: merged already (a commit names the run), what stops its
|
|
72
|
+
* proposal joining main as it is now, or its active notes' index lines and the notes the proposal supersedes in full. */
|
|
73
|
+
export function readForGrade(data, agentId, runId, proposal) {
|
|
74
|
+
const home = homeOf(data, agentId);
|
|
75
|
+
return withAgentRepo(data, agentId, async () => {
|
|
76
|
+
const repo = await agentFolder(data, agentId);
|
|
77
|
+
const sha = (await mainOf(home, repo));
|
|
78
|
+
const merged = await mergeOf(home, repo, sha, runId);
|
|
79
|
+
if (merged)
|
|
80
|
+
return { merged };
|
|
81
|
+
const main = await readMain(home, repo, sha);
|
|
82
|
+
const added = proposedOf(proposal);
|
|
83
|
+
const problems = problemsOf(main, added);
|
|
84
|
+
if (problems.length)
|
|
85
|
+
return { problems };
|
|
86
|
+
const active = notesOf(main).filter((note) => note.status === "active").map(({ file, name, description }) => ({ file, name, description }));
|
|
87
|
+
// mergeProblems passed: each note superseded is active on main, and named once.
|
|
88
|
+
const superseded = added.flatMap((note) => note.supersedes).map((file) => ({ file, text: main.texts.get(file) }));
|
|
89
|
+
return { active, superseded, graded: Object.fromEntries(superseded.map(({ file }) => [file, main.oids.get(file)])) };
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
/** Counts one call in `cost`: its dollars and tokens, each null when unknown (a call that failed, or reported none). */
|
|
93
|
+
const counter = (cost) => (usd, tokens) => {
|
|
94
|
+
cost.usd = usd !== null && Number.isFinite(usd) && cost.usd !== null ? cost.usd + usd : null;
|
|
95
|
+
cost.tokens = tokens && cost.tokens ? { input: cost.tokens.input + tokens.input, cache_read: cost.tokens.cache_read + tokens.cache_read, cache_write: cost.tokens.cache_write + tokens.cache_write, output: cost.tokens.output + tokens.output } : null;
|
|
96
|
+
};
|
|
97
|
+
/** `work`, given a signal that aborts at `ms` or with `outer`, and rejected then whether or not it listens. A call cut
|
|
98
|
+
* off so, before it settled, spent what nobody knows: `cost` turns unknown (null dollars and tokens), never the zeros
|
|
99
|
+
* it started from, and a late answer leaves it unknown. */
|
|
100
|
+
function bounded(ms, outer, cost, work) {
|
|
101
|
+
if (outer.aborted)
|
|
102
|
+
return Promise.reject(outer.reason);
|
|
103
|
+
const signal = AbortSignal.any([outer, AbortSignal.timeout(ms)]);
|
|
104
|
+
let settled = false;
|
|
105
|
+
const doing = work(signal).finally(() => (settled = true));
|
|
106
|
+
doing.catch(() => undefined);
|
|
107
|
+
const cut = new Promise((_, reject) => {
|
|
108
|
+
const stop = () => {
|
|
109
|
+
if (settled)
|
|
110
|
+
return;
|
|
111
|
+
counter(cost)(null, null);
|
|
112
|
+
reject(signal.reason);
|
|
113
|
+
};
|
|
114
|
+
if (signal.aborted)
|
|
115
|
+
stop();
|
|
116
|
+
else
|
|
117
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
118
|
+
});
|
|
119
|
+
return Promise.race([doing, cut]);
|
|
120
|
+
}
|
|
121
|
+
/** That usage by the platform's names; null when there is none, or a count is not a whole number. */
|
|
122
|
+
const tokensOf = (usage) => usage && [usage.input, usage.output, usage.cacheRead ?? 0, usage.cacheWrite ?? 0].every((n) => Number.isSafeInteger(n) && n >= 0) ? { input: usage.input, cache_read: usage.cacheRead ?? 0, cache_write: usage.cacheWrite ?? 0, output: usage.output } : null;
|
|
123
|
+
/** The variable pi-ai's anthropic provider reads for each auth mode: it sends the first as `authorization: Bearer`, the
|
|
124
|
+
* second as `x-api-key`. */
|
|
125
|
+
const BEARER_VARIABLE = "ANTHROPIC_AUTH_TOKEN";
|
|
126
|
+
const X_API_KEY_VARIABLE = "ANTHROPIC_API_KEY";
|
|
127
|
+
/** pi-ai's auth context for a grade on `provider`, the run's: its credential under the one variable pi-ai reads for its
|
|
128
|
+
* auth mode, and no other variable of serve's env. */
|
|
129
|
+
export function graderAuth(provider) {
|
|
130
|
+
const name = provider.auth === "bearer" ? BEARER_VARIABLE : X_API_KEY_VARIABLE;
|
|
131
|
+
return { env: async (asked) => (asked === name ? (await provider.credential()) || undefined : undefined), fileExists: async () => false };
|
|
132
|
+
}
|
|
133
|
+
/** One completion for the grader: on the model the server names for grading (`named`), picked as a workflow's strong
|
|
134
|
+
* tier is (runModels: the gateway, pi-ai's providers, or the faux module); else on the agent's own model, as its run's
|
|
135
|
+
* process picks it (app.ts): claude-agent's from pi-ai's catalog, sent where and as the run's own requests go
|
|
136
|
+
* (claudeProvider), any other harness's by runModels. At its revision's thinking; counted in `cost` (a call that fails
|
|
137
|
+
* has an unknown cost). */
|
|
138
|
+
async function graderModel(env, agent, cost, named) {
|
|
139
|
+
let chosen;
|
|
140
|
+
if (named) {
|
|
141
|
+
// The strong tier named over `env` itself, never a copy of it: the server's keys are properties that do not list
|
|
142
|
+
// (secrets.ts withSecrets), so a spread would leave every one out. runModels and pi-ai's auth read each by name.
|
|
143
|
+
const tiered = Object.create(env, { AGENT_MODEL_STRONG: { value: named, enumerable: true } });
|
|
144
|
+
const picked = await runModels(tiered, undefined, ["strong"]);
|
|
145
|
+
chosen = { models: picked.models, model: picked.byTier.get("strong") };
|
|
146
|
+
}
|
|
147
|
+
else if (agent.harness === "claude-agent" && !env[FAUX_HARNESS_ENV]) {
|
|
148
|
+
const choice = claudeModel(env, agent.model);
|
|
149
|
+
if ("why" in choice)
|
|
150
|
+
throw new Error(choice.why);
|
|
151
|
+
const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
|
|
152
|
+
// The grader asks where the run's requests go, with the run's credential and auth mode: one claudeProvider call for
|
|
153
|
+
// both. It sends the id the run sends (claudeProvider's modelId), on pi-ai's anthropic provider. The catalog only
|
|
154
|
+
// prices the model.
|
|
155
|
+
const sent = claudeProvider(env, choice.model);
|
|
156
|
+
const catalog = builtinModels({ authContext: graderAuth(sent) });
|
|
157
|
+
const at = (found) => (found && typeof found === "object" ? { ...found, baseUrl: sent.origin } : found);
|
|
158
|
+
chosen = { models: { getModel: (provider, id) => at(catalog.getModel(provider, id)), completeSimple: (...call) => catalog.completeSimple(...call) }, model: { provider: "anthropic", modelId: sent.modelId } };
|
|
159
|
+
}
|
|
160
|
+
else if ((agent.harness === "codex" || agent.harness === "opencode") && !env[FAUX_HARNESS_ENV] && openRouterOnly(agent.harness, env)) {
|
|
161
|
+
// codex on OpenRouter alone, and opencode, which takes codex's route: the grade goes where the run's requests go,
|
|
162
|
+
// OpenRouter with its key, on the model the run runs (codexModel, then the id codexProvider sends), through pi-ai's
|
|
163
|
+
// openrouter provider. The revision's own name (openai/<model>) would ask for an OpenAI key, which this route never
|
|
164
|
+
// needs.
|
|
165
|
+
const choice = await codexModel(env, agent.model, agent.harness);
|
|
166
|
+
if ("why" in choice)
|
|
167
|
+
throw new Error(choice.why);
|
|
168
|
+
chosen = await runModels(env, `openrouter/${codexProvider(env, choice.model, agent.harness).modelId}`);
|
|
169
|
+
}
|
|
170
|
+
else
|
|
171
|
+
chosen = await runModels(env, agent.model);
|
|
172
|
+
const models = chosen.models;
|
|
173
|
+
const { model } = chosen;
|
|
174
|
+
const add = counter(cost);
|
|
175
|
+
return async (args, signal) => {
|
|
176
|
+
// The call's tokens from pi-ai's own usage, which keeps the cache's reads and writes apart.
|
|
177
|
+
let usage;
|
|
178
|
+
const tapped = {
|
|
179
|
+
getModel: (provider, id) => models.getModel(provider, id),
|
|
180
|
+
completeSimple: async (...call) => {
|
|
181
|
+
const message = await models.completeSimple(...call);
|
|
182
|
+
usage = message.usage;
|
|
183
|
+
return message;
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
const answer = await completer(tapped, () => model, thinkingOf(env, agent.thinking))(args, signal).catch((error) => (add(null, null), Promise.reject(error)));
|
|
187
|
+
add(answer.cost_usd, tokensOf(usage));
|
|
188
|
+
return answer;
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/** The grader, on `gradeModel` when the server names one (gradeModelOf), given `asked`, what the user said in the run:
|
|
192
|
+
* its verdict, or why it gave none; with what it spent. Rejects only when `signal` (the server closing) aborts it: nothing
|
|
193
|
+
* is decided then. */
|
|
194
|
+
export async function judgeProposal(input) {
|
|
195
|
+
const { runId, agent, main, proposed, env, signal } = input;
|
|
196
|
+
const files = input.files ?? [];
|
|
197
|
+
const cost = { usd: 0, tokens: { ...NO_TOKENS } };
|
|
198
|
+
try {
|
|
199
|
+
const { gradePrompt, parseVerdict } = await import("./learn/index.js");
|
|
200
|
+
const prompt = gradePrompt({ run: runId, instructions: agent.instructions, active: main.active, superseded: main.superseded, proposed, ...(files.length ? { files } : {}), ...(input.asked ? { asked: input.asked } : {}) });
|
|
201
|
+
const grader = await graderModel(env, agent, cost, input.gradeModel);
|
|
202
|
+
const answer = await bounded(input.gradeTimeoutMs ?? GRADE_TIMEOUT_MS, signal, cost, (grade) => grader({ prompt, maxTokens: GRADE_MAX_TOKENS }, grade));
|
|
203
|
+
// The items with their texts: a note the run marked risky waits whatever the grader says (parseVerdict).
|
|
204
|
+
return { verdict: parseVerdict(answer.text, gradedItems(proposed, files)), cost };
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
signal.throwIfAborted();
|
|
208
|
+
return { reason: "grade_failed", error: error, cost };
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** Each skill and draft file as main keeps it: as the run gave it, or, for one the grader held for its owner's OK, with
|
|
212
|
+
* `status: pending` in its SKILL.md or its README.md (learn/skills.ts held). A held workflow.json is as given: its
|
|
213
|
+
* README holds it. */
|
|
214
|
+
/** The graded item a proposal's file is judged as: a draft's README.md with its workflow.json, every other file as
|
|
215
|
+
* itself (a note, a skill's SKILL.md, a draft's workflow.json). */
|
|
216
|
+
const itemOf = (file) => {
|
|
217
|
+
const place = learnedPlace(file);
|
|
218
|
+
return place?.kind === "readme" ? `workflows/${place.name}/workflow.json` : file;
|
|
219
|
+
};
|
|
220
|
+
/** `proposal` with only what `verdict` keeps (a verdict per item): each note, skill and draft (both its files) its item
|
|
221
|
+
* keeps or holds; the ones it drops are left out. A proposal with no verdict (a merge resumed on one kept before the
|
|
222
|
+
* grade read items) is as it is. */
|
|
223
|
+
export function keptProposal(proposal, verdict) {
|
|
224
|
+
if (!verdict?.items.length)
|
|
225
|
+
return proposal;
|
|
226
|
+
const kept = new Set(verdict.items.filter((item) => item.keep).map((item) => item.file));
|
|
227
|
+
const files = (proposal.files ?? []).filter(({ file }) => kept.has(itemOf(file)));
|
|
228
|
+
const { files: _, ...rest } = proposal;
|
|
229
|
+
return { ...rest, notes: proposal.notes.filter(({ file }) => kept.has(file)), ...(files.length ? { files } : {}) };
|
|
230
|
+
}
|
|
231
|
+
export function heldFiles(files, verdict) {
|
|
232
|
+
const waiting = new Set((verdict?.items ?? []).filter((item) => item.pending).map((item) => item.file));
|
|
233
|
+
return files.map(({ file, text }) => {
|
|
234
|
+
const place = learnedPlace(file);
|
|
235
|
+
const judged = place?.kind === "readme" ? `workflows/${place.name}/workflow.json` : file;
|
|
236
|
+
return { file, text: waiting.has(judged) && place?.kind !== "workflow" ? held(text) : text };
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
/** The blob `file` is at commit `sha` of the agent's folder, or undefined when the commit holds no such file. */
|
|
240
|
+
async function blobAt(home, repo, sha, file) {
|
|
241
|
+
try {
|
|
242
|
+
return line(await git(home, repo, ["rev-parse", "--verify", "--quiet", `${sha}:${file}`])) || undefined;
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return undefined;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** Merges run `runId`'s proposal into main as main is now, in the agent's queue, as `verdict` judged its notes: one commit
|
|
249
|
+
* on main (its parent main) that adds the new notes, each with its `origin` and a pending one with `status: pending`
|
|
250
|
+
* (in no index, so no run reads it, until a person approves it), marks each note a kept one supersedes (a pending
|
|
251
|
+
* note's wait for its approval), adds or changes the skill's and draft's files (heldFiles: a held one pending) and
|
|
252
|
+
* rebuilds MEMORY.md, its message `learning: <run>: merged`,
|
|
253
|
+
* `reason` and the run's Run-Id; moved onto main only from the commit it was made on, once more on a main that moved
|
|
254
|
+
* meanwhile. Then the checked-out files are main's. A run a commit on main already names is that commit. `problems`
|
|
255
|
+
* when main, as it is now, takes the notes no more (mergeProblems), or when a note the merge marks superseded is not
|
|
256
|
+
* the blob the grade read (`graded`, readForGrade's): a person changed it since, and their text stands. A note held for
|
|
257
|
+
* its owner's OK marks nothing (supersededBy), so what it names is not checked. `checkout` is why the files could not
|
|
258
|
+
* be brought in line, when they could not: main is merged all the same. */
|
|
259
|
+
export function mergeProposal(data, agentId, runId, proposal, reason, graded, verdict) {
|
|
260
|
+
const home = homeOf(data, agentId);
|
|
261
|
+
// Each note as main keeps it: its origin, the grader's (a run's when it names none), and a pending one waiting.
|
|
262
|
+
const judged = new Map((verdict?.items ?? []).map((item) => [item.file, item]));
|
|
263
|
+
const texts = proposal.notes.map(({ file, text }) => ({ file, text: mergedNote(text, { origin: judged.get(file)?.origin ?? "run", pending: judged.get(file)?.pending === true }) }));
|
|
264
|
+
const added = proposedOf({ ...proposal, notes: texts });
|
|
265
|
+
return withAgentRepo(data, agentId, async () => {
|
|
266
|
+
const repo = await agentFolder(data, agentId);
|
|
267
|
+
const checkout = (sha) => checkOut(repo, sha);
|
|
268
|
+
for (let tries = 0;; tries++) {
|
|
269
|
+
const sha = (await mainOf(home, repo));
|
|
270
|
+
const known = await mergeOf(home, repo, sha, runId);
|
|
271
|
+
if (known)
|
|
272
|
+
return { merged: known, checkout: await checkout(sha) };
|
|
273
|
+
const main = await readMain(home, repo, sha);
|
|
274
|
+
const problems = problemsOf(main, added);
|
|
275
|
+
if (problems.length)
|
|
276
|
+
return { problems };
|
|
277
|
+
// What the merge marks superseded (a note held for its owner's OK marks nothing).
|
|
278
|
+
const replaced = supersededBy(added);
|
|
279
|
+
// The verdict was on the text the grade read: a note this merge marks that is another blob now is never marked on
|
|
280
|
+
// it.
|
|
281
|
+
const changed = [...replaced].filter(([old]) => main.oids.get(old) !== graded[old]).map(([old, by]) => ({ rule: "supersedes", path: by, detail: `${old} changed after the grade read it` }));
|
|
282
|
+
if (changed.length)
|
|
283
|
+
return { problems: changed };
|
|
284
|
+
// A skill's or a draft's file is written whole over main's: one that changed on main after the run started (a
|
|
285
|
+
// person retired or approved it, or another run's merge changed it) is never written over on this run's copy.
|
|
286
|
+
const moved = [];
|
|
287
|
+
for (const { file } of proposal.files ?? []) {
|
|
288
|
+
if ((await blobAt(home, repo, proposal.seed, file)) !== (await blobAt(home, repo, sha, file)))
|
|
289
|
+
moved.push({ rule: "supersedes", path: file, detail: `${file} changed on main after the run started` });
|
|
290
|
+
}
|
|
291
|
+
if (moved.length)
|
|
292
|
+
return { problems: moved };
|
|
293
|
+
const notes = notesOf(main);
|
|
294
|
+
// The new tree: main's, with the new notes, the ones the kept notes supersede marked, and the index rebuilt from
|
|
295
|
+
// what is active then (a pending note is not).
|
|
296
|
+
const files = new Map([...texts, ...heldFiles(proposal.files ?? [], verdict)].map(({ file, text }) => [file, text]));
|
|
297
|
+
for (const [old, by] of replaced)
|
|
298
|
+
files.set(old, supersede(main.texts.get(old), by));
|
|
299
|
+
const after = [...notes.filter((note) => !replaced.has(note.file)), ...added];
|
|
300
|
+
files.set(INDEX_FILE, buildIndex(after));
|
|
301
|
+
const env = { GIT_INDEX_FILE: join(repo, ".git", `merge-${runId}.index`) };
|
|
302
|
+
let commit;
|
|
303
|
+
try {
|
|
304
|
+
await rm(env.GIT_INDEX_FILE, { force: true });
|
|
305
|
+
await git(home, repo, ["read-tree", sha], "", env);
|
|
306
|
+
const entries = [];
|
|
307
|
+
for (const [file, text] of files)
|
|
308
|
+
entries.push(`100644 ${line(await git(home, repo, ["hash-object", "-w", "--no-filters", "--stdin"], text))}\t${file}\0`);
|
|
309
|
+
await git(home, repo, ["update-index", "-z", "--index-info"], entries.join(""), env);
|
|
310
|
+
const tree = line(await git(home, repo, ["write-tree"], "", env));
|
|
311
|
+
commit = line(await git(home, repo, ["commit-tree", tree, "-p", sha, "-m", `learning: ${runId}: merged`, "-m", reason, "-m", `Run-Id: ${runId}`]));
|
|
312
|
+
}
|
|
313
|
+
finally {
|
|
314
|
+
await rm(env.GIT_INDEX_FILE, { force: true });
|
|
315
|
+
}
|
|
316
|
+
try {
|
|
317
|
+
await git(home, repo, ["update-ref", "-m", `learning: merge ${runId}`, "refs/heads/main", commit, sha]);
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
// Lost to a write since main was read: merged again onto the main that won, never forced over it.
|
|
321
|
+
if (tries === 0 && (await mainOf(home, repo)) !== sha)
|
|
322
|
+
continue;
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
return { merged: commit, checkout: await checkout(commit) };
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The most of a map item's label and of an error (a call's, a decision's) the graph shows. */
|
|
2
|
+
export declare const LABEL_SHOWN = 200;
|
|
3
|
+
export declare const ERROR_SHOWN = 2000;
|
|
4
|
+
export type PartKind = "nodes" | "decision" | "effect";
|
|
5
|
+
/** `value`, a part of a graph view of `kind`, as the graph serves it with `values` held: each string and number by
|
|
6
|
+
* redactedOutput, then a map item's label cut at LABEL_SHOWN and an error at ERROR_SHOWN. A text stored cut (a
|
|
7
|
+
* decision's state past 64 KB, an error marked cut, or one of exactly ERROR_CUT_BEFORE characters from before) has its
|
|
8
|
+
* last 6 times the longest held value plus 16 characters held back, where a value the stored cut split would sit. */
|
|
9
|
+
export declare function servedPart(kind: PartKind, value: unknown, values: readonly string[]): unknown;
|
|
10
|
+
/** What every run's graph keeps in serve's memory, in one cache: each part as served (servedPart), and each workflow
|
|
11
|
+
* run's last whole view, which a busy store's read answers from. */
|
|
12
|
+
export declare const GRAPH_CACHE_BYTES: number;
|
|
13
|
+
/** A least recently used cache bounded by bytes: an entry read or set is the most recent, and past `maxBytes` the least
|
|
14
|
+
* recent go, one at a time, until it fits; never all at once. An entry bigger than the bound is not kept. */
|
|
15
|
+
export declare class PartCache {
|
|
16
|
+
readonly maxBytes: number;
|
|
17
|
+
private readonly entries;
|
|
18
|
+
bytes: number;
|
|
19
|
+
constructor(maxBytes: number);
|
|
20
|
+
get size(): number;
|
|
21
|
+
get(key: string): unknown;
|
|
22
|
+
set(key: string, value: unknown, bytes: number): void;
|
|
23
|
+
}
|