@mnaimfaizy/agent-kit 1.0.0-beta.16 → 1.0.0-beta.17
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/README.md +2 -1
- package/package.json +1 -1
- package/src/cli.mjs +23 -6
- package/src/deep-scan/docker-driver.mjs +70 -3
- package/src/deep-scan/lifecycle.mjs +2 -2
- package/src/deep-scan/sbx-driver.mjs +34 -47
- package/src/exec.mjs +5 -1
- package/src/factory/budget/budget.mjs +2 -1
- package/src/factory/doctor/files.mjs +21 -1
- package/src/factory/doctor/local.mjs +24 -8
- package/src/factory/doctor/orchestrate.mjs +14 -14
- package/src/factory/init/blueprint.mjs +9 -2
- package/src/factory/init/index.mjs +4 -3
- package/src/factory/limits/limits.mjs +8 -0
- package/src/factory/qa/command.mjs +139 -1
- package/src/factory/qa/decide.mjs +86 -0
- package/src/factory/qa/report.mjs +50 -0
- package/src/factory/review/brief.mjs +195 -0
- package/src/factory/run/command.mjs +90 -24
- package/src/factory/run/launch.mjs +25 -6
- package/src/factory/run/pipelines.mjs +467 -34
- package/src/factory/run/token.mjs +5 -3
- package/src/factory/run/worktree.mjs +160 -0
- package/src/factory/security/audit.mjs +353 -0
- package/src/factory/setup/command.mjs +80 -17
- package/src/factory/setup/reads.mjs +30 -0
- package/src/factory/setup/writes.mjs +12 -0
- package/src/factory/sweep/actions-main.mjs +5 -3
- package/src/factory/sweep/shell.mjs +7 -3
- package/src/factory/sweep/sweep-core.mjs +240 -12
- package/src/factory/tracker/github.mjs +57 -18
- package/src/stage/build.mjs +100 -0
- package/src/stage/factory-live.mjs +288 -0
- package/src/stage.mjs +81 -4
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// What the factory-mode Chief of Staff is as a Stage (ADR 0039): the build Stage's
|
|
2
|
+
// Launcher side. One Chief of Staff runs `/orchestrate --factory` in the sandbox. It reads a
|
|
3
|
+
// Snapshot the engine rewrites every pump, and writes an Outbox the engine reads live. It
|
|
4
|
+
// holds no GitHub credential and its sandbox mounts no host path (the drivers are
|
|
5
|
+
// mountless): the Snapshot is copied in read-only and re-copied as the engine rewrites it,
|
|
6
|
+
// and the Outbox is copied out to the engine's folder while the run is going
|
|
7
|
+
// (stage/factory-live.mjs). There is no Stage result file: the Outbox's `result` entry is
|
|
8
|
+
// the result, and the engine checks it.
|
|
9
|
+
|
|
10
|
+
import { routeSentence } from "./egress-route.mjs";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The harness settings and the Support Level are the implement Stage's: the Chief of Staff
|
|
14
|
+
* is the same kind of agent (it reads, plans work and starts Delegations that implement).
|
|
15
|
+
*/
|
|
16
|
+
export const STAGE = "implement";
|
|
17
|
+
|
|
18
|
+
/** This Stage takes `snapshotDir` and `outboxDir` and has no result file. */
|
|
19
|
+
export const FACTORY = true;
|
|
20
|
+
|
|
21
|
+
/** Where the sandbox holds the checkout. */
|
|
22
|
+
export const WORKSPACE = "/workspace";
|
|
23
|
+
|
|
24
|
+
export const IN_DIR = "/agent-kit/in";
|
|
25
|
+
export const BRIEF_PATH = `${IN_DIR}/brief.md`;
|
|
26
|
+
export const PROMPT_PATH = `${IN_DIR}/prompt.md`;
|
|
27
|
+
/** The newest Snapshot generation, a link the Launcher swaps; read-only to the agent. */
|
|
28
|
+
export const SNAPSHOT_PATH = "/agent-kit/snapshot";
|
|
29
|
+
/** Where the Snapshot generations are copied in (each read-only). */
|
|
30
|
+
export const SNAPSHOTS_DIR = "/agent-kit/snapshots";
|
|
31
|
+
/** The folder the agent writes its Outbox entries in. */
|
|
32
|
+
export const OUTBOX_PATH = "/agent-kit/outbox";
|
|
33
|
+
/** Only the folder of it is made; no file is read from it. */
|
|
34
|
+
export const RESULT_PATH = "/agent-kit/out/none";
|
|
35
|
+
|
|
36
|
+
export const MAX_RESULT_BYTES = 0;
|
|
37
|
+
export const RESULT_NAME = "result";
|
|
38
|
+
/** The most one Outbox file (a push's bundle) holds, and all of them together. */
|
|
39
|
+
export const MAX_OUTBOX_FILE_BYTES = 100 * 1024 * 1024;
|
|
40
|
+
export const MAX_OUTBOX_BYTES = 256 * 1024 * 1024;
|
|
41
|
+
/** The most a Snapshot holds. */
|
|
42
|
+
export const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
|
|
43
|
+
/** A Delegation's bundle (`delegations/<id>.bundle`) is counted apart, so a few of them never starve the Snapshot's facts. */
|
|
44
|
+
export const MAX_SNAPSHOT_BUNDLES_BYTES = 256 * 1024 * 1024;
|
|
45
|
+
/** How often the Snapshot is re-copied in and the Outbox copied out while the agent runs. */
|
|
46
|
+
export const PUMP_MS = 2_000;
|
|
47
|
+
|
|
48
|
+
export const LIMITS = Object.freeze({
|
|
49
|
+
setupMinutes: 20,
|
|
50
|
+
scanMinutes: 240,
|
|
51
|
+
turns: 400,
|
|
52
|
+
tokens: 80_000_000,
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
export const DOCS_PAGE = "factory/engine.md";
|
|
56
|
+
|
|
57
|
+
/** A stopped run's Outbox is read as far as it got; the engine checks it. */
|
|
58
|
+
export const markStopped = (data) => data;
|
|
59
|
+
export const stoppedNote = () => "the engine reads the Outbox as it stands";
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The brief with the engine's host folders replaced by the sandbox's own paths: the sandbox
|
|
63
|
+
* mounts no host path, so a host path in the brief names nothing the agent can reach.
|
|
64
|
+
*/
|
|
65
|
+
export function sandboxBrief(brief, { snapshotDir, outboxDir }) {
|
|
66
|
+
const named = (dir) => [...new Set([dir, dir.replaceAll("\\", "/")])];
|
|
67
|
+
let text = brief;
|
|
68
|
+
// Longest first, so one folder inside the other is not half replaced.
|
|
69
|
+
const pairs = [
|
|
70
|
+
...named(snapshotDir).map((d) => [d, SNAPSHOT_PATH]),
|
|
71
|
+
...named(outboxDir).map((d) => [d, OUTBOX_PATH]),
|
|
72
|
+
].sort((a, b) => b[0].length - a[0].length);
|
|
73
|
+
for (const [host, inside] of pairs) text = text.split(host).join(inside);
|
|
74
|
+
return text;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export const PROMPT = `Read the brief at ${BRIEF_PATH} and follow it exactly. Your Snapshot is ${SNAPSHOT_PATH} (read-only); write your Outbox entries to ${OUTBOX_PATH}.\n`;
|
|
78
|
+
|
|
79
|
+
/** The Launcher's own opening of the brief, before the engine's. */
|
|
80
|
+
export function briefPreamble(shape) {
|
|
81
|
+
const { checkoutConfig, instructionFiles } = shape;
|
|
82
|
+
const listed = (paths) => paths.map((p) => `\`${p}\``).join(", ");
|
|
83
|
+
return [
|
|
84
|
+
"# Stage brief, from the agent-kit Launcher",
|
|
85
|
+
"",
|
|
86
|
+
"You are the Chief of Staff in factory mode, inside a closed, disposable sandbox. " +
|
|
87
|
+
routeSentence(shape) +
|
|
88
|
+
", and the harness's own web and server-side tools are off. You hold no GitHub credential: the engine reads your Outbox and acts for you. Nothing you change outside the Outbox is kept.",
|
|
89
|
+
"",
|
|
90
|
+
`- The repository: \`${WORKSPACE}\`, a copy of the checked-out commit, with no \`.git\` folder.`,
|
|
91
|
+
`- Your Snapshot: \`${SNAPSHOT_PATH}\`, read-only. The engine replaces it every few seconds: read it again before you decide.`,
|
|
92
|
+
`- Your Outbox: \`${OUTBOX_PATH}\`, writable. The engine reads each file as soon as it is whole, so write a bundle before the entry that names it.`,
|
|
93
|
+
`- The harness's own config is not in the copy (${listed(checkoutConfig)}), so none of it could configure you.`,
|
|
94
|
+
`- The files the harness loads by itself (${listed(instructionFiles)}) are the trusted commit's.`,
|
|
95
|
+
"",
|
|
96
|
+
"-----",
|
|
97
|
+
"",
|
|
98
|
+
"",
|
|
99
|
+
].join("\n");
|
|
100
|
+
}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// The live link of a factory-mode Stage (stage/build.mjs): the Snapshot copied in
|
|
2
|
+
// read-only, and the Outbox copied out to the engine's folder while the agent runs.
|
|
3
|
+
//
|
|
4
|
+
// No host path is mounted into the sandbox (the drivers are mountless: a daemon with its
|
|
5
|
+
// own private /tmp could not see one), so both are copies through the driver:
|
|
6
|
+
//
|
|
7
|
+
// Snapshot every pump the host folder is read; when it changed, a new generation is
|
|
8
|
+
// copied in as root (files 0644, folders 0755, then `chmod -R a-w`) and the
|
|
9
|
+
// /agent-kit/snapshot link is swapped to it, so a reader never sees half of one.
|
|
10
|
+
// Outbox every pump the sandbox's folder is read as a tar and checked on the host
|
|
11
|
+
// (regular files with a plain name, within the caps). A file reaches the engine's
|
|
12
|
+
// folder once it has been the same for two pumps (or the run is over), the
|
|
13
|
+
// bundles before the `.json` entry that names them, by rename, so the engine
|
|
14
|
+
// never reads a half-written entry. A file is written once and never replaced.
|
|
15
|
+
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
import { mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
import { StepFailed } from "../deep-scan/steps.mjs";
|
|
20
|
+
import { tarOf } from "../deep-scan/tar.mjs";
|
|
21
|
+
import {
|
|
22
|
+
MAX_OUTBOX_BYTES,
|
|
23
|
+
MAX_OUTBOX_FILE_BYTES,
|
|
24
|
+
MAX_SNAPSHOT_BUNDLES_BYTES,
|
|
25
|
+
MAX_SNAPSHOT_BYTES,
|
|
26
|
+
OUTBOX_PATH,
|
|
27
|
+
PUMP_MS,
|
|
28
|
+
SNAPSHOT_PATH,
|
|
29
|
+
SNAPSHOTS_DIR,
|
|
30
|
+
} from "./build.mjs";
|
|
31
|
+
|
|
32
|
+
const PLAIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
33
|
+
|
|
34
|
+
/** The regular files under `dir`, as `{ path, data }` with `/` paths; null when over `max` bytes. */
|
|
35
|
+
export function readTree(dir, max = MAX_SNAPSHOT_BYTES, maxBundles = MAX_SNAPSHOT_BUNDLES_BYTES) {
|
|
36
|
+
const files = [];
|
|
37
|
+
let total = 0;
|
|
38
|
+
let bundles = 0;
|
|
39
|
+
const walk = (rel) => {
|
|
40
|
+
for (const entry of readdirSync(join(dir, rel), { withFileTypes: true })) {
|
|
41
|
+
const path = rel ? `${rel}/${entry.name}` : entry.name;
|
|
42
|
+
if (entry.isDirectory()) walk(path);
|
|
43
|
+
else if (entry.isFile()) {
|
|
44
|
+
const data = readFileSync(join(dir, path));
|
|
45
|
+
// A Delegation's bundle has a cap of its own.
|
|
46
|
+
if (/^delegations\/[^/]+\.bundle$/.test(path)) bundles += data.length;
|
|
47
|
+
else total += data.length;
|
|
48
|
+
if (total > max || bundles > maxBundles) throw new RangeError("snapshot too large");
|
|
49
|
+
files.push({ path, data });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
try {
|
|
54
|
+
walk("");
|
|
55
|
+
} catch (e) {
|
|
56
|
+
if (e instanceof RangeError) return null;
|
|
57
|
+
throw e;
|
|
58
|
+
}
|
|
59
|
+
return files.sort((a, b) => (a.path < b.path ? -1 : 1));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const digestOf = (files) => {
|
|
63
|
+
const h = createHash("sha256");
|
|
64
|
+
for (const { path, data } of files) h.update(`${path}\0${data.length}\0`).update(data);
|
|
65
|
+
return h.digest("hex");
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** The tar of one Snapshot generation under SNAPSHOTS_DIR, as root writes it. */
|
|
69
|
+
export function snapshotTar(files, generation) {
|
|
70
|
+
const base = `${SNAPSHOTS_DIR.slice(1)}/${generation}`;
|
|
71
|
+
const dirs = new Set();
|
|
72
|
+
for (const { path } of files) {
|
|
73
|
+
const parts = path.split("/").slice(0, -1);
|
|
74
|
+
for (let i = 1; i <= parts.length; i++) dirs.add(parts.slice(0, i).join("/"));
|
|
75
|
+
}
|
|
76
|
+
return tarOf([
|
|
77
|
+
{ path: "agent-kit", dir: true },
|
|
78
|
+
{ path: SNAPSHOTS_DIR.slice(1), dir: true },
|
|
79
|
+
{ path: base, dir: true },
|
|
80
|
+
...[...dirs].sort().map((d) => ({ path: `${base}/${d}`, dir: true })),
|
|
81
|
+
...files.map(({ path, data }) => ({ path: `${base}/${path}`, data })),
|
|
82
|
+
]);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The flat regular files of a tar the sandbox wrote: `{ files, refused }`, each refused as
|
|
87
|
+
* `{ name, why }`. A link, a folder below the top, a name that is not plain, or a file over the cap is refused, never read.
|
|
88
|
+
*/
|
|
89
|
+
export function outboxFiles(archive, delivered = new Set()) {
|
|
90
|
+
const files = [];
|
|
91
|
+
const refused = [];
|
|
92
|
+
let total = 0;
|
|
93
|
+
const field = (h, s, l) =>
|
|
94
|
+
h
|
|
95
|
+
.subarray(s, s + l)
|
|
96
|
+
.toString("utf8")
|
|
97
|
+
.replace(/\0.*$/s, "");
|
|
98
|
+
for (let o = 0; o + 512 <= archive.length;) {
|
|
99
|
+
const h = archive.subarray(o, o + 512);
|
|
100
|
+
if (h.every((b) => b === 0)) break;
|
|
101
|
+
const size = Number.parseInt(field(h, 124, 12).trim() || "0", 8);
|
|
102
|
+
const type = field(h, 156, 1) || "0";
|
|
103
|
+
const prefix = field(h, 345, 155);
|
|
104
|
+
const raw = prefix ? `${prefix}/${field(h, 0, 100)}` : field(h, 0, 100);
|
|
105
|
+
const name = raw.replace(/^\.\//, "");
|
|
106
|
+
o += 512;
|
|
107
|
+
const data = archive.subarray(o, o + size);
|
|
108
|
+
o += Math.ceil(size / 512) * 512;
|
|
109
|
+
if (type === "x" || type === "g" || name === "" || name === "." || name === "./") continue;
|
|
110
|
+
if (type === "5" && !name.includes("/")) continue;
|
|
111
|
+
if (type !== "0" || !PLAIN_NAME.test(name)) {
|
|
112
|
+
refused.push({ name, why: "not a plain file" });
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
// Already on the host: it counts toward no cap.
|
|
116
|
+
if (delivered.has(name)) continue;
|
|
117
|
+
// Over the per-file cap: refused for good (`forever`), and it counts toward nothing, so it
|
|
118
|
+
// cannot push later files over the total. Over the total: refused for now only.
|
|
119
|
+
if (size > MAX_OUTBOX_FILE_BYTES) {
|
|
120
|
+
refused.push({ name, why: "cap", forever: true });
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (total + size > MAX_OUTBOX_BYTES) {
|
|
124
|
+
refused.push({ name, why: "cap" });
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
total += size;
|
|
128
|
+
files.push({ name, data: Buffer.from(data) });
|
|
129
|
+
}
|
|
130
|
+
return { files, refused };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The live link for one run.
|
|
135
|
+
* @param {{
|
|
136
|
+
* driver: import("../deep-scan/lifecycle.mjs").Driver,
|
|
137
|
+
* snapshotDir: string,
|
|
138
|
+
* outboxDir: string,
|
|
139
|
+
* timers: { setTimeout: Function, clearTimeout: Function },
|
|
140
|
+
* pumpMs?: number,
|
|
141
|
+
* out: (line: string) => void,
|
|
142
|
+
* }} deps
|
|
143
|
+
*/
|
|
144
|
+
export function createLiveLink({ driver, snapshotDir, outboxDir, timers, pumpMs = PUMP_MS, out }) {
|
|
145
|
+
let generation = 0;
|
|
146
|
+
let lastDigest = null;
|
|
147
|
+
const written = new Set();
|
|
148
|
+
// Refused for size for good: left out of every later read, as delivered files are.
|
|
149
|
+
const tooBig = new Set();
|
|
150
|
+
const lastSeen = new Map();
|
|
151
|
+
let timer = null;
|
|
152
|
+
let running = Promise.resolve();
|
|
153
|
+
let stopped = false;
|
|
154
|
+
// Once per distinct reason, so a later, different problem is never silent.
|
|
155
|
+
const warned = new Set();
|
|
156
|
+
const refusedWhy = new Set();
|
|
157
|
+
const warn = (what) => {
|
|
158
|
+
if (warned.has(what)) return;
|
|
159
|
+
warned.add(what);
|
|
160
|
+
out(`Live link: ${what}; the engine reads what has come out.`);
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Copy the host's Snapshot in as a new read-only generation, when it changed. Returns whether
|
|
165
|
+
* a generation is in place (this one, or the last one when nothing changed or this one failed).
|
|
166
|
+
*/
|
|
167
|
+
async function syncSnapshot() {
|
|
168
|
+
const files = readTree(snapshotDir);
|
|
169
|
+
if (files === null) {
|
|
170
|
+
warn(
|
|
171
|
+
"the Snapshot is over the size cap, so the Chief of Staff keeps reading the last one it has",
|
|
172
|
+
);
|
|
173
|
+
return lastDigest !== null;
|
|
174
|
+
}
|
|
175
|
+
const digest = digestOf(files);
|
|
176
|
+
if (digest === lastDigest) return true;
|
|
177
|
+
generation += 1;
|
|
178
|
+
const dir = `${SNAPSHOTS_DIR}/${generation}`;
|
|
179
|
+
await driver.copyIn(snapshotTar(files, generation), "copying the Snapshot in", {
|
|
180
|
+
loosen: false,
|
|
181
|
+
});
|
|
182
|
+
// As root: the generation is root's, and a driver's own copy step may have loosened modes.
|
|
183
|
+
const made = await driver.exec(
|
|
184
|
+
`chown -R root:root ${SNAPSHOTS_DIR} && chmod 0755 ${SNAPSHOTS_DIR} && chmod 1777 /agent-kit && chmod -R a-w,a+rX ${dir}` +
|
|
185
|
+
` && chmod 1777 ${OUTBOX_PATH} && ln -sfn ${dir} ${SNAPSHOT_PATH}` +
|
|
186
|
+
` && for old in ${SNAPSHOTS_DIR}/*; do [ "$old" = ${dir} ] || { chmod -R u+w "$old"; rm -rf "$old"; }; done`,
|
|
187
|
+
{ workdir: null, user: "root" },
|
|
188
|
+
);
|
|
189
|
+
if (made.status !== 0) {
|
|
190
|
+
warn("the Snapshot could not be put in place");
|
|
191
|
+
return lastDigest !== null;
|
|
192
|
+
}
|
|
193
|
+
lastDigest = digest;
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Copy new Outbox files out; `final` writes every file, stable or not. */
|
|
198
|
+
async function syncOutbox(final) {
|
|
199
|
+
// Delivered files are left out of the read, so the caps count what is still to come.
|
|
200
|
+
const skip = [...written, ...tooBig].map((name) => ` --exclude=${name}`).join("");
|
|
201
|
+
const taken = await driver.carryOut(`tar -c -f - -C ${OUTBOX_PATH}${skip} .`, {
|
|
202
|
+
maxBytes: MAX_OUTBOX_BYTES + 1024 * 1024,
|
|
203
|
+
});
|
|
204
|
+
if ("error" in taken) return warn(`the Outbox could not be read (${taken.error})`);
|
|
205
|
+
const { files, refused } = outboxFiles(taken.data, written);
|
|
206
|
+
for (const r of refused) if (r.forever) tooBig.add(r.name);
|
|
207
|
+
const reasons = {
|
|
208
|
+
cap: `over the Outbox cap (${MAX_OUTBOX_FILE_BYTES} bytes a file, ${MAX_OUTBOX_BYTES} in all)`,
|
|
209
|
+
"not a plain file": "not a plain file",
|
|
210
|
+
};
|
|
211
|
+
for (const why of Object.keys(reasons)) {
|
|
212
|
+
const names = refused.filter((r) => r.why === why).map((r) => r.name);
|
|
213
|
+
// Keyed by the reason alone, so a changing list of names does not repeat the line.
|
|
214
|
+
if (names.length && !refusedWhy.has(why)) {
|
|
215
|
+
refusedWhy.add(why);
|
|
216
|
+
warn(`Outbox entries refused, ${reasons[why]}: ${names.join(", ")}`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const ready = files.filter(({ name, data }) => {
|
|
220
|
+
if (written.has(name)) return false;
|
|
221
|
+
const digest = createHash("sha256").update(data).digest("hex");
|
|
222
|
+
const same = lastSeen.get(name) === digest;
|
|
223
|
+
lastSeen.set(name, digest);
|
|
224
|
+
return final || same;
|
|
225
|
+
});
|
|
226
|
+
// A bundle (anything that is not an entry) before the entry that names it.
|
|
227
|
+
ready.sort((a, b) => Number(a.name.endsWith(".json")) - Number(b.name.endsWith(".json")));
|
|
228
|
+
for (const { name, data } of ready) {
|
|
229
|
+
const temp = join(outboxDir, `.${name}.tmp`);
|
|
230
|
+
writeFileSync(temp, data, { mode: 0o600 });
|
|
231
|
+
renameSync(temp, join(outboxDir, name));
|
|
232
|
+
written.add(name);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const pump = async () => {
|
|
237
|
+
try {
|
|
238
|
+
await syncSnapshot();
|
|
239
|
+
await syncOutbox(false);
|
|
240
|
+
} catch (e) {
|
|
241
|
+
warn(`a pump failed (${e?.message ?? e})`);
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
const schedule = () => {
|
|
245
|
+
if (stopped) return;
|
|
246
|
+
timer = timers.setTimeout(() => {
|
|
247
|
+
running = pump().then(schedule);
|
|
248
|
+
}, pumpMs);
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
/** The Outbox folder and the first Snapshot, before the agent starts. */
|
|
253
|
+
async prepare() {
|
|
254
|
+
mkdirSync(outboxDir, { recursive: true });
|
|
255
|
+
const made = await driver.exec(
|
|
256
|
+
`mkdir -p ${OUTBOX_PATH} ${SNAPSHOTS_DIR} && chmod 1777 ${OUTBOX_PATH}`,
|
|
257
|
+
{ workdir: null, user: "root" },
|
|
258
|
+
);
|
|
259
|
+
if (made.status !== 0) {
|
|
260
|
+
const why = String(made.stderr ?? "")
|
|
261
|
+
.split(String.fromCharCode(10))[0]
|
|
262
|
+
.trim();
|
|
263
|
+
throw new StepFailed([
|
|
264
|
+
`FAILED the sandbox's Outbox folder could not be made${why ? `: ${why}` : ""}.`,
|
|
265
|
+
]);
|
|
266
|
+
}
|
|
267
|
+
if (!(await syncSnapshot())) {
|
|
268
|
+
throw new StepFailed([
|
|
269
|
+
"FAILED the first Snapshot could not be put in place (over the size cap, or the sandbox refused it), so the Chief of Staff is not started.",
|
|
270
|
+
]);
|
|
271
|
+
}
|
|
272
|
+
},
|
|
273
|
+
start: schedule,
|
|
274
|
+
/** Stop pumping, and read the Outbox once more: whatever the agent left, whole or not. */
|
|
275
|
+
async finish() {
|
|
276
|
+
stopped = true;
|
|
277
|
+
timers.clearTimeout(timer);
|
|
278
|
+
await running;
|
|
279
|
+
try {
|
|
280
|
+
await syncOutbox(true);
|
|
281
|
+
} catch (e) {
|
|
282
|
+
warn(`the last read failed (${e?.message ?? e})`);
|
|
283
|
+
}
|
|
284
|
+
},
|
|
285
|
+
/** Pumps once now, for a test. */
|
|
286
|
+
pump,
|
|
287
|
+
};
|
|
288
|
+
}
|
package/src/stage.mjs
CHANGED
|
@@ -66,7 +66,9 @@ import { adapterFor } from "./harness/adapters.mjs";
|
|
|
66
66
|
import { effortFor, harnessFacts } from "./harness/facts.mjs";
|
|
67
67
|
import { loadHarness, resolveHarness } from "./harness/resolve.mjs";
|
|
68
68
|
import * as audit from "./stage/audit.mjs";
|
|
69
|
+
import * as build from "./stage/build.mjs";
|
|
69
70
|
import { egressHosts, openEgressRoute, refuseHeldKey } from "./stage/egress-route.mjs";
|
|
71
|
+
import { createLiveLink } from "./stage/factory-live.mjs";
|
|
70
72
|
import * as implement from "./stage/implement.mjs";
|
|
71
73
|
import * as reviewResponse from "./stage/review-response.mjs";
|
|
72
74
|
import {
|
|
@@ -97,6 +99,7 @@ export const STAGE_COMMANDS = Object.freeze({
|
|
|
97
99
|
review,
|
|
98
100
|
implement,
|
|
99
101
|
"review-response": reviewResponse,
|
|
102
|
+
build,
|
|
100
103
|
});
|
|
101
104
|
|
|
102
105
|
const DOCS = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs`;
|
|
@@ -137,6 +140,9 @@ const either = (words) => `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
|
|
|
137
140
|
* transcriptPath?: string,
|
|
138
141
|
* errorLogPath?: string,
|
|
139
142
|
* usagePath?: string,
|
|
143
|
+
* snapshotDir?: string,
|
|
144
|
+
* outboxDir?: string,
|
|
145
|
+
* factory?: boolean,
|
|
140
146
|
* trustedRef?: string,
|
|
141
147
|
* untracked?: boolean,
|
|
142
148
|
* inputPaths?: string[],
|
|
@@ -154,7 +160,9 @@ const either = (words) => `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
|
|
|
154
160
|
* timers?: { setTimeout: Function, clearTimeout: Function },
|
|
155
161
|
* out: (s: string) => void,
|
|
156
162
|
* err: (s: string) => void,
|
|
157
|
-
* }} opts `stage` is a name in STAGE_COMMANDS. `
|
|
163
|
+
* }} opts `stage` is a name in STAGE_COMMANDS. `snapshotDir` and `outboxDir` are the factory-mode
|
|
164
|
+
* Stage's (`build`): the engine's folders, the Snapshot copied into the sandbox read-only and the
|
|
165
|
+
* Outbox copied out live, with `factory` true as the engine says it; no other Stage takes them. `trustedRef` is the commit the
|
|
158
166
|
* instruction files come from (default: the checked-out one). `untracked`
|
|
159
167
|
* copies untracked files in too. `inputPaths` are files to copy in beside
|
|
160
168
|
* the brief, on a Stage that takes them. `bundlePath` is where a writing
|
|
@@ -183,6 +191,9 @@ export async function runStage({
|
|
|
183
191
|
transcriptPath,
|
|
184
192
|
errorLogPath,
|
|
185
193
|
usagePath,
|
|
194
|
+
snapshotDir,
|
|
195
|
+
outboxDir,
|
|
196
|
+
factory,
|
|
186
197
|
trustedRef,
|
|
187
198
|
untracked = false,
|
|
188
199
|
inputPaths = [],
|
|
@@ -251,9 +262,27 @@ export async function runStage({
|
|
|
251
262
|
if (foreign) return usage(`The verify run starts no agent, so it takes no ${foreign}.`);
|
|
252
263
|
if (usagePath !== undefined)
|
|
253
264
|
return usage("The verify run starts no agent, so it takes no --usage.");
|
|
265
|
+
} else if (definition.FACTORY) {
|
|
266
|
+
// The Outbox's `result` entry is this Stage's result: there is no result file.
|
|
267
|
+
if (briefPath === undefined) return usage(`stage ${stage} needs --brief <file>.`);
|
|
268
|
+
if (resultPath !== undefined) {
|
|
269
|
+
return usage(`stage ${stage} takes no --result: its Outbox is its result.`);
|
|
270
|
+
}
|
|
271
|
+
for (const [flag, dir] of [
|
|
272
|
+
["snapshotDir", snapshotDir],
|
|
273
|
+
["outboxDir", outboxDir],
|
|
274
|
+
]) {
|
|
275
|
+
if (dir === undefined) return usage(`stage ${stage} needs ${flag}.`);
|
|
276
|
+
const found = statSync(resolve(cwd, dir), { throwIfNoEntry: false });
|
|
277
|
+
if (!found?.isDirectory()) return usage(`${flag} ${dir} is not a folder that exists.`);
|
|
278
|
+
}
|
|
279
|
+
if (factory !== true) return usage(`stage ${stage} runs in factory mode only.`);
|
|
254
280
|
} else if (briefPath === undefined || resultPath === undefined) {
|
|
255
281
|
return usage(`stage ${stage} needs --brief <file> and --result <file>.`);
|
|
256
282
|
}
|
|
283
|
+
if (!definition.FACTORY && (snapshotDir !== undefined || outboxDir !== undefined || factory)) {
|
|
284
|
+
return usage(`stage ${stage} takes no Snapshot, Outbox or factory mode.`);
|
|
285
|
+
}
|
|
257
286
|
if (model !== undefined && !MODEL_ID.test(model)) {
|
|
258
287
|
return usage(
|
|
259
288
|
`--model must be a plain model id (letters, digits and . _ : @ / [ ] -), got: ${JSON.stringify(model)}`,
|
|
@@ -343,7 +372,7 @@ export async function runStage({
|
|
|
343
372
|
const named = new Map();
|
|
344
373
|
let privateDir = null;
|
|
345
374
|
for (const [flag, given, name] of [
|
|
346
|
-
["--result", resultPath, definition.RESULT_NAME],
|
|
375
|
+
...(definition.FACTORY ? [] : [["--result", resultPath, definition.RESULT_NAME]]),
|
|
347
376
|
...(definition.WRITES_BUNDLE ? [["--bundle", bundlePath, "branch.bundle"]] : []),
|
|
348
377
|
["--transcript", transcriptPath, "transcript.log"],
|
|
349
378
|
["--error-log", errorLogPath, "errors.log"],
|
|
@@ -478,7 +507,9 @@ export async function runStage({
|
|
|
478
507
|
return runInSandbox(
|
|
479
508
|
{
|
|
480
509
|
runner: withResolvedImages(runner, resolvedImages),
|
|
481
|
-
|
|
510
|
+
// The factory-mode build Stage's Snapshot is read-only only to a user that is not root:
|
|
511
|
+
// a Docker driver runs that Stage's steps as uid 1000 (the other Stages stay as they are).
|
|
512
|
+
runtime: definition.FACTORY ? { ...choice.runtime, agentUser: true } : choice.runtime,
|
|
482
513
|
plan: shape,
|
|
483
514
|
signals,
|
|
484
515
|
timers,
|
|
@@ -511,6 +542,13 @@ export async function runStage({
|
|
|
511
542
|
workspace,
|
|
512
543
|
seed,
|
|
513
544
|
files,
|
|
545
|
+
live: definition.FACTORY
|
|
546
|
+
? {
|
|
547
|
+
snapshotDir: resolve(cwd, snapshotDir),
|
|
548
|
+
outboxDir: resolve(cwd, outboxDir),
|
|
549
|
+
timers,
|
|
550
|
+
}
|
|
551
|
+
: null,
|
|
514
552
|
publicLog,
|
|
515
553
|
out,
|
|
516
554
|
err,
|
|
@@ -735,6 +773,23 @@ async function buildSandbox({
|
|
|
735
773
|
if (installAgent) await driver.installAgent(out);
|
|
736
774
|
}
|
|
737
775
|
|
|
776
|
+
/**
|
|
777
|
+
* The factory-mode Stage's Snapshot is a read-only copy (`chmod a-w`), which holds against
|
|
778
|
+
* every user but root. So the Stage refuses to start the agent as root, or as a user it
|
|
779
|
+
* cannot read (ADR 0039).
|
|
780
|
+
*/
|
|
781
|
+
async function requireNonRootHarness(driver) {
|
|
782
|
+
const made = await driver.exec("id -u", { workdir: null });
|
|
783
|
+
const uid = made.status === 0 ? made.stdout.toString("utf8").trim() : "";
|
|
784
|
+
if (/^\d+$/.test(uid) && Number(uid) !== 0) return;
|
|
785
|
+
throw new StepFailed([
|
|
786
|
+
uid === "0"
|
|
787
|
+
? "REFUSED the harness runs as root in the sandbox, so the Snapshot would not be read-only to it."
|
|
788
|
+
: "REFUSED the sandbox's harness user could not be read, so the Snapshot is not known to be read-only to it.",
|
|
789
|
+
"The factory-mode Stage runs the Chief of Staff only as a user that is not root: use a sandbox image whose user is not root.",
|
|
790
|
+
]);
|
|
791
|
+
}
|
|
792
|
+
|
|
738
793
|
/** The Stage in the sandbox, from the image to what comes out. */
|
|
739
794
|
async function launch({
|
|
740
795
|
driver,
|
|
@@ -761,6 +816,7 @@ async function launch({
|
|
|
761
816
|
workspace,
|
|
762
817
|
seed,
|
|
763
818
|
files,
|
|
819
|
+
live,
|
|
764
820
|
publicLog,
|
|
765
821
|
out,
|
|
766
822
|
err,
|
|
@@ -803,7 +859,7 @@ async function launch({
|
|
|
803
859
|
|
|
804
860
|
const names = inputs.map((input) => input.name);
|
|
805
861
|
const preamble = definition.briefPreamble(shape, names, { setup: sandbox.setup !== null });
|
|
806
|
-
const text = `${preamble}${brief}`;
|
|
862
|
+
const text = `${preamble}${live === null ? brief : definition.sandboxBrief(brief, live)}`;
|
|
807
863
|
await driver.copyIn(
|
|
808
864
|
tarOf([
|
|
809
865
|
{ path: "agent-kit", dir: true },
|
|
@@ -835,13 +891,26 @@ async function launch({
|
|
|
835
891
|
clocks.begin("scan", limits.scanMinutes);
|
|
836
892
|
/** @type {import("./exec.mjs").StartResult | null} null when a limit stopped it */
|
|
837
893
|
let agent = null;
|
|
894
|
+
let linked = false;
|
|
895
|
+
// The factory-mode Stage's Snapshot goes in read-only before the agent starts, and is
|
|
896
|
+
// re-copied, with the Outbox copied out, while it runs and once more after it.
|
|
897
|
+
const link = live === null ? null : createLiveLink({ driver, out, ...live });
|
|
838
898
|
try {
|
|
899
|
+
// The Snapshot is read-only only to a user that is not root: check the harness's user
|
|
900
|
+
// before the agent starts, and refuse (the sandbox is torn down) when it is root or unknown.
|
|
901
|
+
if (link) await requireNonRootHarness(driver);
|
|
902
|
+
if (link) await link.prepare();
|
|
903
|
+
linked = true;
|
|
904
|
+
link?.start();
|
|
839
905
|
agent = await driver.exec(
|
|
840
906
|
agentScript({ plan, report: definition.RESULT_PATH, workspace: definition.WORKSPACE }),
|
|
841
907
|
{ env: plan.launch.env },
|
|
842
908
|
);
|
|
843
909
|
} catch (e) {
|
|
844
910
|
if (!(e instanceof LimitReached)) throw e;
|
|
911
|
+
} finally {
|
|
912
|
+
// Only a link that was prepared has an Outbox to read.
|
|
913
|
+
if (linked) await link?.finish();
|
|
845
914
|
}
|
|
846
915
|
clocks.end();
|
|
847
916
|
if (agent && agent.stdout.toString("utf8").split(/\r?\n/).includes(turnsMarker(plan))) {
|
|
@@ -902,6 +971,14 @@ async function launch({
|
|
|
902
971
|
);
|
|
903
972
|
}
|
|
904
973
|
|
|
974
|
+
if (live !== null) {
|
|
975
|
+
// The Outbox is the result and the engine has read it live: nothing is left to copy out.
|
|
976
|
+
out(
|
|
977
|
+
"Outbox: copied out to the engine's folder as it was written. Nothing was filed or posted.",
|
|
978
|
+
);
|
|
979
|
+
if (stopped) return STOPPED_EXIT;
|
|
980
|
+
return failed ? 1 : 0;
|
|
981
|
+
}
|
|
905
982
|
const file = await driver.copyOut(definition.RESULT_PATH, {
|
|
906
983
|
maxBytes: definition.MAX_COPY_BYTES ?? definition.MAX_RESULT_BYTES,
|
|
907
984
|
});
|