@mnaimfaizy/agent-kit 1.0.0-beta.15 → 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 +332 -5
- 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/doctor.mjs +53 -1
- package/src/exec.mjs +18 -5
- package/src/factory/budget/budget.mjs +260 -0
- package/src/factory/build/command.mjs +321 -0
- package/src/factory/build/factory.mjs +473 -0
- package/src/factory/build/findings.mjs +55 -0
- package/src/factory/build/host.mjs +230 -0
- package/src/factory/build/notes.mjs +191 -0
- package/src/factory/build/pull-request.mjs +74 -0
- package/src/factory/bundle.mjs +146 -0
- package/src/factory/checks/allowed-paths.mjs +50 -0
- package/src/factory/checks/plan-header.mjs +296 -0
- package/src/factory/checks/qa.mjs +85 -0
- package/src/factory/checks/review.mjs +73 -0
- package/src/factory/checks/security.mjs +50 -0
- package/src/factory/checks/stage-check.mjs +89 -0
- package/src/factory/claims/command.mjs +187 -0
- package/src/factory/claims/release.mjs +111 -0
- package/src/factory/decision/answers.mjs +103 -0
- package/src/factory/decision/command.mjs +64 -0
- package/src/factory/decision/plan.mjs +99 -0
- package/src/factory/decision/request.mjs +116 -0
- package/src/factory/doctor/files.mjs +349 -0
- package/src/factory/doctor/index.mjs +56 -0
- package/src/factory/doctor/local.mjs +513 -0
- package/src/factory/doctor/orchestrate.mjs +146 -0
- package/src/factory/engine/lease.mjs +146 -0
- package/src/factory/engine/local-engine.mjs +177 -0
- package/src/factory/engine/lockfile.mjs +64 -0
- package/src/factory/engine/workflow-engine.mjs +124 -0
- package/src/factory/gate/comment.mjs +88 -0
- package/src/factory/gate/config.mjs +57 -0
- package/src/factory/gate/gate-core.mjs +250 -0
- package/src/factory/gate/guarded.mjs +17 -0
- package/src/factory/gate/reads.mjs +105 -0
- package/src/factory/gate/task.mjs +193 -0
- package/src/factory/gate/trip-reads.mjs +82 -0
- package/src/factory/gate/trip.mjs +87 -0
- package/src/factory/init/blueprint.mjs +181 -0
- package/src/factory/init/index.mjs +338 -0
- package/src/factory/labels/evidence.mjs +162 -0
- package/src/factory/labels/moves.mjs +32 -0
- package/src/factory/labels/reconcile.mjs +267 -0
- package/src/factory/labels/revert.mjs +87 -0
- package/src/factory/labels/timeline.mjs +72 -0
- package/src/factory/labels/voided.mjs +59 -0
- package/src/factory/limits/harness.mjs +39 -0
- package/src/factory/limits/limits.mjs +131 -0
- package/src/factory/merge/command.mjs +172 -0
- package/src/factory/outbox/check.mjs +240 -0
- package/src/factory/outbox/rulings.mjs +195 -0
- package/src/factory/plan/command.mjs +66 -0
- package/src/factory/plan/comment.mjs +156 -0
- package/src/factory/plan/publish.mjs +149 -0
- package/src/factory/plan/risk.mjs +153 -0
- package/src/factory/qa/command.mjs +301 -0
- package/src/factory/qa/decide.mjs +86 -0
- package/src/factory/qa/report.mjs +50 -0
- package/src/factory/records/engine-record.mjs +133 -0
- package/src/factory/records/main.mjs +96 -0
- package/src/factory/records/record.mjs +226 -0
- package/src/factory/records/sink.mjs +57 -0
- package/src/factory/report/build.mjs +92 -0
- package/src/factory/report/command.mjs +80 -0
- package/src/factory/report/facts.mjs +226 -0
- package/src/factory/report/gate-section.mjs +122 -0
- package/src/factory/report/metrics.mjs +111 -0
- package/src/factory/report/reads.mjs +246 -0
- package/src/factory/report/render.mjs +121 -0
- package/src/factory/report/rollout.mjs +154 -0
- package/src/factory/review/brief.mjs +195 -0
- package/src/factory/review/command.mjs +182 -0
- package/src/factory/run/awake.mjs +70 -0
- package/src/factory/run/collect.mjs +77 -0
- package/src/factory/run/command.mjs +556 -0
- package/src/factory/run/gh.mjs +46 -0
- package/src/factory/run/launch.mjs +66 -0
- package/src/factory/run/pipelines.mjs +694 -0
- package/src/factory/run/raw.mjs +96 -0
- package/src/factory/run/restart.mjs +83 -0
- package/src/factory/run/s3.mjs +193 -0
- package/src/factory/run/secrets.mjs +142 -0
- package/src/factory/run/teardown.mjs +242 -0
- package/src/factory/run/token.mjs +70 -0
- package/src/factory/run/worktree.mjs +160 -0
- package/src/factory/security/audit.mjs +353 -0
- package/src/factory/security/command.mjs +157 -0
- package/src/factory/setup/app.mjs +122 -0
- package/src/factory/setup/command.mjs +472 -0
- package/src/factory/setup/labels.mjs +25 -0
- package/src/factory/setup/reads.mjs +159 -0
- package/src/factory/setup/writes.mjs +138 -0
- package/src/factory/snapshot/write.mjs +176 -0
- package/src/factory/stop/command.mjs +136 -0
- package/src/factory/sweep/actions-main.mjs +119 -0
- package/src/factory/sweep/command.mjs +65 -0
- package/src/factory/sweep/knobs.mjs +78 -0
- package/src/factory/sweep/marker-version.mjs +15 -0
- package/src/factory/sweep/markers.mjs +112 -0
- package/src/factory/sweep/overlap.mjs +24 -0
- package/src/factory/sweep/run.mjs +198 -0
- package/src/factory/sweep/shell.mjs +398 -0
- package/src/factory/sweep/split.mjs +104 -0
- package/src/factory/sweep/states.mjs +87 -0
- package/src/factory/sweep/sweep-core.mjs +2009 -0
- package/src/factory/tracker/github.mjs +713 -0
- package/src/factory/tracker/operations.mjs +153 -0
- package/src/factory/upgrade/index.mjs +83 -0
- package/src/init.mjs +62 -24
- package/src/kit-owned-paths.mjs +1 -1
- package/src/stage/build.mjs +100 -0
- package/src/stage/factory-live.mjs +288 -0
- package/src/stage.mjs +100 -4
- package/src/upgrade.mjs +39 -7
|
@@ -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
|
@@ -50,7 +50,9 @@ import {
|
|
|
50
50
|
parseLimits,
|
|
51
51
|
STOPPED_EXIT,
|
|
52
52
|
stoppedStatus,
|
|
53
|
+
TOKENS,
|
|
53
54
|
TURNS,
|
|
55
|
+
WALL_CLOCK,
|
|
54
56
|
LimitReached,
|
|
55
57
|
} from "./deep-scan/limits.mjs";
|
|
56
58
|
import { MODEL_ID } from "./deep-scan/model-proxy.mjs";
|
|
@@ -64,7 +66,9 @@ import { adapterFor } from "./harness/adapters.mjs";
|
|
|
64
66
|
import { effortFor, harnessFacts } from "./harness/facts.mjs";
|
|
65
67
|
import { loadHarness, resolveHarness } from "./harness/resolve.mjs";
|
|
66
68
|
import * as audit from "./stage/audit.mjs";
|
|
69
|
+
import * as build from "./stage/build.mjs";
|
|
67
70
|
import { egressHosts, openEgressRoute, refuseHeldKey } from "./stage/egress-route.mjs";
|
|
71
|
+
import { createLiveLink } from "./stage/factory-live.mjs";
|
|
68
72
|
import * as implement from "./stage/implement.mjs";
|
|
69
73
|
import * as reviewResponse from "./stage/review-response.mjs";
|
|
70
74
|
import {
|
|
@@ -95,6 +99,7 @@ export const STAGE_COMMANDS = Object.freeze({
|
|
|
95
99
|
review,
|
|
96
100
|
implement,
|
|
97
101
|
"review-response": reviewResponse,
|
|
102
|
+
build,
|
|
98
103
|
});
|
|
99
104
|
|
|
100
105
|
const DOCS = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs`;
|
|
@@ -134,6 +139,10 @@ const either = (words) => `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
|
|
|
134
139
|
* bundlePath?: string,
|
|
135
140
|
* transcriptPath?: string,
|
|
136
141
|
* errorLogPath?: string,
|
|
142
|
+
* usagePath?: string,
|
|
143
|
+
* snapshotDir?: string,
|
|
144
|
+
* outboxDir?: string,
|
|
145
|
+
* factory?: boolean,
|
|
137
146
|
* trustedRef?: string,
|
|
138
147
|
* untracked?: boolean,
|
|
139
148
|
* inputPaths?: string[],
|
|
@@ -151,7 +160,9 @@ const either = (words) => `${words.slice(0, -1).join(", ")} or ${words.at(-1)}`;
|
|
|
151
160
|
* timers?: { setTimeout: Function, clearTimeout: Function },
|
|
152
161
|
* out: (s: string) => void,
|
|
153
162
|
* err: (s: string) => void,
|
|
154
|
-
* }} 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
|
|
155
166
|
* instruction files come from (default: the checked-out one). `untracked`
|
|
156
167
|
* copies untracked files in too. `inputPaths` are files to copy in beside
|
|
157
168
|
* the brief, on a Stage that takes them. `bundlePath` is where a writing
|
|
@@ -179,6 +190,10 @@ export async function runStage({
|
|
|
179
190
|
bundlePath,
|
|
180
191
|
transcriptPath,
|
|
181
192
|
errorLogPath,
|
|
193
|
+
usagePath,
|
|
194
|
+
snapshotDir,
|
|
195
|
+
outboxDir,
|
|
196
|
+
factory,
|
|
182
197
|
trustedRef,
|
|
183
198
|
untracked = false,
|
|
184
199
|
inputPaths = [],
|
|
@@ -245,9 +260,29 @@ export async function runStage({
|
|
|
245
260
|
];
|
|
246
261
|
const foreign = AGENT_FLAGS.find((_, i) => given[i] !== undefined);
|
|
247
262
|
if (foreign) return usage(`The verify run starts no agent, so it takes no ${foreign}.`);
|
|
263
|
+
if (usagePath !== undefined)
|
|
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.`);
|
|
248
280
|
} else if (briefPath === undefined || resultPath === undefined) {
|
|
249
281
|
return usage(`stage ${stage} needs --brief <file> and --result <file>.`);
|
|
250
282
|
}
|
|
283
|
+
if (!definition.FACTORY && (snapshotDir !== undefined || outboxDir !== undefined || factory)) {
|
|
284
|
+
return usage(`stage ${stage} takes no Snapshot, Outbox or factory mode.`);
|
|
285
|
+
}
|
|
251
286
|
if (model !== undefined && !MODEL_ID.test(model)) {
|
|
252
287
|
return usage(
|
|
253
288
|
`--model must be a plain model id (letters, digits and . _ : @ / [ ] -), got: ${JSON.stringify(model)}`,
|
|
@@ -337,10 +372,12 @@ export async function runStage({
|
|
|
337
372
|
const named = new Map();
|
|
338
373
|
let privateDir = null;
|
|
339
374
|
for (const [flag, given, name] of [
|
|
340
|
-
["--result", resultPath, definition.RESULT_NAME],
|
|
375
|
+
...(definition.FACTORY ? [] : [["--result", resultPath, definition.RESULT_NAME]]),
|
|
341
376
|
...(definition.WRITES_BUNDLE ? [["--bundle", bundlePath, "branch.bundle"]] : []),
|
|
342
377
|
["--transcript", transcriptPath, "transcript.log"],
|
|
343
378
|
["--error-log", errorLogPath, "errors.log"],
|
|
379
|
+
// Only when asked for: the Factory's trusted step reads it (#515).
|
|
380
|
+
...(usagePath === undefined ? [] : [["--usage", usagePath, "usage.json"]]),
|
|
344
381
|
]) {
|
|
345
382
|
if (given === undefined) {
|
|
346
383
|
privateDir ??= mkdtempSync(join(tmpdir(), "agent-kit-stage-"));
|
|
@@ -470,7 +507,9 @@ export async function runStage({
|
|
|
470
507
|
return runInSandbox(
|
|
471
508
|
{
|
|
472
509
|
runner: withResolvedImages(runner, resolvedImages),
|
|
473
|
-
|
|
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,
|
|
474
513
|
plan: shape,
|
|
475
514
|
signals,
|
|
476
515
|
timers,
|
|
@@ -503,6 +542,13 @@ export async function runStage({
|
|
|
503
542
|
workspace,
|
|
504
543
|
seed,
|
|
505
544
|
files,
|
|
545
|
+
live: definition.FACTORY
|
|
546
|
+
? {
|
|
547
|
+
snapshotDir: resolve(cwd, snapshotDir),
|
|
548
|
+
outboxDir: resolve(cwd, outboxDir),
|
|
549
|
+
timers,
|
|
550
|
+
}
|
|
551
|
+
: null,
|
|
506
552
|
publicLog,
|
|
507
553
|
out,
|
|
508
554
|
err,
|
|
@@ -727,6 +773,23 @@ async function buildSandbox({
|
|
|
727
773
|
if (installAgent) await driver.installAgent(out);
|
|
728
774
|
}
|
|
729
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
|
+
|
|
730
793
|
/** The Stage in the sandbox, from the image to what comes out. */
|
|
731
794
|
async function launch({
|
|
732
795
|
driver,
|
|
@@ -753,6 +816,7 @@ async function launch({
|
|
|
753
816
|
workspace,
|
|
754
817
|
seed,
|
|
755
818
|
files,
|
|
819
|
+
live,
|
|
756
820
|
publicLog,
|
|
757
821
|
out,
|
|
758
822
|
err,
|
|
@@ -795,7 +859,7 @@ async function launch({
|
|
|
795
859
|
|
|
796
860
|
const names = inputs.map((input) => input.name);
|
|
797
861
|
const preamble = definition.briefPreamble(shape, names, { setup: sandbox.setup !== null });
|
|
798
|
-
const text = `${preamble}${brief}`;
|
|
862
|
+
const text = `${preamble}${live === null ? brief : definition.sandboxBrief(brief, live)}`;
|
|
799
863
|
await driver.copyIn(
|
|
800
864
|
tarOf([
|
|
801
865
|
{ path: "agent-kit", dir: true },
|
|
@@ -827,13 +891,26 @@ async function launch({
|
|
|
827
891
|
clocks.begin("scan", limits.scanMinutes);
|
|
828
892
|
/** @type {import("./exec.mjs").StartResult | null} null when a limit stopped it */
|
|
829
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 });
|
|
830
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();
|
|
831
905
|
agent = await driver.exec(
|
|
832
906
|
agentScript({ plan, report: definition.RESULT_PATH, workspace: definition.WORKSPACE }),
|
|
833
907
|
{ env: plan.launch.env },
|
|
834
908
|
);
|
|
835
909
|
} catch (e) {
|
|
836
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();
|
|
837
914
|
}
|
|
838
915
|
clocks.end();
|
|
839
916
|
if (agent && agent.stdout.toString("utf8").split(/\r?\n/).includes(turnsMarker(plan))) {
|
|
@@ -865,6 +942,17 @@ async function launch({
|
|
|
865
942
|
});
|
|
866
943
|
|
|
867
944
|
const stopped = clocks.stopped();
|
|
945
|
+
// The run's usage, for the Factory's trusted step: two numbers from the kit's
|
|
946
|
+
// own proxy and clocks, written before anything that can fail below. A
|
|
947
|
+
// harness the proxy cannot front has no count, so it writes none.
|
|
948
|
+
if (files["--usage"] !== undefined && hosts === null && proxy) {
|
|
949
|
+
const named = { [TURNS]: "turns", [TOKENS]: "tokens", [WALL_CLOCK]: "minutes" };
|
|
950
|
+
writeFileSync(
|
|
951
|
+
files["--usage"],
|
|
952
|
+
`${JSON.stringify({ tokens: proxy.tokens(), stopped: stopped ? (named[stopped.limit] ?? null) : null })}\n`,
|
|
953
|
+
{ mode: 0o600, flag: "wx" },
|
|
954
|
+
);
|
|
955
|
+
}
|
|
868
956
|
const failed = agent !== null && agent.status !== 0;
|
|
869
957
|
if (stopped) {
|
|
870
958
|
out(`${stoppedStatus(stopped)} Copying out what result the agent left.`);
|
|
@@ -883,6 +971,14 @@ async function launch({
|
|
|
883
971
|
);
|
|
884
972
|
}
|
|
885
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
|
+
}
|
|
886
982
|
const file = await driver.copyOut(definition.RESULT_PATH, {
|
|
887
983
|
maxBytes: definition.MAX_COPY_BYTES ?? definition.MAX_RESULT_BYTES,
|
|
888
984
|
});
|
package/src/upgrade.mjs
CHANGED
|
@@ -14,6 +14,8 @@ import { PinRewriteError, readWorkflows, rewriteKitPins } from "./callers.mjs";
|
|
|
14
14
|
import { checkPins } from "./checks/pins.mjs";
|
|
15
15
|
import { fileAndPinChecks, printFileAndPinChecks } from "./doctor.mjs";
|
|
16
16
|
import { firstLine } from "./exec.mjs";
|
|
17
|
+
import { hasFactory } from "./factory/doctor/index.mjs";
|
|
18
|
+
import { factoryNotes, withCliPins } from "./factory/upgrade/index.mjs";
|
|
17
19
|
import { openKitRepo, PreManifestTagError, serverFromEnv } from "./kit-tag.mjs";
|
|
18
20
|
import {
|
|
19
21
|
applyPlan,
|
|
@@ -69,7 +71,7 @@ export function planUpgrade({ runner, root, oldSnap, newSnap, files, force, pinn
|
|
|
69
71
|
const writes = kitFileWrites(newSnap);
|
|
70
72
|
for (const w of writes) checkLocalPath(root, w.path, { deleted: deletes });
|
|
71
73
|
|
|
72
|
-
const
|
|
74
|
+
const pinEditsSoFar = [];
|
|
73
75
|
if (pinnedTag !== newSnap.tag) {
|
|
74
76
|
for (const file of files) {
|
|
75
77
|
if (file.pins.length === 0) continue;
|
|
@@ -81,7 +83,7 @@ export function planUpgrade({ runner, root, oldSnap, newSnap, files, force, pinn
|
|
|
81
83
|
if (err instanceof PinRewriteError) throw new Refusal(`${file.path}: ${err.message}`);
|
|
82
84
|
throw err;
|
|
83
85
|
}
|
|
84
|
-
|
|
86
|
+
pinEditsSoFar.push({
|
|
85
87
|
path: file.path,
|
|
86
88
|
count: rewritten.count,
|
|
87
89
|
bytes: Buffer.from(rewritten.text, "utf8"),
|
|
@@ -89,6 +91,19 @@ export function planUpgrade({ runner, root, oldSnap, newSnap, files, force, pinn
|
|
|
89
91
|
}
|
|
90
92
|
}
|
|
91
93
|
|
|
94
|
+
// A Factory's Callers also pin the CLI they install: move that pin to the tag's version.
|
|
95
|
+
let cliPins = [];
|
|
96
|
+
let pinEdits = pinEditsSoFar;
|
|
97
|
+
const factory = hasFactory(root);
|
|
98
|
+
if (factory) {
|
|
99
|
+
({ edits: pinEdits, cli: cliPins } = withCliPins({
|
|
100
|
+
files,
|
|
101
|
+
edits: pinEditsSoFar,
|
|
102
|
+
readText: (path) => readWorkflowText(root, path),
|
|
103
|
+
newTag: newSnap.tag,
|
|
104
|
+
}));
|
|
105
|
+
}
|
|
106
|
+
|
|
92
107
|
const { changed: dirty, ignored } = uncommittedChanges({ runner, root, paths: deletes });
|
|
93
108
|
if (dirty.length && !force) {
|
|
94
109
|
throw new Refusal(
|
|
@@ -98,7 +113,7 @@ export function planUpgrade({ runner, root, oldSnap, newSnap, files, force, pinn
|
|
|
98
113
|
);
|
|
99
114
|
}
|
|
100
115
|
|
|
101
|
-
return { deletes, removed, writes, pinEdits, dirty, ignored };
|
|
116
|
+
return { deletes, removed, writes, pinEdits, cliPins, factory, dirty, ignored };
|
|
102
117
|
}
|
|
103
118
|
|
|
104
119
|
/**
|
|
@@ -199,12 +214,17 @@ export async function runUpgrade({
|
|
|
199
214
|
out(`Delete (no longer in ${newTag}'s kit-owned-paths.txt):`);
|
|
200
215
|
for (const p of plan.removed) out(` ${p}`);
|
|
201
216
|
}
|
|
202
|
-
|
|
217
|
+
const usesEdits = plan.pinEdits.filter((e) => !e.cliOnly);
|
|
218
|
+
if (usesEdits.length) {
|
|
203
219
|
out(`Rewrite uses: pins to @${newTag}:`);
|
|
204
|
-
for (const e of
|
|
220
|
+
for (const e of usesEdits) out(` ${e.path} (${e.count} pin${e.count === 1 ? "" : "s"})`);
|
|
205
221
|
} else {
|
|
206
222
|
out(`The uses: pins already name ${newTag}.`);
|
|
207
223
|
}
|
|
224
|
+
if (plan.cliPins.length) {
|
|
225
|
+
out(`Rewrite the CLI pins of the Factory Callers to @${newTag.slice(1)}:`);
|
|
226
|
+
for (const e of plan.cliPins) out(` ${e.path} (${e.count} pin${e.count === 1 ? "" : "s"})`);
|
|
227
|
+
}
|
|
208
228
|
if (plan.dirty.length) {
|
|
209
229
|
out(`--force: discarding uncommitted changes in ${plan.dirty.length} file(s):`);
|
|
210
230
|
for (const d of listed(plan.dirty)) out(` ${d}`);
|
|
@@ -272,9 +292,21 @@ export async function runUpgrade({
|
|
|
272
292
|
}
|
|
273
293
|
}
|
|
274
294
|
|
|
275
|
-
// The
|
|
295
|
+
// The Factory is the Consumer's: say what upgrade left alone.
|
|
296
|
+
// Judged before the writes, from the Consumer's own Factory files, as the plan was.
|
|
297
|
+
const { factory } = plan;
|
|
298
|
+
if (factory) {
|
|
299
|
+
out("");
|
|
300
|
+
for (const line of factoryNotes({ newTag })) out(line);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// The same file and pin checks as `doctor --ci`, against the tag already fetched, and the
|
|
304
|
+
// Factory's file checks when the checkout has a Factory.
|
|
276
305
|
out("");
|
|
277
|
-
const failed = printFileAndPinChecks(
|
|
306
|
+
const failed = printFileAndPinChecks(
|
|
307
|
+
out,
|
|
308
|
+
fileAndPinChecks({ runner, root, snap: newSnap, factory }),
|
|
309
|
+
);
|
|
278
310
|
out("");
|
|
279
311
|
out(
|
|
280
312
|
failed
|