@parcha/agentrun-serve 0.0.0-stage → 0.1.0-beta.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +560 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +1723 -2
- package/dist/adapters.d.ts +205 -0
- package/dist/adapters.js +459 -0
- package/dist/agents.d.ts +124 -0
- package/dist/agents.js +302 -0
- package/dist/app.d.ts +7 -0
- package/dist/app.js +324 -0
- package/dist/bound-files.d.ts +4 -0
- package/dist/bound-files.js +164 -0
- package/dist/box/record.d.ts +6 -0
- package/dist/box/record.js +41 -0
- package/dist/box/sweep.d.ts +53 -0
- package/dist/box/sweep.js +193 -0
- package/dist/box-image.d.ts +98 -0
- package/dist/box-image.js +283 -0
- package/dist/box-relay.d.ts +42 -0
- package/dist/box-relay.js +222 -0
- package/dist/boxes.d.ts +54 -0
- package/dist/boxes.js +182 -0
- package/dist/cap.d.ts +224 -0
- package/dist/cap.js +721 -0
- package/dist/catalog.d.ts +20 -0
- package/dist/catalog.js +53 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +167 -0
- package/dist/coding-tools.d.ts +31 -0
- package/dist/coding-tools.js +81 -0
- package/dist/console/THIRD-PARTY-NOTICES.txt +1141 -0
- package/dist/console/assets/index-BN7oVcO4.js +445 -0
- package/dist/console/assets/index-By-jkqki.css +1 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
- package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
- package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
- package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
- package/dist/console/index.html +15 -0
- package/dist/daytona-api.d.ts +21 -0
- package/dist/daytona-api.js +101 -0
- package/dist/decision-rows.d.ts +11 -0
- package/dist/decision-rows.js +116 -0
- package/dist/decisions.d.ts +94 -0
- package/dist/decisions.js +184 -0
- package/dist/effort-guidance.d.ts +5 -0
- package/dist/effort-guidance.js +14 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.js +11 -0
- package/dist/errors.d.ts +72 -0
- package/dist/errors.js +66 -0
- package/dist/exa-keyless.d.ts +35 -0
- package/dist/exa-keyless.js +202 -0
- package/dist/fetch-page.d.ts +114 -0
- package/dist/fetch-page.js +182 -0
- package/dist/files.d.ts +60 -0
- package/dist/files.js +153 -0
- package/dist/grade.d.ts +96 -0
- package/dist/grade.js +348 -0
- package/dist/graph-view.d.ts +100 -0
- package/dist/graph-view.js +212 -0
- package/dist/harness-app.d.ts +38 -0
- package/dist/harness-app.js +626 -0
- package/dist/harness.d.ts +53 -0
- package/dist/harness.js +74 -0
- package/dist/home-path.d.ts +27 -0
- package/dist/home-path.js +78 -0
- package/dist/host-tools.d.ts +20 -0
- package/dist/host-tools.js +140 -0
- package/dist/host.d.ts +39 -0
- package/dist/host.js +81 -0
- package/dist/hosted-search.d.ts +27 -0
- package/dist/hosted-search.js +129 -0
- package/dist/import-sources.d.ts +104 -0
- package/dist/import-sources.js +629 -0
- package/dist/import-summary.d.ts +25 -0
- package/dist/import-summary.js +75 -0
- package/dist/import-worker.d.ts +26 -0
- package/dist/import-worker.js +41 -0
- package/dist/import.d.ts +145 -0
- package/dist/import.js +1221 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/key-check.d.ts +36 -0
- package/dist/key-check.js +108 -0
- package/dist/key-refusal.d.ts +51 -0
- package/dist/key-refusal.js +187 -0
- package/dist/learn/check.d.ts +99 -0
- package/dist/learn/check.js +259 -0
- package/dist/learn/grade.d.ts +79 -0
- package/dist/learn/grade.js +433 -0
- package/dist/learn/index.d.ts +7 -0
- package/dist/learn/index.js +11 -0
- package/dist/learn/invisible.d.ts +5 -0
- package/dist/learn/invisible.js +42 -0
- package/dist/learn/notes.d.ts +59 -0
- package/dist/learn/notes.js +146 -0
- package/dist/learn/reflect.d.ts +49 -0
- package/dist/learn/reflect.js +167 -0
- package/dist/learn/secrets.d.ts +18 -0
- package/dist/learn/secrets.js +111 -0
- package/dist/learn/skills.d.ts +84 -0
- package/dist/learn/skills.js +198 -0
- package/dist/learning-routes.d.ts +196 -0
- package/dist/learning-routes.js +609 -0
- package/dist/learning-run.d.ts +304 -0
- package/dist/learning-run.js +797 -0
- package/dist/learning-words.d.ts +73 -0
- package/dist/learning-words.js +171 -0
- package/dist/learning.d.ts +377 -0
- package/dist/learning.js +801 -0
- package/dist/llm.d.ts +40 -0
- package/dist/llm.js +37 -0
- package/dist/llms.txt +37 -0
- package/dist/mcp-servers.d.ts +115 -0
- package/dist/mcp-servers.js +445 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +392 -0
- package/dist/model.d.ts +184 -0
- package/dist/model.js +484 -0
- package/dist/monid.d.ts +74 -0
- package/dist/monid.js +277 -0
- package/dist/openapi/agentrun-v2.openapi.json +4805 -0
- package/dist/openapi.d.ts +10 -0
- package/dist/openapi.js +1417 -0
- package/dist/owner.d.ts +55 -0
- package/dist/owner.js +222 -0
- package/dist/packs.d.ts +71 -0
- package/dist/packs.js +180 -0
- package/dist/page.d.ts +32 -0
- package/dist/page.js +133 -0
- package/dist/paid-calls.d.ts +46 -0
- package/dist/paid-calls.js +110 -0
- package/dist/pause.d.ts +68 -0
- package/dist/pause.js +97 -0
- package/dist/pdf-pages.d.ts +44 -0
- package/dist/pdf-pages.js +147 -0
- package/dist/place.d.ts +46 -0
- package/dist/place.js +105 -0
- package/dist/print.d.ts +20 -0
- package/dist/print.js +29 -0
- package/dist/propose.d.ts +38 -0
- package/dist/propose.js +82 -0
- package/dist/quiet-sqlite-warning.d.ts +1 -0
- package/dist/quiet-sqlite-warning.js +14 -0
- package/dist/request-start.d.ts +14 -0
- package/dist/request-start.js +226 -0
- package/dist/result.d.ts +3 -0
- package/dist/result.js +5 -0
- package/dist/rows.d.ts +46 -0
- package/dist/rows.js +121 -0
- package/dist/run-box.d.ts +134 -0
- package/dist/run-box.js +440 -0
- package/dist/run-manifest.d.ts +27 -0
- package/dist/run-manifest.js +60 -0
- package/dist/runnable.d.ts +80 -0
- package/dist/runnable.js +162 -0
- package/dist/runs.d.ts +840 -0
- package/dist/runs.js +2279 -0
- package/dist/secret-cut.d.ts +27 -0
- package/dist/secret-cut.js +109 -0
- package/dist/secrets.d.ts +50 -0
- package/dist/secrets.js +140 -0
- package/dist/server-lock.d.ts +44 -0
- package/dist/server-lock.js +140 -0
- package/dist/server.d.ts +626 -0
- package/dist/server.js +1756 -0
- package/dist/sessions.d.ts +4 -0
- package/dist/sessions.js +105 -0
- package/dist/skills.d.ts +31 -0
- package/dist/skills.js +68 -0
- package/dist/stats.d.ts +101 -0
- package/dist/stats.js +82 -0
- package/dist/tool-keys.d.ts +151 -0
- package/dist/tool-keys.js +273 -0
- package/dist/tool-plane.d.ts +143 -0
- package/dist/tool-plane.js +242 -0
- package/dist/tools.d.ts +147 -0
- package/dist/tools.js +253 -0
- package/dist/turn-end.d.ts +23 -0
- package/dist/turn-end.js +14 -0
- package/dist/turns.d.ts +34 -0
- package/dist/turns.js +202 -0
- package/dist/uploads.d.ts +104 -0
- package/dist/uploads.js +474 -0
- package/dist/usage.d.ts +29 -0
- package/dist/usage.js +58 -0
- package/dist/validate.d.ts +55 -0
- package/dist/validate.js +175 -0
- package/dist/web-fetch.d.ts +64 -0
- package/dist/web-fetch.js +262 -0
- package/dist/web-search.d.ts +54 -0
- package/dist/web-search.js +136 -0
- package/dist/webhooks.d.ts +182 -0
- package/dist/webhooks.js +487 -0
- package/dist/workspace-paths.d.ts +33 -0
- package/dist/workspace-paths.js +104 -0
- package/dist/workspace.d.ts +88 -0
- package/dist/workspace.js +369 -0
- package/launcher/agentrun-serve +109 -0
- package/package.json +94 -4
- package/skills/agentrun-serve/SKILL.md +128 -0
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
// What a person sees and controls of an agent's learning: this server's own routes under /v2 (learning/1).
|
|
2
|
+
// - Per agent: main's index, its notes and its log of changes, each a page, its skills and workflow drafts, and how its
|
|
3
|
+
// runs' learning fared; one note, a skill's SKILL.md or a draft's file as text with its ETag, its blob id on main.
|
|
4
|
+
// - A person's approval of a note, a skill or a draft that waits for the owner's OK, and their edit, create or retire of
|
|
5
|
+
// one note (a skill or a draft is a run's to change): a precondition on the note's version (If-Match, or If-None-Match: * to
|
|
6
|
+
// create; neither is 428), the structural checks a run's notes pass (learn/check.ts checkNote; a retire, the note's
|
|
7
|
+
// format alone, so a leaking note can always be revoked) and no grader, then one host commit on main in the agent's
|
|
8
|
+
// queue, compare and swap, with MEMORY.md rebuilt and a `Changed-By: user` trailer, and the checked-out files brought
|
|
9
|
+
// in line. MEMORY.md itself is never written here.
|
|
10
|
+
// - Per run: its learning whole, and its diff: what it proposed against its seed, or once merged, its merge commit against
|
|
11
|
+
// its parent.
|
|
12
|
+
// Every read is plumbing at one commit of main, outside the queue: a commit never changes, so a read needs no lock, and
|
|
13
|
+
// a page's cursor names the commit it was read at. What a commit's notes are, parsed and in order, is kept for the few
|
|
14
|
+
// commits last read (Recent), so later pages and the view at the same commit read no note again; the log reads only
|
|
15
|
+
// its page's commits (skip and max-count). A read reaches the folder through readFolder, a write through agentFolder:
|
|
16
|
+
// the same link rule, so a link at the folder is an error on either, never followed. A text that leaves holding one of
|
|
17
|
+
// the host's secrets as they are now (a value made secret after it was written) is cut of it, a file's name holding
|
|
18
|
+
// one reads "[redacted]" whole, and a diff's file holding one is withheld.
|
|
19
|
+
import { rm } from "node:fs/promises";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
import { approve, buildIndex, CAPS, checkNote, INDEX_FILE, INDEX_LINES, isHeld, learnedFront, learnedName, learnedPlace, learnedStatus, NOTE_FILE, NOTE_STATUSES, parseNoteFile, printable, released, retire, retiredLearned, SKILLS_DIR, supersede, WORKFLOWS_DIR } from "./learn/index.js";
|
|
22
|
+
import { ApiError, invalid } from "./errors.js";
|
|
23
|
+
import { homeOf, readJson } from "./files.js";
|
|
24
|
+
import { agentFolder, changedOrder, checkOut, detailShown, git, line, mainOf, notesView, openAgentRepo, PROPOSAL, readBlobs, readFolder, readPin, secretsShown, withAgentRepo } from "./learning.js";
|
|
25
|
+
import { isObject } from "./validate.js";
|
|
26
|
+
/** A file on main larger than this is not read: a note is at most 4 KB (learn/check.ts CAPS.note). */
|
|
27
|
+
const FILE_CAP = 1 << 20;
|
|
28
|
+
/** A diff's file whose patch is larger than this is withheld as too large. */
|
|
29
|
+
const PATCH_CAP = 64 * 1024;
|
|
30
|
+
/** The agent view's first pages, and the most a page holds. */
|
|
31
|
+
const NOTES_PAGE = 50;
|
|
32
|
+
const LOG_PAGE = 20;
|
|
33
|
+
const PAGE_MAX = 200;
|
|
34
|
+
/** The trailer of a person's commit, as `Run-Id` is a run's merge's. */
|
|
35
|
+
const BY_USER = "Changed-By: user";
|
|
36
|
+
/** The trailer an approval's commit carries beside BY_USER: it came from the owner's password session in the console. */
|
|
37
|
+
const APPROVED_VIA = "Approved-Via: console";
|
|
38
|
+
/** What a retire adds to a note, on top of the note cap a retired note may fill (learn/notes.ts retire). */
|
|
39
|
+
const RETIRED_LINE = Buffer.byteLength("status: retired\n");
|
|
40
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
41
|
+
export { secretsShown } from "./learning.js";
|
|
42
|
+
/** The few values last kept, by key, oldest dropped first: at most `entries` of them, `bytes` in all by their sizes. */
|
|
43
|
+
class Recent {
|
|
44
|
+
entries;
|
|
45
|
+
bytes;
|
|
46
|
+
held = new Map();
|
|
47
|
+
size = 0;
|
|
48
|
+
constructor(entries, bytes = Infinity) {
|
|
49
|
+
this.entries = entries;
|
|
50
|
+
this.bytes = bytes;
|
|
51
|
+
}
|
|
52
|
+
get(key) {
|
|
53
|
+
const hit = this.held.get(key);
|
|
54
|
+
if (!hit)
|
|
55
|
+
return undefined;
|
|
56
|
+
this.held.delete(key);
|
|
57
|
+
this.held.set(key, hit);
|
|
58
|
+
return hit.value;
|
|
59
|
+
}
|
|
60
|
+
set(key, value, size = 0) {
|
|
61
|
+
this.drop(key);
|
|
62
|
+
if (size > this.bytes)
|
|
63
|
+
return;
|
|
64
|
+
this.held.set(key, { value, size });
|
|
65
|
+
this.size += size;
|
|
66
|
+
while (this.held.size > this.entries || this.size > this.bytes)
|
|
67
|
+
this.drop(this.held.keys().next().value);
|
|
68
|
+
}
|
|
69
|
+
drop(key) {
|
|
70
|
+
const hit = this.held.get(key);
|
|
71
|
+
if (!hit)
|
|
72
|
+
return;
|
|
73
|
+
this.held.delete(key);
|
|
74
|
+
this.size -= hit.size;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** By the folder and the commit, which never changes: its index and notes in the view's order, for the 8 commits last
|
|
78
|
+
* read and 16 MiB at most (a note is 4 KB at most), and how many changes its log holds. Raw: each answer cuts them of
|
|
79
|
+
* the host's secrets as they are then. */
|
|
80
|
+
const parsedAt = new Recent(8, 16 << 20);
|
|
81
|
+
const changesAt = new Recent(64);
|
|
82
|
+
/** Where a read finds the agent's folder: through readFolder, so a link at its home, its `learning/` or its `.git` is
|
|
83
|
+
* an error, never followed, and a folder never made reads as empty. */
|
|
84
|
+
const placeOf = async (data, agentId) => ({ home: homeOf(data, agentId), repo: await readFolder(data, agentId) });
|
|
85
|
+
export const etagOf = (oid) => `"${oid}"`;
|
|
86
|
+
const EMPTY = { items: [], total: 0, next_cursor: null };
|
|
87
|
+
/** Whether `path` is a skill's SKILL.md or a draft's workflow.json or README.md, its folder well named. */
|
|
88
|
+
const isLearned = (path) => {
|
|
89
|
+
const place = learnedPlace(path);
|
|
90
|
+
return place !== undefined && learnedName(place.kind, place.name);
|
|
91
|
+
};
|
|
92
|
+
/** The `.md` files at commit `sha`'s top (or the one `file`, a skill's or a draft's too), by name: the index and notes'
|
|
93
|
+
* names, regular files under FILE_CAP only, each with its blob id. */
|
|
94
|
+
async function entriesAt(home, repo, sha, file) {
|
|
95
|
+
const out = new Map();
|
|
96
|
+
for (const entry of (await git(home, repo, ["ls-tree", "-l", "-z", sha, ...(file ? ["--", file] : [])])).toString("utf8").split("\0").filter(Boolean)) {
|
|
97
|
+
const tab = entry.indexOf("\t");
|
|
98
|
+
const [mode, type, oid, size] = entry.slice(0, tab).split(/\s+/);
|
|
99
|
+
const path = entry.slice(tab + 1);
|
|
100
|
+
if ((path === INDEX_FILE || NOTE_FILE.test(path) || (file !== undefined && isLearned(path))) && mode === "100644" && type === "blob" && oid && Number(size) <= FILE_CAP)
|
|
101
|
+
out.set(path, oid);
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
/** The texts of `entries`, by file, read in one batch: one that is not UTF-8 is left out. */
|
|
106
|
+
async function textsOf(home, repo, entries) {
|
|
107
|
+
const files = [...entries.keys()];
|
|
108
|
+
const blobs = await readBlobs(home, repo, files.map((file) => entries.get(file)));
|
|
109
|
+
const out = new Map();
|
|
110
|
+
files.forEach((file, i) => {
|
|
111
|
+
try {
|
|
112
|
+
out.set(file, { oid: entries.get(file), text: utf8.decode(blobs[i]) });
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
// Not UTF-8: no note, and never shown as one.
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** What commit `sha` holds: the index's text, and every note that parses, with its text, by file. */
|
|
121
|
+
async function readAt(home, repo, sha) {
|
|
122
|
+
const texts = await textsOf(home, repo, await entriesAt(home, repo, sha));
|
|
123
|
+
const notes = new Map();
|
|
124
|
+
for (const [file, { oid, text }] of texts) {
|
|
125
|
+
const note = file === INDEX_FILE ? [] : parseNoteFile(file, text);
|
|
126
|
+
if (!Array.isArray(note))
|
|
127
|
+
notes.set(file, { ...note, text, oid });
|
|
128
|
+
}
|
|
129
|
+
return { index: texts.get(INDEX_FILE)?.text ?? "", notes };
|
|
130
|
+
}
|
|
131
|
+
/** One file at commit `sha`: its blob id and text, or undefined. */
|
|
132
|
+
const fileAt = async (home, repo, sha, file) => (await textsOf(home, repo, await entriesAt(home, repo, sha, file))).get(file);
|
|
133
|
+
/** Whether commit `sha`'s tree holds anything at `file`, as git stores it: any mode or type, any size, any bytes. The
|
|
134
|
+
* notes leave out a file that is not a regular UTF-8 one under FILE_CAP, so a write asks this before it takes a name
|
|
135
|
+
* as free. */
|
|
136
|
+
const heldAt = async (home, repo, sha, file) => (await git(home, repo, ["ls-tree", "-z", sha, "--", file])).toString("utf8").split("\0").some((entry) => entry.slice(entry.indexOf("\t") + 1) === file);
|
|
137
|
+
/** The commits on main that are changes: a run's merge (`Run-Id`) or a person's commit (`Changed-By: user`), by their
|
|
138
|
+
* trailers' lines; the folder's first commit, the host's, is neither. Every commit on main is the host's, so a line
|
|
139
|
+
* that matches is a trailer. */
|
|
140
|
+
const CHANGES = ["--first-parent", "--extended-regexp", "--grep=^Run-Id: ", "--grep=^Changed-By: user$"];
|
|
141
|
+
const CHANGE_FORMAT = "%x1e%H%x1f%cI%x1f%s%x1f%b%x1f%(trailers:key=Run-Id,valueonly,separator=%x2C)%x1f%(trailers:key=Changed-By,valueonly,separator=%x2C)%x1f%(trailers:key=Approved-Via,valueonly,separator=%x2C)";
|
|
142
|
+
/** `git log -z --name-only`'s records, each its header (as the format wrote it) and the files it changed. */
|
|
143
|
+
const recordsOf = (out) => out.toString("utf8").split("\x1e").slice(1).map((record) => {
|
|
144
|
+
const end = record.indexOf("\0");
|
|
145
|
+
return { head: record.slice(0, end < 0 ? undefined : end), files: end < 0 ? [] : record.slice(end + 1).split("\0").map((file) => file.replace(/^\n/, "")).filter(Boolean) };
|
|
146
|
+
});
|
|
147
|
+
/** The changes on main to `sha`, newest first, from the `offset`th, at most `limit`: only those commits read, each told
|
|
148
|
+
* by its trailers (a run's, or `{user: true}`). A merge's reason is the grader's, its own paragraph before the
|
|
149
|
+
* trailers; a person's commit has none, so its subject says what it did. */
|
|
150
|
+
async function changesFrom(home, repo, sha, offset, limit) {
|
|
151
|
+
const log = [];
|
|
152
|
+
for (const { head, files } of recordsOf(await git(home, repo, ["log", ...CHANGES, `--skip=${offset}`, `--max-count=${limit}`, "-z", "--name-only", `--format=${CHANGE_FORMAT}`, sha]))) {
|
|
153
|
+
const [commit = "", at = "", subject = "", body = "", run = "", by = "", via = ""] = head.split("\x1f");
|
|
154
|
+
const runId = run.split(",")[0].trim();
|
|
155
|
+
const approvedVia = via.split(",")[0].trim();
|
|
156
|
+
const who = runId ? { run: runId } : by.trim() === "user" ? { user: true, ...(approvedVia ? { via: approvedVia } : {}) } : undefined;
|
|
157
|
+
if (!who || !commit || !Date.parse(at))
|
|
158
|
+
continue;
|
|
159
|
+
const paragraphs = body.split(/\n\s*\n/).map((part) => part.trim()).filter(Boolean);
|
|
160
|
+
log.push({ by: who, commit, at: new Date(at).toISOString(), reason: paragraphs.slice(0, -1).join(" ") || subject.replace(/^learning: /, ""), files });
|
|
161
|
+
}
|
|
162
|
+
return log;
|
|
163
|
+
}
|
|
164
|
+
/** How many changes main holds to `sha`, counted once a commit: git reads commits alone, never a tree. */
|
|
165
|
+
async function changeCount(home, repo, sha) {
|
|
166
|
+
const key = `${repo}\0${sha}`;
|
|
167
|
+
const known = changesAt.get(key);
|
|
168
|
+
if (known !== undefined)
|
|
169
|
+
return known;
|
|
170
|
+
const count = Number(line(await git(home, repo, ["rev-list", "--count", ...CHANGES, sha])));
|
|
171
|
+
changesAt.set(key, count);
|
|
172
|
+
return count;
|
|
173
|
+
}
|
|
174
|
+
/** A page of the changes on main to `sha`, cut of the host's secrets. */
|
|
175
|
+
async function logPage(home, repo, sha, offset, limit, shown) {
|
|
176
|
+
const [total, log] = await Promise.all([changeCount(home, repo, sha), changesFrom(home, repo, sha, offset, limit)]);
|
|
177
|
+
return { items: log.map((change) => ({ ...change, reason: shown.text(change.reason), files: change.files.map(shown.name) })), total, next_cursor: offset + limit < total ? cursorOf(sha, offset + limit) : null };
|
|
178
|
+
}
|
|
179
|
+
/** Commit `sha`'s index and notes, its notes as the view shows them: active first, then by their newest change on
|
|
180
|
+
* main's first-parent log (their place in the walk, so two changes in one second keep their order), newest first, then
|
|
181
|
+
* by name. Read once a commit, then kept (parsedAt). */
|
|
182
|
+
async function notesAt(home, repo, sha) {
|
|
183
|
+
const key = `${repo}\0${sha}`;
|
|
184
|
+
const known = parsedAt.get(key);
|
|
185
|
+
if (known)
|
|
186
|
+
return known;
|
|
187
|
+
const [{ index, notes }, touched] = await Promise.all([readAt(home, repo, sha), changedOrder(home, repo, sha)]);
|
|
188
|
+
const rank = (note) => (note.status === "active" ? 0 : 1);
|
|
189
|
+
const parsed = { index, notes: [...notes.values()].sort((a, b) => rank(a) - rank(b) || (touched.get(a.file) ?? Infinity) - (touched.get(b.file) ?? Infinity) || (a.file < b.file ? -1 : 1)) };
|
|
190
|
+
parsedAt.set(key, parsed, 2 * parsed.notes.reduce((size, note) => size + note.text.length + 256, index.length));
|
|
191
|
+
return parsed;
|
|
192
|
+
}
|
|
193
|
+
/** By the folder and the commit: its skills and drafts, raw (each answer cuts them of the host's secrets as they are
|
|
194
|
+
* then), for the 8 commits last read. */
|
|
195
|
+
const learnedAtCache = new Recent(8, 4 << 20);
|
|
196
|
+
/** The run whose merge last changed each of commit `sha`'s files under skills/ and workflows/: its first-parent log's
|
|
197
|
+
* commits with a Run-Id, newest first, read once (a person's approval, which names none, changes no answer). */
|
|
198
|
+
async function lastRuns(home, repo, sha) {
|
|
199
|
+
const out = new Map();
|
|
200
|
+
for (const { head, files } of recordsOf(await git(home, repo, ["log", "--first-parent", "-z", "--name-only", "--format=%x1e%(trailers:key=Run-Id,valueonly,separator=%x2C)", sha, "--", SKILLS_DIR, WORKFLOWS_DIR]))) {
|
|
201
|
+
const run = head.split(",")[0].trim();
|
|
202
|
+
if (run)
|
|
203
|
+
for (const file of files)
|
|
204
|
+
if (!out.has(file))
|
|
205
|
+
out.set(file, run);
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
/** Commit `sha`'s skills and workflow drafts, by name: each skill's SKILL.md and each draft's workflow.json with its
|
|
210
|
+
* README.md, regular files under FILE_CAP, with what their front matter says. A draft without its README, or a file
|
|
211
|
+
* that is not UTF-8, is left out, as the checker never lets it in. Read once a commit, then kept. */
|
|
212
|
+
async function learnedAt(home, repo, sha) {
|
|
213
|
+
const key = `${repo}\0${sha}`;
|
|
214
|
+
const known = learnedAtCache.get(key);
|
|
215
|
+
if (known)
|
|
216
|
+
return known;
|
|
217
|
+
const entries = new Map();
|
|
218
|
+
for (const entry of (await git(home, repo, ["ls-tree", "-r", "-l", "-z", sha, "--", SKILLS_DIR, WORKFLOWS_DIR])).toString("utf8").split("\0").filter(Boolean)) {
|
|
219
|
+
const tab = entry.indexOf("\t");
|
|
220
|
+
const [mode, type, oid, size] = entry.slice(0, tab).split(/\s+/);
|
|
221
|
+
const path = entry.slice(tab + 1);
|
|
222
|
+
if (isLearned(path) && mode === "100644" && type === "blob" && oid && Number(size) <= FILE_CAP)
|
|
223
|
+
entries.set(path, { oid, size: Number(size) });
|
|
224
|
+
}
|
|
225
|
+
const fronts = new Map([...entries].filter(([path]) => !path.endsWith("/workflow.json")).map(([path, { oid }]) => [path, oid]));
|
|
226
|
+
// A folder with none reads no history for them.
|
|
227
|
+
const [texts, runs] = entries.size ? await Promise.all([textsOf(home, repo, fronts), lastRuns(home, repo, sha)]) : [new Map(), new Map()];
|
|
228
|
+
const skills = [];
|
|
229
|
+
const workflows = [];
|
|
230
|
+
for (const [path, { size }] of entries) {
|
|
231
|
+
const place = learnedPlace(path);
|
|
232
|
+
if (place.kind === "readme")
|
|
233
|
+
continue;
|
|
234
|
+
const held = place.kind === "skill" ? path : `${WORKFLOWS_DIR}/${place.name}/README.md`;
|
|
235
|
+
const front = texts.get(held);
|
|
236
|
+
if (!front)
|
|
237
|
+
continue;
|
|
238
|
+
const said = learnedFront(front.text);
|
|
239
|
+
const item = { name: place.name, file: path, ...(place.kind === "workflow" ? { readme: held } : {}), description: said?.description ?? "", status: learnedStatus(front.text), run: runs.get(path) ?? null, bytes: size, etag: etagOf(front.oid) };
|
|
240
|
+
(place.kind === "skill" ? skills : workflows).push(item);
|
|
241
|
+
}
|
|
242
|
+
const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
243
|
+
const found = { skills: skills.sort(byName), workflows: workflows.sort(byName) };
|
|
244
|
+
learnedAtCache.set(key, found, [...skills, ...workflows].reduce((n, item) => n + item.description.length + 512, 0));
|
|
245
|
+
return found;
|
|
246
|
+
}
|
|
247
|
+
/** A skill or a draft as the view shows it, cut of the host's secrets: a name or a file holding one reads [redacted]. */
|
|
248
|
+
const learnedView = (item, shown) => ({ ...item, name: shown.name(item.name), file: shown.name(item.file), ...(item.readme ? { readme: shown.name(item.readme) } : {}), description: shown.text(item.description) });
|
|
249
|
+
/** A note as the view shows it, cut of the host's secrets: its name and the one that superseded it whole; with its
|
|
250
|
+
* ETag, the one its file's GET answers, so an edit or a retire from the card names the version it shows. */
|
|
251
|
+
const noteView = ({ file, name, description, type, status, origin, superseded_by, text, oid }, shown) => ({ file: shown.name(file), name: shown.text(name), description: shown.text(description), type, status, origin, superseded_by: superseded_by === null ? null : shown.name(superseded_by), text: shown.text(text), etag: etagOf(oid) });
|
|
252
|
+
const cursorOf = (sha, offset) => Buffer.from(`${sha}.${offset}`).toString("base64url");
|
|
253
|
+
/** A page of `all`, from `offset`, at most `limit`, each shown by `view` (so only the page's are cut of secrets). */
|
|
254
|
+
const pageOf = (all, sha, offset, limit, view) => ({ items: all.slice(offset, offset + limit).map(view), total: all.length, next_cursor: offset + limit < all.length ? cursorOf(sha, offset + limit) : null });
|
|
255
|
+
/** A page's request: its limit (1 to PAGE_MAX), and the commit and offset its cursor names, a commit of the folder's. */
|
|
256
|
+
async function pageRequest(home, repo, query, fallback) {
|
|
257
|
+
const given = query.get("limit");
|
|
258
|
+
const limit = given === null ? fallback : Number(given);
|
|
259
|
+
if ((given !== null && !/^\d+$/.test(given)) || limit < 1 || limit > PAGE_MAX)
|
|
260
|
+
throw new ApiError("bad_request", `limit is an integer from 1 to ${PAGE_MAX}`);
|
|
261
|
+
const cursor = query.get("cursor");
|
|
262
|
+
if (cursor === null)
|
|
263
|
+
return { limit };
|
|
264
|
+
const named = /^([0-9a-f]{40}|[0-9a-f]{64})\.(\d{1,9})$/.exec(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
265
|
+
const known = named && (await git(home, repo, ["cat-file", "-e", `${named[1]}^{commit}`]).then(() => true, () => false));
|
|
266
|
+
if (!named || !known)
|
|
267
|
+
throw new ApiError("bad_request", "cursor is not one this server gave");
|
|
268
|
+
return { limit, at: { sha: named[1], offset: Number(named[2]) } };
|
|
269
|
+
}
|
|
270
|
+
/** GET /agents/{id}/learning: main, its index, the first page of its notes and of its log, and how the agent's runs
|
|
271
|
+
* fared and what learning changed for them (`counts`, `impact`: learning-run.ts, from the runs' rows and the learning
|
|
272
|
+
* ledger); an agent with no folder (its learning never on) has an empty one. */
|
|
273
|
+
export async function agentLearning(data, agentId, shown, counts, impact) {
|
|
274
|
+
const { home, repo } = await placeOf(data, agentId);
|
|
275
|
+
const sha = await mainOf(home, repo);
|
|
276
|
+
if (!sha)
|
|
277
|
+
return { agent: agentId, main: null, index: "", notes: EMPTY, skills: [], workflows: [], log: EMPTY, counts, impact };
|
|
278
|
+
const [{ index, notes }, { skills, workflows }, log] = await Promise.all([notesAt(home, repo, sha), learnedAt(home, repo, sha), logPage(home, repo, sha, 0, LOG_PAGE, shown)]);
|
|
279
|
+
return { agent: agentId, main: sha, index: shown.text(index), notes: pageOf(notes, sha, 0, NOTES_PAGE, (note) => noteView(note, shown)), skills: skills.map((item) => learnedView(item, shown)), workflows: workflows.map((item) => learnedView(item, shown)), log, counts, impact };
|
|
280
|
+
}
|
|
281
|
+
/** GET /agents/{id}/learning/notes?cursor=&limit=&status=: a page of the notes, ordered as the view's, from what the
|
|
282
|
+
* commit's first read kept. */
|
|
283
|
+
export async function learningNotes(data, agentId, query, shown) {
|
|
284
|
+
const status = query.get("status");
|
|
285
|
+
if (status !== null && !NOTE_STATUSES.includes(status))
|
|
286
|
+
throw new ApiError("bad_request", `status is one of ${NOTE_STATUSES.join(", ")}`);
|
|
287
|
+
const { home, repo } = await placeOf(data, agentId);
|
|
288
|
+
const { limit, at } = await pageRequest(home, repo, query, NOTES_PAGE);
|
|
289
|
+
const sha = at?.sha ?? (await mainOf(home, repo));
|
|
290
|
+
if (!sha)
|
|
291
|
+
return EMPTY;
|
|
292
|
+
const { notes } = await notesAt(home, repo, sha);
|
|
293
|
+
return pageOf(status === null ? notes : notes.filter((note) => note.status === status), sha, at?.offset ?? 0, limit, (note) => noteView(note, shown));
|
|
294
|
+
}
|
|
295
|
+
/** GET /agents/{id}/learning/log?cursor=&limit=: a page of the changes on main, newest first, reading only its own. */
|
|
296
|
+
export async function learningLog(data, agentId, query, shown) {
|
|
297
|
+
const { home, repo } = await placeOf(data, agentId);
|
|
298
|
+
const { limit, at } = await pageRequest(home, repo, query, LOG_PAGE);
|
|
299
|
+
const sha = at?.sha ?? (await mainOf(home, repo));
|
|
300
|
+
if (!sha)
|
|
301
|
+
return EMPTY;
|
|
302
|
+
return logPage(home, repo, sha, at?.offset ?? 0, limit, shown);
|
|
303
|
+
}
|
|
304
|
+
/** The file a route names, decoded, for its `use`: a note's name; for a read MEMORY.md too, and a skill's SKILL.md or a
|
|
305
|
+
* draft's workflow.json or README.md (`skills/<name>/SKILL.md`, percent-encoded); for an approval a skill's SKILL.md or
|
|
306
|
+
* a draft's README.md, the file that says it waits. Anything else is 400. The name is never echoed. */
|
|
307
|
+
function fileOf(raw, use) {
|
|
308
|
+
let file;
|
|
309
|
+
try {
|
|
310
|
+
file = decodeURIComponent(raw);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
throw new ApiError("bad_request", "the file name is not percent-encoded right");
|
|
314
|
+
}
|
|
315
|
+
const place = learnedPlace(file);
|
|
316
|
+
if (place) {
|
|
317
|
+
if (!learnedName(place.kind, place.name))
|
|
318
|
+
throw new ApiError("bad_request", "A skill's folder is named with lowercase letters, digits and single dashes, a workflow's with lowercase letters, digits, dashes and underscores.");
|
|
319
|
+
if (use === "write")
|
|
320
|
+
throw new ApiError("bad_request", "A skill or a workflow is changed by a run's learning, approved by its owner, or retired: a person edits and creates notes.");
|
|
321
|
+
if (use === "approve" && place.kind === "workflow")
|
|
322
|
+
throw new ApiError("bad_request", "A workflow is approved by its README.md, the file that says it waits.");
|
|
323
|
+
if (use === "retire" && place.kind === "workflow")
|
|
324
|
+
throw new ApiError("bad_request", "A workflow is retired by its README.md, the file that says whether it is in use.");
|
|
325
|
+
return file;
|
|
326
|
+
}
|
|
327
|
+
if (file === INDEX_FILE && use !== "read")
|
|
328
|
+
throw new ApiError("bad_request", "MEMORY.md is built by the server from the active notes, one line each, and is never written: edit, create or retire a note instead.");
|
|
329
|
+
if (file !== INDEX_FILE && !NOTE_FILE.test(file))
|
|
330
|
+
throw new ApiError("bad_request", "A learning file is a note's name at the folder's top: letters, digits, dots, dashes and underscores, starting with a letter or digit, ending .md.");
|
|
331
|
+
return file;
|
|
332
|
+
}
|
|
333
|
+
/** GET /agents/{id}/learning/files/{file}: the file on main as text, its ETag, and its type (a draft's workflow.json is
|
|
334
|
+
* JSON). */
|
|
335
|
+
export async function readNote(data, agentId, raw, shown) {
|
|
336
|
+
const file = fileOf(raw, "read");
|
|
337
|
+
const { home, repo } = await placeOf(data, agentId);
|
|
338
|
+
const sha = await mainOf(home, repo);
|
|
339
|
+
const found = sha ? await fileAt(home, repo, sha, file) : undefined;
|
|
340
|
+
if (!found)
|
|
341
|
+
throw new ApiError("not_found", "the agent's learning folder has no such file on main");
|
|
342
|
+
return { text: shown.text(found.text), etag: etagOf(found.oid), ...(file.endsWith(".json") ? { type: "application/json; charset=utf-8" } : {}) };
|
|
343
|
+
}
|
|
344
|
+
/** A note (or a skill's or draft's file) as a text answer: its ETag, an explicit type (markdown unless it names one),
|
|
345
|
+
* nosniff, and a sandbox on whatever opens it. */
|
|
346
|
+
export function sendNote(res, status, note, headers = {}) {
|
|
347
|
+
res.writeHead(status, { "content-type": note.type ?? "text/markdown; charset=utf-8", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-security-policy": "sandbox", etag: note.etag, ...headers });
|
|
348
|
+
res.end(note.text);
|
|
349
|
+
}
|
|
350
|
+
/** A PUT's body, read to its end (over `max` bytes is 413): the note's whole text, as `text/markdown` or `text/plain`, or
|
|
351
|
+
* as `application/json` `{text}`, the one form the console's page may send under its session (page.ts: a write from
|
|
352
|
+
* the page is JSON from its own origin). A JSON body that is not an object is 400; one whose `text` is missing or not
|
|
353
|
+
* text, or with another field, is 422 by field, as every JSON body here. */
|
|
354
|
+
export async function noteBody(req, max) {
|
|
355
|
+
const type = String(req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
|
|
356
|
+
const json = type === "application/json";
|
|
357
|
+
if (!json && type !== "text/markdown" && type !== "text/plain")
|
|
358
|
+
throw new ApiError("unsupported_media_type", "the body is the note's whole text, front matter included: text/markdown or text/plain, or application/json {text}");
|
|
359
|
+
const chunks = [];
|
|
360
|
+
let size = 0;
|
|
361
|
+
for await (const chunk of req) {
|
|
362
|
+
size += chunk.length;
|
|
363
|
+
if (size <= max)
|
|
364
|
+
chunks.push(chunk);
|
|
365
|
+
}
|
|
366
|
+
if (size > max)
|
|
367
|
+
throw new ApiError("payload_too_large", `the body is over ${max} bytes`, { details: { limit: "max_body_bytes" } });
|
|
368
|
+
if (!json)
|
|
369
|
+
return Buffer.concat(chunks);
|
|
370
|
+
let value;
|
|
371
|
+
try {
|
|
372
|
+
value = JSON.parse(Buffer.concat(chunks).toString("utf8") || "null");
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
throw new ApiError("bad_request", "the body is not JSON");
|
|
376
|
+
}
|
|
377
|
+
if (!isObject(value))
|
|
378
|
+
throw new ApiError("bad_request", "the body is not a JSON object");
|
|
379
|
+
const issues = Object.keys(value).filter((key) => key !== "text").map((key) => ({ field: key, reason: "not_allowed", message: `The body keeps no field ${key}.` }));
|
|
380
|
+
// A lone surrogate is no text: UTF-8 would carry it as U+FFFD, a note other than the one sent.
|
|
381
|
+
if (typeof value.text !== "string" || /\p{Cs}/u.test(value.text))
|
|
382
|
+
issues.push({ field: "text", reason: value.text === undefined ? "missing" : "wrong_type", message: "text is the note's whole text, front matter included" });
|
|
383
|
+
if (issues.length)
|
|
384
|
+
throw invalid(issues);
|
|
385
|
+
return Buffer.from(value.text, "utf8");
|
|
386
|
+
}
|
|
387
|
+
const refused = (problems) => new ApiError("bad_request", `The note does not pass the checks: ${[...new Set(problems.map((problem) => problem.rule))].join(", ")}.`, { problems });
|
|
388
|
+
/** What a write's headers ask (RFC 9110 13.1): If-Match, the ETags of the note as GET answered it, or for a PUT
|
|
389
|
+
* If-None-Match: *, only if the name is not taken. Neither, or If-Match: *, which names no version read, is 428. */
|
|
390
|
+
function conditionOf(ifMatch, ifNoneMatch, put) {
|
|
391
|
+
const match = ifMatch?.split(",").map((tag) => tag.trim()).filter(Boolean);
|
|
392
|
+
const absent = put && ifNoneMatch?.trim() === "*";
|
|
393
|
+
if (match?.includes("*"))
|
|
394
|
+
throw new ApiError("precondition_required", "If-Match: * names no version: send the note's ETag, as GET answered it.");
|
|
395
|
+
if (!match?.length && !absent)
|
|
396
|
+
throw new ApiError("precondition_required", put ? "A write names the version it read: If-Match with the note's ETag to edit it, or If-None-Match: * to create it." : "A retire names the version it read: If-Match with the note's ETag.");
|
|
397
|
+
return { ...(match?.length ? { match } : {}), absent };
|
|
398
|
+
}
|
|
399
|
+
/** PUT /agents/{id}/learning/files/{file} (`body`, the note's whole text), or POST .../retire or .../approve (`approve`;
|
|
400
|
+
* no body), as a person: the precondition, then the checks (a retire's and an approve's, the note's format alone: never
|
|
401
|
+
* its secrets), then one commit on main in the agent's queue, on the folder agentFolder checked: the note, and MEMORY.md
|
|
402
|
+
* rebuilt from main's notes with it, its message `learning: <edited|created|retired|approved> by a person: <file>` and
|
|
403
|
+
* a `Changed-By: user` trailer (and `Approved-Via: console` on an approval), main moved
|
|
404
|
+
* only from the commit it was made on (once more on a main that moved meanwhile), then the checked-out files. A note
|
|
405
|
+
* the checks refuse is never written to git. A retire of a note that is not active, and an edit that changes nothing,
|
|
406
|
+
* commit nothing. `refuse`: the host's secrets. */
|
|
407
|
+
export async function writeNote(data, agentId, raw, input) {
|
|
408
|
+
const file = fileOf(raw, input.approve ? "approve" : input.body === undefined ? "retire" : "write");
|
|
409
|
+
// A skill's SKILL.md or a draft's README.md: only ever approved or retired here.
|
|
410
|
+
const learned = learnedPlace(file);
|
|
411
|
+
const condition = conditionOf(input.ifMatch, input.ifNoneMatch, input.body !== undefined);
|
|
412
|
+
let given;
|
|
413
|
+
if (input.body !== undefined) {
|
|
414
|
+
const { problems, note } = checkNote(file, input.body, input.refuse);
|
|
415
|
+
if (!note)
|
|
416
|
+
throw refused(problems);
|
|
417
|
+
given = note.text;
|
|
418
|
+
}
|
|
419
|
+
const home = homeOf(data, agentId);
|
|
420
|
+
return withAgentRepo(data, agentId, async () => {
|
|
421
|
+
// The folder through agentFolder, as a run's merge reaches it: a link at the agent's home, its learning/ or its
|
|
422
|
+
// .git is refused (an error, nothing written), never followed. `check` checks again once a create has made .git.
|
|
423
|
+
const check = () => agentFolder(data, agentId);
|
|
424
|
+
const repo = await check();
|
|
425
|
+
for (let tries = 0;; tries++) {
|
|
426
|
+
const main = await mainOf(home, repo);
|
|
427
|
+
const current = main ? await fileAt(home, repo, main, file) : undefined;
|
|
428
|
+
// A file main holds by this name that is no note (another mode, over FILE_CAP, not UTF-8) is never written over:
|
|
429
|
+
// a create of the name is refused, and an edit or a retire gives no hint to create it.
|
|
430
|
+
const held = current !== undefined || (main !== undefined && (await heldAt(home, repo, main, file)));
|
|
431
|
+
const notNote = "The folder's file by this name on main is no note (not a regular UTF-8 file of at most 1 MiB), and a person's write never replaces it.";
|
|
432
|
+
if (condition.match && !(current && condition.match.includes(etagOf(current.oid))))
|
|
433
|
+
throw new ApiError("precondition_failed", current ? "The note changed since it was read (a run's merge, or another edit): read it again." : held ? notNote : "There is no such note on main: create it with If-None-Match: *.");
|
|
434
|
+
if (condition.absent && held)
|
|
435
|
+
throw new ApiError("precondition_failed", current ? "The folder has a note by this name: read it, then edit it with If-Match." : notNote);
|
|
436
|
+
// A note whose text holds one of the host's secrets as they are now (a value made secret after it was written) is
|
|
437
|
+
// read cut of it, under its own ETag: an edit of what was shown would write the cut over the hidden text. Only a
|
|
438
|
+
// retire reaches it.
|
|
439
|
+
if (given !== undefined && current && secretsShown(input.refuse).holds(current.text)) {
|
|
440
|
+
throw refused([{ rule: "secret_value", path: file, detail: "This note holds a value the server now keeps secret, so its text was shown with that value hidden, and saving would replace the hidden text. Retire it and write a new note instead." }]);
|
|
441
|
+
}
|
|
442
|
+
let text = given;
|
|
443
|
+
// A note that waits for its owner's OK is made active by an approval alone: an edit keeps it waiting, so one that
|
|
444
|
+
// drops or changes its status is refused, whoever sends it.
|
|
445
|
+
if (given !== undefined && current) {
|
|
446
|
+
const was = parseNoteFile(file, current.text);
|
|
447
|
+
const now = parseNoteFile(file, given);
|
|
448
|
+
if (!Array.isArray(was) && was.status === "pending" && !Array.isArray(now) && now.status !== "pending")
|
|
449
|
+
throw refused([printable({ rule: "status", path: file, detail: "it waits for its owner's OK: an edit keeps status: pending, only an approval makes it active, and a retire takes it out" }, input.refuse)]);
|
|
450
|
+
}
|
|
451
|
+
// Beside the note itself: what an approve marks of the notes the approved one supersedes.
|
|
452
|
+
const also = new Map();
|
|
453
|
+
const notes = main ? (await readAt(home, repo, main)).notes : new Map();
|
|
454
|
+
if (text === undefined && learned && !input.approve) {
|
|
455
|
+
// Retired, as a note is: no later run is given it. One already retired is answered as it is; nothing else in
|
|
456
|
+
// the folder changes.
|
|
457
|
+
if (learnedStatus(current.text) === "retired")
|
|
458
|
+
return { status: 200, file, text: current.text, etag: etagOf(current.oid) };
|
|
459
|
+
text = retiredLearned(current.text);
|
|
460
|
+
}
|
|
461
|
+
else if (text === undefined && learned) {
|
|
462
|
+
// Approved, it is no longer held: given to every later run. Nothing else in the folder changes.
|
|
463
|
+
if (!isHeld(current.text))
|
|
464
|
+
throw new ApiError("bad_request", `The ${learned.kind === "skill" ? "skill" : "workflow"} is not waiting for an OK: it is ${learnedStatus(current.text)}.`);
|
|
465
|
+
text = released(current.text);
|
|
466
|
+
}
|
|
467
|
+
else if (text === undefined && input.approve) {
|
|
468
|
+
const note = parseNoteFile(file, current.text);
|
|
469
|
+
if (Array.isArray(note))
|
|
470
|
+
throw refused(note.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
|
|
471
|
+
if (note.status !== "pending")
|
|
472
|
+
throw new ApiError("bad_request", `The note is not waiting for an OK: it is ${note.status}.`);
|
|
473
|
+
// Approved, it is active: in the index, and every later run reads it. What it supersedes, and is active still, is
|
|
474
|
+
// superseded now, as a run's merge marks it.
|
|
475
|
+
text = approve(current.text);
|
|
476
|
+
for (const old of note.supersedes)
|
|
477
|
+
if (notes.get(old)?.status === "active")
|
|
478
|
+
also.set(old, supersede(notes.get(old).text, file));
|
|
479
|
+
}
|
|
480
|
+
else if (text === undefined) {
|
|
481
|
+
const note = parseNoteFile(file, current.text);
|
|
482
|
+
if (Array.isArray(note))
|
|
483
|
+
throw refused(note.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
|
|
484
|
+
// A pending note is retired too: a person who will never approve it takes it out of the folder's waiting list.
|
|
485
|
+
if (note.status !== "active" && note.status !== "pending")
|
|
486
|
+
return { status: 200, file, text: current.text, etag: etagOf(current.oid) };
|
|
487
|
+
// A retire is how a person takes a note out of every later run's prompt, a leaking one above all, so it always
|
|
488
|
+
// can: only the note's format is checked as retired (its front matter parses, and it fits the note cap with the
|
|
489
|
+
// status line added), never a secret in its name or text. Every answer cuts those as any read does.
|
|
490
|
+
text = retire(current.text);
|
|
491
|
+
const retired = parseNoteFile(file, text);
|
|
492
|
+
if (Array.isArray(retired))
|
|
493
|
+
throw refused(retired.map((detail) => printable({ rule: "note", path: file, detail }, input.refuse)));
|
|
494
|
+
const size = Buffer.byteLength(text);
|
|
495
|
+
if (size > CAPS.note + RETIRED_LINE)
|
|
496
|
+
throw refused([printable({ rule: "too_large", path: file, detail: `${size} bytes as retired; the cap is ${CAPS.note}, and the status line a retire adds` }, input.refuse)]);
|
|
497
|
+
}
|
|
498
|
+
if (current && text === current.text)
|
|
499
|
+
return { status: 200, file, text, etag: etagOf(current.oid) };
|
|
500
|
+
const after = learned ? [...notes.values()] : [...[...notes.values()].filter((note) => note.file !== file && !also.has(note.file)), parseNoteFile(file, text), ...[...also].map(([old, marked]) => parseNoteFile(old, marked))];
|
|
501
|
+
const lines = after.filter((note) => note.status === "active").length;
|
|
502
|
+
if (lines > INDEX_LINES)
|
|
503
|
+
throw refused([{ rule: "index_full", detail: `the index would hold ${lines} lines; it holds at most ${INDEX_LINES}, so retire a note first` }]);
|
|
504
|
+
const parent = main ?? (await openAgentRepo(home, repo, check));
|
|
505
|
+
const subject = `learning: ${input.approve ? "approved" : given === undefined ? "retired" : current ? "edited" : "created"} by a person: ${file}`;
|
|
506
|
+
const env = { GIT_INDEX_FILE: join(repo, ".git", "person.index") };
|
|
507
|
+
let commit;
|
|
508
|
+
let oid;
|
|
509
|
+
try {
|
|
510
|
+
await rm(env.GIT_INDEX_FILE, { force: true });
|
|
511
|
+
await git(home, repo, ["read-tree", parent], "", env);
|
|
512
|
+
oid = line(await git(home, repo, ["hash-object", "-w", "--no-filters", "--stdin"], text));
|
|
513
|
+
const index = line(await git(home, repo, ["hash-object", "-w", "--no-filters", "--stdin"], buildIndex(after)));
|
|
514
|
+
let entries = `100644 ${oid}\t${file}\x00100644 ${index}\t${INDEX_FILE}\x00`;
|
|
515
|
+
for (const [old, marked] of also)
|
|
516
|
+
entries += `100644 ${line(await git(home, repo, ["hash-object", "-w", "--no-filters", "--stdin"], marked))}\t${old}\x00`;
|
|
517
|
+
await git(home, repo, ["update-index", "-z", "--index-info"], entries, env);
|
|
518
|
+
const tree = line(await git(home, repo, ["write-tree"], "", env));
|
|
519
|
+
// Who approved, and how, in the trailers; the commit's own date is when. Never the note's text.
|
|
520
|
+
const trailers = input.approve ? `${BY_USER}\n${APPROVED_VIA}` : BY_USER;
|
|
521
|
+
commit = line(await git(home, repo, ["commit-tree", tree, "-p", parent, "-m", subject, "-m", trailers]));
|
|
522
|
+
}
|
|
523
|
+
finally {
|
|
524
|
+
await rm(env.GIT_INDEX_FILE, { force: true });
|
|
525
|
+
}
|
|
526
|
+
try {
|
|
527
|
+
await git(home, repo, ["update-ref", "-m", subject, "refs/heads/main", commit, parent]);
|
|
528
|
+
}
|
|
529
|
+
catch (error) {
|
|
530
|
+
// Lost to a write since main was read: the precondition asked again of the main that won, never forced over it.
|
|
531
|
+
if (tries === 0 && (await mainOf(home, repo)) !== parent)
|
|
532
|
+
continue;
|
|
533
|
+
throw error;
|
|
534
|
+
}
|
|
535
|
+
const failed = await checkOut(repo, commit);
|
|
536
|
+
if (failed)
|
|
537
|
+
process.stderr.write(`agentrun-serve: the agent ${agentId}'s learning files are not main's: ${failed.message}\n`);
|
|
538
|
+
return { status: current ? 200 : 201, file, text, etag: etagOf(oid) };
|
|
539
|
+
}
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
/** GET /runs/{id}/learning: the run's learning whole, or null for a run that does not learn: its detail cut of the
|
|
543
|
+
* host's secrets now, and the notes it read and learned as its view shows them (learning.ts notesView). */
|
|
544
|
+
export async function runLearning(run, shown, secrets) {
|
|
545
|
+
const learning = run.meta.learning;
|
|
546
|
+
if (!learning)
|
|
547
|
+
return null;
|
|
548
|
+
const pin = await readPin(run.dir).catch(() => undefined);
|
|
549
|
+
const { state, reason, at, verdict, problems, merged, cost_usd, tokens, pending } = learning;
|
|
550
|
+
return {
|
|
551
|
+
run: run.id, state, reason, detail: detailShown(learning, shown), at,
|
|
552
|
+
// Once it settled (a run that runs again for a follow-up is still reading).
|
|
553
|
+
...notesView(learning, shown, run.settled),
|
|
554
|
+
seed: pin?.seed ?? null,
|
|
555
|
+
merged: merged ?? null,
|
|
556
|
+
// The merge's notes that wait for a person's OK: on main as `status: pending`, read by no run until approved.
|
|
557
|
+
pending: (pending ?? []).map(({ file, name }) => ({ file: shown.name(file), name: shown.text(name) })),
|
|
558
|
+
// The grader's, with its item for each new note: a name holding one of the host's secrets reads [redacted], and
|
|
559
|
+
// each text is cut of them.
|
|
560
|
+
verdict: verdict ? { merge: verdict.merge, reason: shown.text(verdict.reason), items: (verdict.items ?? []).map(({ file, keep, pending: waits, origin, question, why }) => ({ file: shown.name(file), keep, ...(waits ? { pending: true } : {}), ...(origin ? { origin } : {}), ...(question ? { question: shown.text(question) } : {}), why: shown.text(why) })) } : null,
|
|
561
|
+
problems: (problems ?? []).map((problem) => printable(problem, secrets)),
|
|
562
|
+
// The grade's alone: the end-of-run turn's cost is in the run's own totals.
|
|
563
|
+
cost_usd: { grade: cost_usd?.grade ?? null },
|
|
564
|
+
tokens: { grade: tokens?.grade ?? null },
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
/** `text`, an added file, as git's unified diff writes it, hunks only. */
|
|
568
|
+
function addedPatch(text) {
|
|
569
|
+
if (!text)
|
|
570
|
+
return "";
|
|
571
|
+
const lines = text.split("\n");
|
|
572
|
+
const last = lines.pop();
|
|
573
|
+
const added = [...lines.map((one) => `+${one}\n`), ...(last ? [`+${last}\n\\n`] : [])];
|
|
574
|
+
return `@@ -0,0 +1${added.length === 1 ? "" : `,${added.length}`} @@\n${added.join("")}`;
|
|
575
|
+
}
|
|
576
|
+
/** GET /runs/{id}/learning/diff: once merged, its merge commit against its parent, as git diffs them; before, its proposal
|
|
577
|
+
* (new notes only) against its seed; a run that proposed nothing, no file. A file's patch is withheld when too large, or
|
|
578
|
+
* when it holds one of the host's secrets now. */
|
|
579
|
+
export async function runDiff(data, run, shown) {
|
|
580
|
+
const learning = run.meta.learning;
|
|
581
|
+
if (!learning)
|
|
582
|
+
throw new ApiError("not_found", "the run does not learn, so it proposed nothing");
|
|
583
|
+
const file = (name, status, patch) => {
|
|
584
|
+
const path = shown.name(name);
|
|
585
|
+
return Buffer.byteLength(patch) > PATCH_CAP ? { path, status, withheld: "too_large" } : shown.holds(patch) ? { path, status, withheld: "secret" } : { path, status, patch };
|
|
586
|
+
};
|
|
587
|
+
if (learning.merged) {
|
|
588
|
+
const { home, repo } = await placeOf(data, run.agentId);
|
|
589
|
+
const head = learning.merged;
|
|
590
|
+
const base = /^[0-9a-f]{40,64}$/.test(head) ? await git(home, repo, ["rev-parse", "--verify", "--quiet", `${head}^1`]).then(line, () => undefined) : undefined;
|
|
591
|
+
if (!base)
|
|
592
|
+
throw new ApiError("not_found", "the run's merge is not in its agent's learning folder");
|
|
593
|
+
const diff = ["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--no-color"];
|
|
594
|
+
const listed = (await git(home, repo, [...diff, "--name-status", "-z", base, head])).toString("utf8").split("\0").filter(Boolean);
|
|
595
|
+
const files = [];
|
|
596
|
+
for (let i = 0; i + 1 < listed.length; i += 2) {
|
|
597
|
+
const status = { A: "added", D: "deleted" }[listed[i][0]] ?? "modified";
|
|
598
|
+
const raw = (await git(home, repo, [...diff, "--text", "-U3", base, head, "--", listed[i + 1]])).toString("utf8");
|
|
599
|
+
const at = raw.search(/^@@/m);
|
|
600
|
+
files.push(file(listed[i + 1], status, at < 0 ? "" : raw.slice(at)));
|
|
601
|
+
}
|
|
602
|
+
return { base, head, files };
|
|
603
|
+
}
|
|
604
|
+
const proposal = await readJson(join(run.dir, PROPOSAL));
|
|
605
|
+
const notes = isObject(proposal) && typeof proposal.seed === "string" && Array.isArray(proposal.notes) ? proposal.notes.filter((note) => isObject(note) && typeof note.file === "string" && NOTE_FILE.test(note.file) && typeof note.text === "string") : undefined;
|
|
606
|
+
if (notes)
|
|
607
|
+
return { base: proposal.seed, head: null, files: notes.map((note) => file(note.file, "added", addedPatch(note.text))) };
|
|
608
|
+
return { base: (await readPin(run.dir).catch(() => undefined))?.seed ?? null, head: null, files: [] };
|
|
609
|
+
}
|