@0perator/operator 0.2.1 → 0.2.2-next.1

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.
Files changed (66) hide show
  1. package/README.md +1 -1
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +8 -2
  4. package/dist/autonomy/agent-cli.js +1 -1
  5. package/dist/autonomy/headless.js +30 -6
  6. package/dist/autonomy/pr-isolation.js +92 -0
  7. package/dist/autonomy/pr-preflight.js +474 -0
  8. package/dist/autonomy/session-factory.js +2 -0
  9. package/dist/browser/capture.js +505 -0
  10. package/dist/browser/engine.js +4 -3
  11. package/dist/browser/page-capture.js +167 -0
  12. package/dist/browser/png.js +116 -0
  13. package/dist/browser/visual-compare.js +229 -0
  14. package/dist/bus/beam-drop.js +55 -0
  15. package/dist/bus/inbox.js +7 -1
  16. package/dist/cli.js +130 -26
  17. package/dist/config/managed.js +40 -1
  18. package/dist/config/persona.js +86 -41
  19. package/dist/config/product-hosts.js +2 -0
  20. package/dist/config/settings.js +30 -13
  21. package/dist/config/skills-index.js +37 -14
  22. package/dist/engine/agent.js +1 -1
  23. package/dist/engine/aurora.js +18 -9
  24. package/dist/engine/continuation.js +36 -0
  25. package/dist/engine/identity.js +42 -0
  26. package/dist/engine/moa.js +7 -0
  27. package/dist/engine/net-error.js +15 -0
  28. package/dist/engine/rolling-summary.js +142 -93
  29. package/dist/engine/waterfall.js +33 -0
  30. package/dist/gateway-cli.js +10 -1
  31. package/dist/memory/session-index.js +3 -3
  32. package/dist/permissions/index.js +2 -1
  33. package/dist/permissions/policy.js +9 -2
  34. package/dist/permissions/tier.js +9 -1
  35. package/dist/products/craft.js +90 -1
  36. package/dist/products/temple.js +20 -1
  37. package/dist/products/voice.js +112 -0
  38. package/dist/router/free-models.js +5 -9
  39. package/dist/router/models.js +58 -14
  40. package/dist/router/provider-models.js +78 -0
  41. package/dist/router/router.js +15 -3
  42. package/dist/selfimprove/lessons.js +23 -0
  43. package/dist/session.js +192 -87
  44. package/dist/skills/catalogue.js +5 -2
  45. package/dist/skills/finder.js +4 -4
  46. package/dist/skills/install-guard.js +1 -1
  47. package/dist/tools/beam.js +246 -0
  48. package/dist/tools/craft.js +23 -0
  49. package/dist/tools/deferred.js +7 -3
  50. package/dist/tools/doc-text.js +1 -1
  51. package/dist/tools/registry.js +55 -9
  52. package/dist/tools/sandbox.js +6 -6
  53. package/dist/ui/App.js +3 -3
  54. package/dist/ui/ApprovalPrompt.js +1 -1
  55. package/dist/ui/Composer.js +44 -2
  56. package/dist/ui/StatusRule.js +2 -1
  57. package/dist/ui/Transcript.js +5 -0
  58. package/dist/ui/modelPicker.js +10 -6
  59. package/dist/ui/phase.js +4 -2
  60. package/dist/ui/slashCommands.js +1 -0
  61. package/dist/ui/voice.js +185 -0
  62. package/dist/update.js +1 -2
  63. package/dist/util/audio-io.js +82 -0
  64. package/dist/util/slash.js +2 -2
  65. package/dist/vision/pairs.js +239 -0
  66. package/package.json +1 -1
@@ -0,0 +1,474 @@
1
+ import { SHELL_ANY, SHELL_FOREGROUND } from "../tools/classes.js";
2
+ import { engineNote } from "../engine/continuation.js";
3
+ import { seatbeltProfile, bwrapArgs } from "../tools/sandbox.js";
4
+ const env = () => globalThis.process?.env ?? {};
5
+ let live = {};
6
+ /** Read per call by every session in the process; set at startup from settings.prPreflight. */
7
+ export function setPrPreflightSettings(s) {
8
+ live = { ...(s ?? {}) };
9
+ }
10
+ /** KODE_PR_PREFLIGHT=0/1 wins over the setting; on by default. */
11
+ export function prPreflightOn(e = env(), s = live) {
12
+ const v = e.KODE_PR_PREFLIGHT;
13
+ if (v === "0" || v === "false")
14
+ return false;
15
+ if (v === "1" || v === "true")
16
+ return true;
17
+ return s.enabled !== false;
18
+ }
19
+ function join(base, p) {
20
+ const joined = p.startsWith("/") ? p : `${base.replace(/\/+$/, "")}/${p}`;
21
+ const out = [];
22
+ for (const part of joined.split("/")) {
23
+ if (!part || part === ".")
24
+ continue;
25
+ if (part === "..")
26
+ out.pop();
27
+ else
28
+ out.push(part);
29
+ }
30
+ return `/${out.join("/")}`;
31
+ }
32
+ const unquote = (t) => t.replace(/^(['"])(.*)\1$/, "$2");
33
+ const literal = (t) => !/[$`*?]/.test(t);
34
+ /** Split a shell line on ;, &&, || and newlines (pipes stay inside one segment) and follow `cd` between them. */
35
+ export function segments(command, home = env().HOME ?? "") {
36
+ const out = [];
37
+ let dir = undefined;
38
+ for (const raw of command.split(/&&|\|\||;|\n/)) {
39
+ const text = raw.trim().replace(/^[({]\s*/, "").replace(/\s*[)}]$/, "");
40
+ if (!text)
41
+ continue;
42
+ const cd = /^(?:cd|pushd)(?:\s+(\S+))?\s*$/.exec(text);
43
+ if (cd) {
44
+ const t = unquote(cd[1] ?? "~");
45
+ const p = t === "~" || t.startsWith("~/") ? `${home}${t.slice(1)}` : t;
46
+ if (!literal(p) || p === "-")
47
+ dir = null;
48
+ else if (p.startsWith("/"))
49
+ dir = join("/", p);
50
+ else
51
+ dir = dir === null ? null : dir === undefined ? p : join(dir, p);
52
+ continue;
53
+ }
54
+ out.push({ text, dir });
55
+ }
56
+ return out;
57
+ }
58
+ const tokens = (s) => s.trim().split(/\s+/).filter(Boolean).map(unquote);
59
+ const prNumber = (t) => {
60
+ if (!t)
61
+ return undefined;
62
+ const m = /^#?(\d+)$/.exec(t) ?? /\/pull\/(\d+)(?:[/.?#]|$)/.exec(t);
63
+ return m ? Number(m[1]) : undefined;
64
+ };
65
+ const GIT = String.raw `\bgit\s+(?:-C\s+(\S+)\s+)?`;
66
+ const PULL_REF = /^\+?(?:refs\/)?(?:pull|merge-requests)\/(\d+)\/(?:head|merge)(?::(\S+))?$/;
67
+ const VALUE_OPTS = new Set(["-b", "-B", "--orphan", "--reason", "-c", "-C"]);
68
+ /** The PR-relevant events in one segment of a shell command. Pure; table-tested. */
69
+ export function prEvents(text) {
70
+ const ev = [];
71
+ const pipe = text.split("|").map((p) => p.trim());
72
+ const gh = /\bgh\s+pr\s+(?:checkout|co)\b(.*)/.exec(text);
73
+ if (gh)
74
+ ev.push({ kind: "gh-checkout", pr: tokens(gh[1]).map(prNumber).find((n) => n !== undefined) });
75
+ const diffFrom = (s) => {
76
+ const d = /\bgh\s+pr\s+diff\b(.*)/.exec(s);
77
+ if (d)
78
+ return { pr: tokens(d[1]).map(prNumber).find((n) => n !== undefined) };
79
+ const u = /\/pull\/(\d+)\.(?:patch|diff)\b/.exec(s);
80
+ return u ? { pr: Number(u[1]) } : null;
81
+ };
82
+ const applier = (s) => new RegExp(`${GIT}(?:apply|am)\\b|\\bpatch\\b`).test(s);
83
+ if (pipe.length > 1) {
84
+ const src = diffFrom(pipe[0]);
85
+ if (src && pipe.slice(1).some(applier))
86
+ ev.push({ kind: "apply", pr: src.pr });
87
+ }
88
+ const redirect = /\s>\s*(\S+)\s*$/.exec(pipe[0]);
89
+ if (redirect) {
90
+ const src = diffFrom(pipe[0]);
91
+ if (src)
92
+ ev.push({ kind: "patch-file", pr: src.pr, file: unquote(redirect[1]) });
93
+ }
94
+ const applyFile = new RegExp(`${GIT}(?:apply|am)\\b(.*)`).exec(text);
95
+ if (applyFile && pipe.length === 1) {
96
+ const file = tokens(applyFile[2]).filter((t) => !t.startsWith("-")).pop();
97
+ if (file)
98
+ ev.push({ kind: "apply", file, dir: applyFile[1] });
99
+ }
100
+ const fetch = new RegExp(`${GIT}(fetch|pull)\\b(.*)`).exec(text);
101
+ if (fetch) {
102
+ for (const t of tokens(fetch[3])) {
103
+ const m = PULL_REF.exec(t);
104
+ if (!m)
105
+ continue;
106
+ if (fetch[2] === "pull")
107
+ ev.push({ kind: "apply", pr: Number(m[1]), dir: fetch[1] });
108
+ else
109
+ ev.push({ kind: "fetch", pr: Number(m[1]), ref: m[2]?.replace(/^refs\/heads\//, ""), dir: fetch[1] });
110
+ }
111
+ }
112
+ const sw = new RegExp(`${GIT}(checkout|switch)\\b(.*)`).exec(text);
113
+ if (sw) {
114
+ const args = tokens(sw[3]);
115
+ if (!args.includes("--") && !args.some((a) => a === "-p" || a === "--patch")) {
116
+ const pos = args.filter((a, i) => !a.startsWith("-") && !VALUE_OPTS.has(args[i - 1] ?? ""));
117
+ ev.push({ kind: "switch", ref: pos.pop() ?? args[args.indexOf("-b") + 1], dir: sw[1] });
118
+ }
119
+ }
120
+ const wt = new RegExp(`${GIT}worktree\\s+add\\b(.*)`).exec(text);
121
+ if (wt) {
122
+ const args = tokens(wt[2]);
123
+ const pos = args.filter((a, i) => !a.startsWith("-") && !VALUE_OPTS.has(args[i - 1] ?? ""));
124
+ if (pos[0])
125
+ ev.push({ kind: "switch", worktree: pos[0], ref: pos[1], dir: wt[1] });
126
+ }
127
+ return ev;
128
+ }
129
+ // ── What executes code ────────────────────────────────────────────────────────
130
+ const EXEC_RE = new RegExp([
131
+ String.raw `\b(?:npm|pnpm|yarn|bun)\s+(?:install|i|ci|add|rebuild|run|run-script|test|t|start|build|exec|x|dlx|pack)\b`,
132
+ String.raw `\byarn\s*$`,
133
+ String.raw `\b(?:npx|pnpx|bunx|tsx|ts-node|deno|node|nodemon)\b(?!\s+(?:-v|--version)\b)`,
134
+ String.raw `\bpython[0-9.]*\b(?!\s+(?:-V|--version)\b)`,
135
+ String.raw `\b(?:pytest|tox|nox|pipenv)\b|\bpip[0-9.]*\s+install\b|\buv\s+(?:run|sync|pip\s+install)\b|\bpoetry\s+(?:install|run)\b`,
136
+ String.raw `\b(?:ruby|rake|rspec|rails)\b|\bbundle\s+(?:install|exec)\b`,
137
+ String.raw `\bgo\s+(?:run|test|build|generate|install|vet)\b`,
138
+ String.raw `\bcargo\s+(?:run|test|build|bench|check|clippy|install)\b`,
139
+ String.raw `\b(?:make|gmake|cmake|ninja|bazel|gradle|mvn|meson|just)\b`,
140
+ String.raw `\b(?:php|perl)\b|\bcomposer\s+install\b|\bjava\s+-jar\b|\b(?:dotnet|swift)\s+(?:run|test|build)\b|\bxcodebuild\b|\bmix\s+(?:test|run|compile|deps\.get)\b`,
141
+ String.raw `(?:^|[\s;&|(])\.{1,2}/[\w.-]`,
142
+ String.raw `\b(?:bash|sh|zsh)\s+(?!-c\b)[^\s-]`,
143
+ String.raw `(?:^|[;&|]\s*)(?:source|\.)\s+\S`,
144
+ String.raw `\bdocker\s+(?:build|buildx\s+build|compose\s+(?:up|build|run))\b`,
145
+ ].join("|"));
146
+ export function execKind(name, args) {
147
+ if (SHELL_ANY.has(name))
148
+ return EXEC_RE.test(String(args.command ?? "")) ? "shell" : null;
149
+ if (name === "verify_pipeline") {
150
+ const stages = Array.isArray(args.stages) ? args.stages : [];
151
+ return stages.some((s) => EXEC_RE.test(String(s?.command ?? ""))) ? "shell" : null;
152
+ }
153
+ if (name === "pkg_install" || name === "validate")
154
+ return "opaque";
155
+ return null;
156
+ }
157
+ /** The marked trees and the owner's answers, shared by a session and the sub-agents it starts. */
158
+ export class PrTrees {
159
+ trees = new Map();
160
+ /** Branch names and commit shas fetched from a PR. */
161
+ refs = new Map();
162
+ /** Patch files written from a PR diff. */
163
+ patches = new Map();
164
+ /** `${root}@${sha}` the owner chose to run on the host. */
165
+ hostOk = new Set();
166
+ /** Trees the owner (or an unattended run) put in isolation, and whether that isolation has the network. */
167
+ isolated = new Map();
168
+ probe;
169
+ /** The marked tree holding `dir`, if any. */
170
+ treeFor(dir) {
171
+ for (const t of this.trees.values())
172
+ if (dir === t.root || dir.startsWith(`${t.root}/`))
173
+ return t;
174
+ return undefined;
175
+ }
176
+ }
177
+ // ── Detection (observe what a call did) ───────────────────────────────────────
178
+ /** Did the call run to a zero exit? Tool results carry `[exit N]` / `(no output; exit N)` on failure. */
179
+ export function succeeded(result) {
180
+ const r = result.trim();
181
+ if (/^(?:error|Permission denied|Blocked|Held|\[engine note)/i.test(r))
182
+ return false;
183
+ if (/\[timed out|\[interrupted/.test(r))
184
+ return false;
185
+ const exit = /(?:\[exit (\d+)\]|\(no output; exit (\d+|\?)\))\s*(?:\n\[note[^\n]*)*$/.exec(r);
186
+ return !exit || (exit[1] ?? exit[2]) === "0";
187
+ }
188
+ function commandOf(name, args) {
189
+ if (SHELL_ANY.has(name))
190
+ return String(args.command ?? "");
191
+ if (name === "git_command")
192
+ return `git ${(Array.isArray(args.args) ? args.args.map(String) : [String(args.args ?? "")]).join(" ")}`;
193
+ return null;
194
+ }
195
+ function baseDir(args, ctx) {
196
+ const shellAt = ctx.shell.dir;
197
+ if (typeof args.cwd === "string" && args.cwd)
198
+ return join(shellAt ?? ctx.cwd, args.cwd.replace(/^~(?=\/|$)/, (ctx.env ?? env()).HOME ?? "~"));
199
+ return shellAt;
200
+ }
201
+ async function toplevel(dir, ctx) {
202
+ return (await ctx.git(dir, ["rev-parse", "--show-toplevel"])) || dir;
203
+ }
204
+ const normUrl = (u) => u.trim().replace(/\.git$/, "").replace(/^[a-z+]+:\/\/(?:[^@/]+@)?/, "").replace(/^[^@/]+@([^:]+):/, "$1/").toLowerCase();
205
+ /** "remote/branch" when HEAD's branch (or the ref checked out) comes from a remote that is not this repo's origin. */
206
+ async function forkOf(root, branch, ref, ctx) {
207
+ let remote = null;
208
+ if (branch && branch !== "HEAD")
209
+ remote = await ctx.git(root, ["config", `branch.${branch}.remote`]);
210
+ if (!remote && ref) {
211
+ const remotes = ((await ctx.git(root, ["remote"])) ?? "").split("\n").filter(Boolean);
212
+ remote = remotes.find((r) => ref.startsWith(`${r}/`)) ?? null;
213
+ }
214
+ if (!remote || remote === "origin" || remote === ".")
215
+ return undefined;
216
+ const url = await ctx.git(root, ["remote", "get-url", remote]);
217
+ const origin = await ctx.git(root, ["remote", "get-url", "origin"]);
218
+ if (url && origin && normUrl(url) === normUrl(origin))
219
+ return undefined;
220
+ return `${remote}/${branch && branch !== "HEAD" ? branch : (ref ?? "").slice(remote.length + 1)}`;
221
+ }
222
+ function mark(trees, t, ctx) {
223
+ const prev = trees.trees.get(t.root);
224
+ trees.trees.set(t.root, prev?.sticky && !t.sticky ? { ...t, sticky: true, pr: t.pr ?? prev.pr } : t);
225
+ if (!prev || prev.pr !== t.pr || prev.fork !== t.fork)
226
+ ctx.audit?.(`marked ${t.root} untrusted: ${label(t)} (${t.how})`);
227
+ }
228
+ const label = (t) => (t.pr !== undefined ? `PR #${t.pr}` : t.fork ? `fork branch ${t.fork}` : "a PR");
229
+ /** Re-read a tree after a checkout / switch / worktree add: a PR ref or a fork branch marks it, the owner's own branch
230
+ * clears it (unless a PR diff was applied there). */
231
+ async function evaluate(root, ref, trees, ctx) {
232
+ const head = await ctx.git(root, ["rev-parse", "HEAD"]);
233
+ const branch = await ctx.git(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
234
+ const pr = (branch && branch !== "HEAD" ? trees.refs.get(branch) : undefined) ?? (head ? trees.refs.get(head) : undefined) ?? (ref ? trees.refs.get(ref) : undefined);
235
+ if (pr !== undefined)
236
+ return mark(trees, { root, pr, how: `checked out ${branch && branch !== "HEAD" ? branch : (ref ?? "a PR ref")}` }, ctx);
237
+ const fork = await forkOf(root, branch, ref, ctx);
238
+ if (fork)
239
+ return mark(trees, { root, fork, how: "checked out a branch from a fork remote" }, ctx);
240
+ const prev = trees.trees.get(root);
241
+ if (prev && !prev.sticky) {
242
+ trees.trees.delete(root);
243
+ ctx.audit?.(`cleared ${root}: back on ${branch ?? "an owner branch"}`);
244
+ }
245
+ }
246
+ /** Record what a finished call did to the working trees, and where the persistent shell now is. */
247
+ export async function observe(name, args, result, ctx, trees) {
248
+ const command = commandOf(name, args);
249
+ if (command === null)
250
+ return;
251
+ const home = (ctx.env ?? env()).HOME ?? "";
252
+ const base = name === "git_command" ? baseDir(args, ctx) ?? ctx.cwd : baseDir(args, ctx);
253
+ const segs = name === "git_command" ? [{ text: command, dir: undefined }] : segments(command, home);
254
+ if (SHELL_FOREGROUND.has(name) && !(typeof args.cwd === "string" && args.cwd)) {
255
+ // A `cd` in the persistent shell moves it for the next call, whether or not the rest succeeded.
256
+ const last = segments(`${command}\ntrue`, home).pop();
257
+ if (last.dir === null)
258
+ ctx.shell.dir = null;
259
+ else if (last.dir !== undefined)
260
+ ctx.shell.dir = ctx.shell.dir === null && !last.dir.startsWith("/") ? null : join(ctx.shell.dir ?? ctx.cwd, last.dir);
261
+ }
262
+ if (!succeeded(result))
263
+ return;
264
+ for (const seg of segs) {
265
+ const evs = prEvents(seg.text);
266
+ if (!evs.length)
267
+ continue;
268
+ const segDir = seg.dir === null ? null : join(base ?? ctx.cwd, seg.dir ?? ".");
269
+ for (const ev of evs) {
270
+ const dir = segDir === null ? (base ?? ctx.cwd) : ev.dir ? join(segDir, ev.dir) : segDir;
271
+ if (ev.kind === "fetch") {
272
+ if (ev.ref)
273
+ trees.refs.set(ev.ref, ev.pr);
274
+ const sha = await ctx.git(dir, ["rev-parse", ev.ref ?? "FETCH_HEAD"]);
275
+ if (sha)
276
+ trees.refs.set(sha, ev.pr);
277
+ }
278
+ else if (ev.kind === "patch-file") {
279
+ trees.patches.set(join(dir, ev.file), ev.pr);
280
+ }
281
+ else if (ev.kind === "gh-checkout") {
282
+ const root = await toplevel(dir, ctx);
283
+ const branch = await ctx.git(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
284
+ if (ev.pr !== undefined && branch && branch !== "HEAD")
285
+ trees.refs.set(branch, ev.pr);
286
+ mark(trees, { root, pr: ev.pr, how: "gh pr checkout" }, ctx);
287
+ }
288
+ else if (ev.kind === "apply") {
289
+ const file = ev.file ? join(dir, ev.file) : undefined;
290
+ if (file && !trees.patches.has(file))
291
+ continue; // a patch the owner has, not one from a PR
292
+ const root = await toplevel(dir, ctx);
293
+ mark(trees, { root, pr: ev.pr ?? (file ? trees.patches.get(file) : undefined), how: "applied a PR diff", sticky: true }, ctx);
294
+ }
295
+ else {
296
+ const root = ev.worktree ? join(dir, ev.worktree) : await toplevel(dir, ctx);
297
+ await evaluate(root, ev.ref, trees, ctx);
298
+ }
299
+ }
300
+ }
301
+ }
302
+ // ── Gate ──────────────────────────────────────────────────────────────────────
303
+ /** The marked tree this call would execute code in, or undefined. A directory that cannot be known counts as inside
304
+ * a marked tree (false positives only ask). */
305
+ export function heldTree(name, args, ctx, trees) {
306
+ if (!trees.trees.size || !execKind(name, args))
307
+ return undefined;
308
+ const base = baseDir(args, ctx);
309
+ const cmds = name === "verify_pipeline"
310
+ ? (Array.isArray(args.stages) ? args.stages : []).map((s) => String(s?.command ?? ""))
311
+ : [String(args.command ?? "")];
312
+ for (const t of trees.trees.values())
313
+ if (cmds.some((c) => c.includes(t.root)))
314
+ return t;
315
+ const first = trees.trees.values().next().value;
316
+ if (base === null)
317
+ return first;
318
+ for (const cmd of cmds) {
319
+ for (const seg of segments(cmd, (ctx.env ?? env()).HOME ?? "")) {
320
+ if (seg.dir === null || (base === null && !seg.dir?.startsWith("/")))
321
+ return first;
322
+ const dir = seg.dir === undefined ? base : join(base, seg.dir);
323
+ const t = trees.treeFor(dir);
324
+ if (t)
325
+ return t;
326
+ }
327
+ }
328
+ if (!SHELL_ANY.has(name) && name !== "verify_pipeline")
329
+ return trees.treeFor(base) ?? (typeof args.cwd === "string" ? undefined : first);
330
+ return undefined;
331
+ }
332
+ const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
333
+ /** The command rewritten to run under the confirmed backend: writes only in the tree, the scratch dir and temp; no
334
+ * network unless the owner chose it. Package caches are pointed into the scratch dir so an install can work. */
335
+ export function isolate(command, backend, root, scratch, network, e = env()) {
336
+ const tmp = [...new Set(["/tmp", "/private/tmp", e.TMPDIR].filter((p) => !!p).flatMap((p) => (p.startsWith("/var/") ? [p, `/private${p}`] : [p])))];
337
+ const scope = { writeRoots: [root, scratch, ...tmp], network };
338
+ const cache = `${scratch}/pr-cache`;
339
+ const inner = `export npm_config_cache=${q(`${cache}/npm`)} XDG_CACHE_HOME=${q(cache)} PIP_CACHE_DIR=${q(`${cache}/pip`)}\n${command}`;
340
+ if (backend === "seatbelt")
341
+ return `/usr/bin/sandbox-exec -p ${q(seatbeltProfile("strict", scope))} /bin/bash -c ${q(inner)}`;
342
+ return `bwrap ${bwrapArgs("strict", scope).map(q).join(" ")} /bin/bash -c ${q(inner)}`;
343
+ }
344
+ function isolatedArgs(name, args, wrap) {
345
+ if (name === "verify_pipeline" && Array.isArray(args.stages)) {
346
+ return { ...args, stages: args.stages.map((s) => ({ ...s, command: wrap(String(s.command ?? "")) })) };
347
+ }
348
+ return { ...args, command: wrap(String(args.command ?? "")) };
349
+ }
350
+ const head = (name, args) => {
351
+ const c = SHELL_ANY.has(name) ? String(args.command ?? "") : name;
352
+ return c.length > 80 ? `${c.slice(0, 77)}…` : c;
353
+ };
354
+ export const HOST_OPTION = "Run on the host (I trust this PR)";
355
+ export const HOST_UNSAFE_OPTION = "Run on the host: UNSAFE, no isolation could be confirmed on this box";
356
+ export const CANCEL_OPTION = "Cancel";
357
+ const ISOLATE_OPTION = (p) => `Run in isolation: ${p.label ?? p.backend}, network off (recommended)`;
358
+ const ISOLATE_NET_OPTION = (p) => `Run in isolation: ${p.label ?? p.backend}, network on (installs need it)`;
359
+ /** The question and choices put to the owner. */
360
+ export function preflightQuestion(name, args, tree, sha, probe, s) {
361
+ const where = `${tree.root} @ ${sha.slice(0, 7)}`;
362
+ const also = probe.reportOnly.length ? ` Also on this box, not wired here (run it yourself): ${probe.reportOnly.join(", ")}.` : "";
363
+ const question = `\`${head(name, args)}\` would run code from ${label(tree)} (${where}), which you did not write. Where should it run?${also}`;
364
+ if (!probe.backend)
365
+ return { question: `${question} No isolation could be confirmed: ${probe.detail.join("; ")}.`, options: [HOST_UNSAFE_OPTION, CANCEL_OPTION] };
366
+ const options = [ISOLATE_OPTION(probe)];
367
+ if (s.network === "ask")
368
+ options.push(ISOLATE_NET_OPTION(probe));
369
+ options.push(HOST_OPTION, CANCEL_OPTION);
370
+ return { question, options };
371
+ }
372
+ /** Which offered option the reply picked; anything unrecognised is Cancel (fail closed). */
373
+ export function pickOption(answer, options) {
374
+ const a = answer.trim();
375
+ const n = /^(\d)\b/.exec(a);
376
+ if (n && options[Number(n[1]) - 1])
377
+ return options[Number(n[1]) - 1];
378
+ return options.find((o) => a === o || a.startsWith(o) || o.startsWith(a) && a.length > 12) ?? CANCEL_OPTION;
379
+ }
380
+ const HELD = (name, why) => engineNote(`PR preflight: "${name}" was not run. ${why} Do not retry it or an equivalent; continue with what does not run the PR's code, or report this step for the owner.`);
381
+ /** Decide a held call: run as-is (host), run rewritten (isolation), or refuse. */
382
+ export async function preflight(name, args, tree, ctx, trees) {
383
+ const s = ctx.settings ?? live;
384
+ const sha = (await ctx.git(tree.root, ["rev-parse", "HEAD"])) ?? "unknown";
385
+ const key = `${tree.root}@${sha}`;
386
+ const runIsolated = (p, network) => {
387
+ if (execKind(name, args) === "opaque")
388
+ return { refuse: HELD(name, `${name} cannot run inside the isolation chosen for ${label(tree)}; run the same step through bash, which runs it isolated.`) };
389
+ const wrap = (c) => isolate(c, p.backend, tree.root, ctx.scratch, network, ctx.env ?? env());
390
+ return { run: isolatedArgs(name, args, wrap), note: `[pr preflight: ran isolated (${p.label ?? p.backend}, network ${network ? "on" : "off"}, writes only in ${tree.root}, scratch and temp)]` };
391
+ };
392
+ const chosen = trees.isolated.get(tree.root);
393
+ if (chosen) {
394
+ const p = await (trees.probe ??= ctx.probe());
395
+ if (p.backend)
396
+ return runIsolated(p, chosen.network);
397
+ }
398
+ if (trees.hostOk.has(key))
399
+ return { run: args };
400
+ const p = await (trees.probe ??= ctx.probe());
401
+ if (!ctx.ask) {
402
+ if (!p.backend) {
403
+ ctx.audit?.(`refused ${head(name, args)} in ${key}: unattended, no isolation confirmed`);
404
+ return { refuse: HELD(name, `It would run code from ${label(tree)} (${tree.root}), nobody is here to approve the host, and no isolation could be confirmed on this box (${p.detail.join("; ")}). Unattended runs never run untrusted PR code on the host.`) };
405
+ }
406
+ trees.isolated.set(tree.root, { network: false });
407
+ ctx.audit?.(`isolated ${key} (${p.backend}, network off): unattended`);
408
+ return runIsolated(p, false);
409
+ }
410
+ const { question, options } = preflightQuestion(name, args, tree, sha, p, s);
411
+ const pick = pickOption(await ctx.ask(question, options), options);
412
+ if (pick === HOST_OPTION || pick === HOST_UNSAFE_OPTION) {
413
+ trees.hostOk.add(key);
414
+ ctx.audit?.(`owner chose HOST for ${label(tree)} at ${key}${p.backend ? "" : " (no isolation confirmed)"}`);
415
+ return { run: args };
416
+ }
417
+ if (p.backend && (pick === ISOLATE_OPTION(p) || pick === ISOLATE_NET_OPTION(p))) {
418
+ const network = pick === ISOLATE_NET_OPTION(p);
419
+ trees.isolated.set(tree.root, { network });
420
+ ctx.audit?.(`owner chose isolation for ${label(tree)} at ${key} (${p.backend}, network ${network ? "on" : "off"})`);
421
+ return runIsolated(p, network);
422
+ }
423
+ ctx.audit?.(`owner cancelled ${head(name, args)} in ${key}`);
424
+ return { refuse: HELD(name, `The owner cancelled running code from ${label(tree)} (${tree.root}).`) };
425
+ }
426
+ /** Hold calls that would run PR code, and watch shell/git calls for PR checkouts. Off (setting or env) = pass-through
427
+ * apart from the bookkeeping, so turning it on mid-session still knows what is checked out. */
428
+ export function withPrPreflight(inner, ctx) {
429
+ const on = () => prPreflightOn(ctx.env ?? env(), ctx.settings ?? live);
430
+ const within = (t, fn) => (ctx.within ? ctx.within(t, fn) : fn());
431
+ const one = async (name, args, run, refused) => {
432
+ const trees = ctx.trees();
433
+ const tree = on() ? heldTree(name, args, ctx, trees) : undefined;
434
+ let callArgs = args;
435
+ let note;
436
+ if (tree) {
437
+ const o = await preflight(name, args, tree, ctx, trees);
438
+ if ("refuse" in o) {
439
+ refused();
440
+ return o.refuse;
441
+ }
442
+ callArgs = o.run;
443
+ note = o.note;
444
+ }
445
+ const result = await within(trees, () => run(callArgs));
446
+ await observe(name, args, result, ctx, trees).catch(() => { });
447
+ return note ? `${result}\n${note}` : result;
448
+ };
449
+ return {
450
+ sched: inner.sched,
451
+ execute: (name, args, report) => one(name, args, (a) => inner.execute(name, a, report), () => report?.refused("blocked")),
452
+ executeParallel: async (calls, onSettle, signal, onStart) => {
453
+ const trees = ctx.trees();
454
+ const watched = calls.some((c) => commandOf(c.name, c.args) !== null);
455
+ const held = on() && calls.some((c) => heldTree(c.name, c.args, ctx, trees));
456
+ if (!held) {
457
+ const out = await within(trees, () => inner.executeParallel(calls, onSettle, signal, onStart));
458
+ if (watched)
459
+ for (const [i, c] of calls.entries())
460
+ await observe(c.name, c.args, out[i] ?? "", ctx, trees).catch(() => { });
461
+ return out;
462
+ }
463
+ // A held call asks the owner: run the round one call at a time so each answer lands before the next call.
464
+ const results = [];
465
+ for (const [i, c] of calls.entries()) {
466
+ let refused = false;
467
+ const r = await one(c.name, c.args, async (a) => (await inner.executeParallel([{ ...c, args: a }], undefined, signal, () => onStart?.(i)))[0] ?? "", () => { refused = true; });
468
+ results.push(r);
469
+ onSettle?.(i, r, refused ? "blocked" : undefined);
470
+ }
471
+ return results;
472
+ },
473
+ };
474
+ }
@@ -15,6 +15,7 @@ import { resolveMode } from "../classifier/modes.js";
15
15
  import { classifierConfig } from "../classifier/config.js";
16
16
  import { setSpeculation, speculationEnabled } from "../engine/aurora.js";
17
17
  import { setDelegateSettings } from "./delegate-mode.js";
18
+ import { setPrPreflightSettings } from "./pr-preflight.js";
18
19
  /** Build the Aurora router from settings — the headless twin of cli.tsx's buildRouter(). Both share the one
19
20
  * multi-tier chain builder (primary → other fleet nodes → back-compat single failover → cloud), so a
20
21
  * wedged/degraded endpoint fails over through the whole fleet before the turn can error. */
@@ -42,6 +43,7 @@ export function createAutonomySession(settings, opts = {}) {
42
43
  const role = opts.role ?? envSubagentRole();
43
44
  setSpeculation(speculationEnabled(settings)); // GW-26: the owner's opt-out reaches headless, ACP and delegated runs
44
45
  setDelegateSettings(settings.delegate); // delegate mode's guard fences headless, ACP and delegated runs too
46
+ setPrPreflightSettings(settings.prPreflight); // so does the PR preflight (no ask_user here: isolation or refuse)
45
47
  const session = new Session({
46
48
  systemPrompt: role
47
49
  ? subagentSystemPrompt({ cwd: opts.cwd ?? process.cwd(), ctxTokens: modelCtxFor(settings.activeModel, settings.models), type: role })