@0perator/operator 0.2.0 → 0.2.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.
- package/README.md +4 -3
- package/dist/auth/commands.js +7 -3
- package/dist/auth/identity.js +1 -0
- package/dist/auth/staff.js +55 -0
- package/dist/autonomy/delegate-mode.js +2 -2
- package/dist/autonomy/delegate.js +41 -14
- package/dist/autonomy/headless.js +7 -4
- package/dist/autonomy/index.js +2 -4
- package/dist/autonomy/session-factory.js +11 -12
- package/dist/autonomy/subagent-model.js +17 -7
- package/dist/background/capacity.js +136 -0
- package/dist/background/evidence.js +42 -0
- package/dist/background/index.js +311 -44
- package/dist/background/lane-phase.js +60 -0
- package/dist/background/lane-summary.js +151 -0
- package/dist/background/notices.js +12 -3
- package/dist/background/synthesis.js +25 -0
- package/dist/bus/inbox.js +150 -6
- package/dist/cli.js +191 -96
- package/dist/config/features.js +3 -3
- package/dist/config/persona.js +29 -3
- package/dist/config/settings.js +261 -20
- package/dist/config/staff-prompt.js +12 -0
- package/dist/engine/agent.js +51 -40
- package/dist/engine/aurora.js +36 -4
- package/dist/engine/batch-scheduler.js +4 -13
- package/dist/engine/compaction.js +1 -1
- package/dist/engine/continuation.js +30 -32
- package/dist/engine/decision-points.js +2 -3
- package/dist/engine/fanout.js +16 -0
- package/dist/engine/loop-guard.js +26 -83
- package/dist/engine/messages.js +2 -2
- package/dist/engine/moa.js +16 -1
- package/dist/engine/native-vision-node.js +72 -0
- package/dist/engine/native-vision.js +103 -0
- package/dist/engine/verify-gate.js +37 -7
- package/dist/gateway-cli.js +14 -3
- package/dist/memory/live-progress.js +4 -5
- package/dist/moa/codeact-lane.js +98 -0
- package/dist/moa/codeact-sandbox.js +409 -0
- package/dist/moa/codeact.js +140 -0
- package/dist/permissions/artifact-visibility.js +10 -0
- package/dist/permissions/tier.js +4 -2
- package/dist/products/craft.js +2 -2
- package/dist/remote/grants.js +119 -0
- package/dist/remote/host.js +33 -5
- package/dist/router/models.js +24 -14
- package/dist/selfimprove/index.js +8 -6
- package/dist/services/preflight.js +35 -91
- package/dist/session.js +127 -41
- package/dist/skills/install-guard.js +68 -0
- package/dist/skills/install.js +67 -0
- package/dist/toolchain/manifest.json +13 -13
- package/dist/tools/background-result.js +1 -1
- package/dist/tools/classes.js +103 -0
- package/dist/tools/contract.js +1 -1
- package/dist/tools/craft.js +13 -2
- package/dist/tools/executor.js +25 -15
- package/dist/tools/generation-gateway.js +94 -0
- package/dist/tools/registry.js +83 -152
- package/dist/ui/App.js +15 -4
- package/dist/ui/BgPanel.js +15 -10
- package/dist/ui/Header.js +1 -6
- package/dist/ui/StatusRule.js +18 -7
- package/dist/ui/ToolStep.js +3 -3
- package/dist/ui/Transcript.js +36 -14
- package/dist/ui/batchLine.js +4 -4
- package/dist/ui/editdiff.js +2 -4
- package/dist/ui/format.js +4 -20
- package/dist/ui/liveTools.js +3 -3
- package/dist/ui/opsMode.js +20 -0
- package/dist/ui/types.js +0 -2
- package/dist/update-check.js +17 -6
- package/package.json +1 -1
- package/dist/tools/mutating.js +0 -15
|
@@ -12,21 +12,20 @@
|
|
|
12
12
|
// its plan over what the owner typed. freshHandoff drops live blocks past LIVE_MAX_AGE_MS as a second guard.
|
|
13
13
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
14
14
|
import { dirname, relative, isAbsolute } from "node:path";
|
|
15
|
+
import { FILE_WRITE, PLAN_WRITE, ranOk } from "../tools/classes.js";
|
|
15
16
|
export const LIVE_START = "<!-- live-progress:start";
|
|
16
17
|
export const LIVE_END = "<!-- live-progress:end -->";
|
|
17
|
-
const MUTATING = new Set(["file_write", "file_edit", "task_add", "task_update", "task_clear"]);
|
|
18
18
|
const MAX_FILES = 12;
|
|
19
19
|
const MAX_TASK_CHARS = 80;
|
|
20
20
|
const MAX_BLOCK_CHARS = 1500;
|
|
21
|
-
const
|
|
22
|
-
const landed = (e) => !ERROR_RESULT.test(e.result ?? "");
|
|
21
|
+
const landed = (e) => ranOk(e.result ?? "");
|
|
23
22
|
/** True when a tool round changed state worth journaling (a failed write is not progress). */
|
|
24
23
|
export function roundProgressed(events) {
|
|
25
|
-
return events.some((e) =>
|
|
24
|
+
return events.some((e) => (FILE_WRITE.has(e.name) || PLAN_WRITE.has(e.name)) && landed(e));
|
|
26
25
|
}
|
|
27
26
|
/** The file paths a round actually touched (file_write / file_edit `path` whose result was not an error). */
|
|
28
27
|
export function touchedPaths(events) {
|
|
29
|
-
return events.filter((e) => (e.name
|
|
28
|
+
return events.filter((e) => FILE_WRITE.has(e.name) && landed(e)).map((e) => String(e.args?.path ?? "")).filter(Boolean);
|
|
30
29
|
}
|
|
31
30
|
const MARK = { pending: "[ ]", in_progress: "[>]", done: "[x]", cancelled: "[~]" };
|
|
32
31
|
const openTag = (session) => `${LIVE_START} ${session} -->`;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { codeActConfig, codeActReport } from "./codeact.js";
|
|
2
|
+
// The sandbox imports node builtins: an opaque specifier keeps it out of the platform-neutral bundle (conventions/kode-tsi.md).
|
|
3
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
4
|
+
/** Runs at most this many programs per delegated step: the program, and one fix after a failure. */
|
|
5
|
+
export const CODEACT_MAX_RUNS = 2;
|
|
6
|
+
/** The only tools an executor holds on a lane step besides codeact_run: reads. The step's read-only claim is enforced by
|
|
7
|
+
* the tool set (no shell, no writes), not trusted. */
|
|
8
|
+
export const CODEACT_STEP_TOOLS = ["file_read", "read_files", "list_directory", "glob", "find_files", "search", "grep_search"];
|
|
9
|
+
/** delegate_task's extra properties while moa.codeact.enabled; the schema is unchanged when it is off. */
|
|
10
|
+
export const CODEACT_DELEGATE_PROPS = {
|
|
11
|
+
lane: { type: "string", enum: ["tools", "codeact"], description: "codeact: a bulk, read-only, deterministic step done by ONE sandboxed program (no network, no secrets, writes only to scratch). Checked in code; a step that fails the check runs on tools and you are told why. Default tools." },
|
|
12
|
+
targets: { type: "array", items: { type: "string" }, description: "codeact: the paths the program reads (the step's repo dirs, logs, files)" },
|
|
13
|
+
items: { type: "number", description: "codeact: how many items the step covers (files, lines, records)" },
|
|
14
|
+
est_round_trips: { type: "number", description: "codeact: tool calls the step would take with tools" },
|
|
15
|
+
read_only: { type: "boolean", description: "codeact: true only if the step changes nothing" },
|
|
16
|
+
deterministic: { type: "boolean", description: "codeact: true only if the same inputs always give the same answer" },
|
|
17
|
+
needs_network: { type: "boolean" },
|
|
18
|
+
needs_secrets: { type: "boolean" },
|
|
19
|
+
};
|
|
20
|
+
/** delegate_task with the lane's properties added (a copy; the registry's tool is untouched). */
|
|
21
|
+
export function withCodeActDelegateSchema(base) {
|
|
22
|
+
const params = base.parameters;
|
|
23
|
+
return {
|
|
24
|
+
...base,
|
|
25
|
+
description: `${base.description} Lane: pass lane:"codeact" with targets, items or est_round_trips, read_only, deterministic for a bulk read-only step (scan, count, batch check, log analysis); the sub-agent then does it in one sandboxed program.`,
|
|
26
|
+
parameters: { ...base.parameters, properties: { ...params.properties, ...CODEACT_DELEGATE_PROPS } },
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
const bool = (v) => v === true || v === "true";
|
|
30
|
+
const num = (v) => (typeof v === "number" ? v : typeof v === "string" && v.trim() && Number.isFinite(Number(v)) ? Number(v) : undefined);
|
|
31
|
+
/** The step a delegate_task call claims, or undefined when it did not ask for the lane. Missing flags read as false. */
|
|
32
|
+
export function codeActStepFromArgs(args, author) {
|
|
33
|
+
if (String(args.lane ?? "").trim().toLowerCase() !== "codeact")
|
|
34
|
+
return undefined;
|
|
35
|
+
const t = args.targets;
|
|
36
|
+
const targets = Array.isArray(t) ? t.map(String) : typeof t === "string" ? t.split(/[,\n]/).map((s) => s.trim()).filter(Boolean) : [];
|
|
37
|
+
return {
|
|
38
|
+
readOnly: bool(args.read_only), deterministic: bool(args.deterministic),
|
|
39
|
+
needsNetwork: bool(args.needs_network), needsSecrets: bool(args.needs_secrets),
|
|
40
|
+
items: num(args.items), estRoundTrips: num(args.est_round_trips), targets, author,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** What the executor is told on top of the planner's task. */
|
|
44
|
+
export function codeActBrief(task, targets, language) {
|
|
45
|
+
const lang = language === "python" ? "Python 3 (standard library only)" : "Node (ES module, node:fs / node:path only)";
|
|
46
|
+
return [
|
|
47
|
+
task,
|
|
48
|
+
"",
|
|
49
|
+
"## How to do this step: the CodeAct lane",
|
|
50
|
+
`Do the whole step with ONE call to codeact_run: a short ${lang} program that reads the targets and computes the answer.`,
|
|
51
|
+
`- Targets (read-only): ${targets.join(", ")}. The program's working directory is the first target; the paths are also in`,
|
|
52
|
+
" argv[1:] and the CODEACT_TARGETS environment variable (JSON).",
|
|
53
|
+
"- It may write only under CODEACT_SCRATCH. No network, no subprocesses or shells, no secrets: they are blocked.",
|
|
54
|
+
'- Its LAST stdout line must be one JSON object: {"summary": "<one plain line>", "data": <the result>}.',
|
|
55
|
+
"- Your other tools here only read (no shell). Look first only if you must (one quick listing); then write the program.",
|
|
56
|
+
" If it fails, fix it once from the error.",
|
|
57
|
+
"- Do not edit, commit or send anything in this step. Answer with the summary and the data as the step's report.",
|
|
58
|
+
].join("\n");
|
|
59
|
+
}
|
|
60
|
+
/** The executor's `codeact_run`: runs the program in the sandbox over the step's checked targets, at most
|
|
61
|
+
* CODEACT_MAX_RUNS times. */
|
|
62
|
+
export function makeCodeActTool(ctx) {
|
|
63
|
+
let runs = 0;
|
|
64
|
+
const cfg = codeActConfig(ctx.settings);
|
|
65
|
+
return {
|
|
66
|
+
name: "codeact_run",
|
|
67
|
+
description: `Run ONE short program over this step's read-only targets in a sandbox (no network, no subprocesses, writes only to CODEACT_SCRATCH) and get its JSON result back. The program's last stdout line must be {"summary": "...", "data": ...}. At most ${CODEACT_MAX_RUNS} runs for this step.`,
|
|
68
|
+
safe: false,
|
|
69
|
+
contract: { v: 1, effects: ["exec", "read"], bins: ["sandbox-exec", "bwrap", "python3", "node"] },
|
|
70
|
+
parameters: {
|
|
71
|
+
type: "object",
|
|
72
|
+
properties: {
|
|
73
|
+
program: { type: "string", description: `the whole program text (at most ${cfg.maxProgramBytes} bytes)` },
|
|
74
|
+
language: { type: "string", enum: ["python", "node"], description: `default ${ctx.language}` },
|
|
75
|
+
},
|
|
76
|
+
required: ["program"],
|
|
77
|
+
},
|
|
78
|
+
run: async (a) => {
|
|
79
|
+
if (runs >= CODEACT_MAX_RUNS)
|
|
80
|
+
return `error: codeact_run: this step already used its ${CODEACT_MAX_RUNS} runs; finish it with your other tools or report what failed`;
|
|
81
|
+
runs++;
|
|
82
|
+
const language = a.language === "node" || a.language === "python" ? a.language : ctx.language;
|
|
83
|
+
const req = { language, program: String(a.program ?? ""), targets: ctx.targets, settings: ctx.settings };
|
|
84
|
+
const run = ctx.runner ?? (await nodeImport("./codeact-sandbox.js")).runCodeAct;
|
|
85
|
+
const r = await run(req);
|
|
86
|
+
ctx.onResult?.(r);
|
|
87
|
+
return codeActReport(r);
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** The one-line trace a delegation appends to its report: how the lane ran, where the program and result are kept. */
|
|
92
|
+
export function codeActTraceLine(results) {
|
|
93
|
+
if (!results.length)
|
|
94
|
+
return "[codeact trace: no program ran]";
|
|
95
|
+
const last = results[results.length - 1];
|
|
96
|
+
const ms = results.reduce((s, r) => s + r.stats.wallMs, 0);
|
|
97
|
+
return `[codeact trace: ${last.status} · ${results.length} program run${results.length === 1 ? "" : "s"} · ${ms} ms · ${last.sandbox.mechanism} · ${last.program.language} sha256 ${last.program.sha256.slice(0, 12)}${last.runDir ? ` · ${last.runDir}` : ""}]`;
|
|
98
|
+
}
|
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
// The CodeAct lane's sandbox runner: runs ONE executor-written program (Python or Node) over read-only targets and returns
|
|
2
|
+
// structured data. Node CLI only; callers load it with a dynamic import (it imports node builtins).
|
|
3
|
+
//
|
|
4
|
+
// Layers, outermost first:
|
|
5
|
+
// 1. OS sandbox, required. macOS: sandbox-exec with a profile built per run (no network, no fork, exec only inside the
|
|
6
|
+
// interpreter's own install, writes only to the run's scratch dir, file contents under the home folder, temp and
|
|
7
|
+
// /Volumes unreadable except the targets and the run dir, secret paths unreadable even as metadata, no keychain,
|
|
8
|
+
// pasteboard or Apple events). Linux: bubblewrap with every namespace unshared (network included), only the system
|
|
9
|
+
// dirs, the interpreter, the targets (read-only) and the scratch dir (writable) mounted, secret paths masked and the
|
|
10
|
+
// shells replaced with /dev/null. Anything else, or a probe that fails: nothing runs (status sandbox_unavailable).
|
|
11
|
+
// 2. Interpreter guards. Python runs -I -S -B under an audit hook that refuses sockets, subprocesses, exec, fork,
|
|
12
|
+
// ctypes and writes outside scratch, with RLIMIT_CPU / RLIMIT_FSIZE (and RLIMIT_AS on Linux). Node runs under its
|
|
13
|
+
// permission model (fs read: targets + run dir; fs write: scratch; no child processes, workers, addons or network)
|
|
14
|
+
// with a heap cap.
|
|
15
|
+
// 3. A screen before anything runs: size cap and the denied constructs (network, process and dynamic-code modules).
|
|
16
|
+
// 4. The parent: a scrubbed environment, a wall clock, a resident-memory ceiling over the process tree and an output
|
|
17
|
+
// ceiling, each enforced by killing the process group.
|
|
18
|
+
// The program prints one JSON object as its last stdout line: {"summary": "<one line>", "data": <anything>}.
|
|
19
|
+
import { execFile, spawn } from "node:child_process";
|
|
20
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
21
|
+
import { existsSync, realpathSync, statSync } from "node:fs";
|
|
22
|
+
import { mkdir, readdir, rm, writeFile } from "node:fs/promises";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { dirname, join } from "node:path";
|
|
25
|
+
import { get_operator_home, operatorPath } from "../config/home.js";
|
|
26
|
+
import { redactSecrets } from "../engine/redact.js";
|
|
27
|
+
import { ownChild } from "../util/owned-children.js";
|
|
28
|
+
import { codeActConfig, secretPaths } from "./codeact.js";
|
|
29
|
+
const execFileOk = (file, args, timeout = 5000) => new Promise((res) => execFile(file, args, { timeout, env: { PATH: "/usr/bin:/bin" } }, (e) => res(!e)));
|
|
30
|
+
let _avail;
|
|
31
|
+
/** Is there an OS sandbox here that can hold a program? Probed once per process. No answer means no lane. */
|
|
32
|
+
export function sandboxAvailability() {
|
|
33
|
+
_avail ??= (async () => {
|
|
34
|
+
if (process.platform === "darwin") {
|
|
35
|
+
if (!existsSync("/usr/bin/sandbox-exec"))
|
|
36
|
+
return { ok: false, reason: "sandbox-exec is missing" };
|
|
37
|
+
return (await execFileOk("/usr/bin/sandbox-exec", ["-p", "(version 1)(allow default)(deny network*)", "/usr/bin/true"]))
|
|
38
|
+
? { ok: true, mechanism: "seatbelt" }
|
|
39
|
+
: { ok: false, reason: "sandbox-exec cannot apply a profile here (already inside a sandbox?)" };
|
|
40
|
+
}
|
|
41
|
+
if (process.platform === "linux") {
|
|
42
|
+
const bwrap = ["/usr/bin/bwrap", "/bin/bwrap", "/usr/local/bin/bwrap"].find((p) => existsSync(p));
|
|
43
|
+
if (!bwrap)
|
|
44
|
+
return { ok: false, reason: "bubblewrap (bwrap) is not installed" };
|
|
45
|
+
const tru = existsSync("/usr/bin/true") ? "/usr/bin/true" : "/bin/true";
|
|
46
|
+
return (await execFileOk(bwrap, ["--unshare-all", "--die-with-parent", "--ro-bind", "/", "/", tru]))
|
|
47
|
+
? { ok: true, mechanism: "bwrap" }
|
|
48
|
+
: { ok: false, reason: "bwrap cannot create namespaces here (unprivileged user namespaces off?)" };
|
|
49
|
+
}
|
|
50
|
+
return { ok: false, reason: `no CodeAct sandbox on ${process.platform}` };
|
|
51
|
+
})();
|
|
52
|
+
return _avail;
|
|
53
|
+
}
|
|
54
|
+
// ---- the screen -------------------------------------------------------------------------------------------------
|
|
55
|
+
const PY_DENIED = [
|
|
56
|
+
[/^\s*(?:import|from)\s+(?:socket|ssl|subprocess|multiprocessing|urllib|http|ftplib|smtplib|poplib|imaplib|telnetlib|asyncio|ctypes|cffi|pty|requests|httpx|aiohttp|paramiko|webbrowser|xmlrpc|socketserver|importlib|code|codeop|runpy|signal)\b/m, "a network, process or dynamic-import module"],
|
|
57
|
+
[/\bos\s*\.\s*(?:system|popen|exec\w*|spawn\w*|fork\w*|posix_spawn\w*|kill\w*|setuid|setgid|chroot|putenv)\b/, "a process call on os"],
|
|
58
|
+
[/\b__import__\s*\(|(?<![.\w])(?:eval|exec|compile|breakpoint)\s*\(/, "dynamic code"],
|
|
59
|
+
];
|
|
60
|
+
const NODE_MODS = "child_process|net|http|https|http2|dgram|tls|dns|worker_threads|cluster|vm|inspector|module|repl|wasi|v8";
|
|
61
|
+
const NODE_DENIED = [
|
|
62
|
+
[new RegExp(`\\b(?:require\\s*\\(\\s*|from\\s+|import\\s+)['"](?:node:)?(?:${NODE_MODS})(?:/[\\w/]*)?['"]`), "a network or process module"],
|
|
63
|
+
[/\bfetch\s*\(|\bWebSocket\b|\bXMLHttpRequest\b|\bEventSource\b/, "the network"],
|
|
64
|
+
[/\bprocess\s*\.\s*(?:binding|dlopen|kill|_linkedBinding)\b/, "a process internal"],
|
|
65
|
+
[/\beval\s*\(|\bnew\s+Function\b|\bimport\s*\(/, "dynamic code"],
|
|
66
|
+
];
|
|
67
|
+
/** Why a program may not run, or undefined. A fast, plain refusal; the sandbox is what actually enforces. */
|
|
68
|
+
export function screenProgram(language, text, maxBytes) {
|
|
69
|
+
const bytes = Buffer.byteLength(text, "utf8");
|
|
70
|
+
if (!text.trim())
|
|
71
|
+
return "the program is empty";
|
|
72
|
+
if (bytes > maxBytes)
|
|
73
|
+
return `the program is ${bytes} bytes; the lane takes at most ${maxBytes}`;
|
|
74
|
+
for (const [re, what] of language === "python" ? PY_DENIED : NODE_DENIED) {
|
|
75
|
+
const m = re.exec(text);
|
|
76
|
+
if (m)
|
|
77
|
+
return `the program uses ${what} (${m[0].trim().slice(0, 40)}); the lane reads files and computes, nothing else`;
|
|
78
|
+
}
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
// ---- interpreters -----------------------------------------------------------------------------------------------
|
|
82
|
+
function findPython(override) {
|
|
83
|
+
const c = [override, process.env.KODE_CODEACT_PYTHON, "/opt/homebrew/bin/python3", "/usr/local/bin/python3", process.platform === "linux" ? "/usr/bin/python3" : undefined];
|
|
84
|
+
return c.find((p) => !!p && existsSync(p));
|
|
85
|
+
}
|
|
86
|
+
function findNode(override) {
|
|
87
|
+
return [override, process.env.KODE_CODEACT_NODE, process.execPath].find((p) => !!p && existsSync(p));
|
|
88
|
+
}
|
|
89
|
+
/** The directory an interpreter's whole install lives in (what it may exec and read): a Homebrew keg, a framework's
|
|
90
|
+
* parent, else two levels up from the real binary. */
|
|
91
|
+
export function interpreterPrefix(bin) {
|
|
92
|
+
let real = bin;
|
|
93
|
+
try {
|
|
94
|
+
real = realpathSync(bin);
|
|
95
|
+
}
|
|
96
|
+
catch { /* keep the given path */ }
|
|
97
|
+
const keg = /^(.*\/Cellar\/[^/]+\/[^/]+)\//.exec(real);
|
|
98
|
+
if (keg)
|
|
99
|
+
return keg[1];
|
|
100
|
+
const fw = /^(.*)\/[^/]+\.framework\//.exec(real);
|
|
101
|
+
if (fw)
|
|
102
|
+
return fw[1];
|
|
103
|
+
return dirname(dirname(real));
|
|
104
|
+
}
|
|
105
|
+
let _nodePerm;
|
|
106
|
+
/** The permission-model flag this node understands ("--permission" from 22.13/23.5, "--experimental-permission" on 20),
|
|
107
|
+
* or null. */
|
|
108
|
+
async function nodePermissionFlag(node) {
|
|
109
|
+
_nodePerm ??= new Map();
|
|
110
|
+
if (_nodePerm.has(node))
|
|
111
|
+
return _nodePerm.get(node);
|
|
112
|
+
let flag = null;
|
|
113
|
+
for (const f of ["--permission", "--experimental-permission"])
|
|
114
|
+
if (await execFileOk(node, [f, "-e", "0"])) {
|
|
115
|
+
flag = f;
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
_nodePerm.set(node, flag);
|
|
119
|
+
return flag;
|
|
120
|
+
}
|
|
121
|
+
const sbq = (s) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
122
|
+
/** The macOS profile for one run. SBPL is last-match-wins: broad denies first, then the run's allows, then the secret
|
|
123
|
+
* denies on top so no allow can reach them. */
|
|
124
|
+
export function codeActSeatbeltProfile(p) {
|
|
125
|
+
const sub = (xs) => xs.map((x) => `(subpath ${sbq(x)})`).join(" ");
|
|
126
|
+
const readable = [p.runDir, ...p.targets, p.interpreterPrefix];
|
|
127
|
+
return [
|
|
128
|
+
"(version 1)",
|
|
129
|
+
"(allow default)",
|
|
130
|
+
"(deny network*)",
|
|
131
|
+
"(deny process-fork)",
|
|
132
|
+
"(deny process-exec*)",
|
|
133
|
+
`(allow process-exec* (subpath ${sbq(p.interpreterPrefix)}))`,
|
|
134
|
+
"(deny file-write*)",
|
|
135
|
+
`(allow file-write* (subpath ${sbq(p.scratch)}) (literal "/dev/null"))`,
|
|
136
|
+
`(deny file-read-data ${sub([p.home, "/Users", "/private/var/folders", "/private/tmp", "/tmp", "/Volumes", "/private/var/root"])})`,
|
|
137
|
+
`(allow file-read-data ${sub(readable)})`,
|
|
138
|
+
`(deny file-read* ${sub(p.secrets)})`,
|
|
139
|
+
'(deny mach-lookup (global-name "com.apple.SecurityServer") (global-name "com.apple.securityd") (global-name "com.apple.security.agent") (global-name "com.apple.pasteboard.1") (global-name "com.apple.coreservices.launchservicesd"))',
|
|
140
|
+
"(deny appleevent-send)",
|
|
141
|
+
].join("\n");
|
|
142
|
+
}
|
|
143
|
+
const SHELLS = ["/bin/sh", "/bin/bash", "/bin/dash", "/bin/zsh", "/usr/bin/sh", "/usr/bin/bash", "/usr/bin/dash", "/usr/bin/zsh", "/bin/busybox", "/usr/bin/busybox"];
|
|
144
|
+
/** The bubblewrap argv (before the interpreter) for one run: a fresh root with only what the program needs. */
|
|
145
|
+
export function codeActBwrapArgs(p, exists = existsSync, isDir = (x) => { try {
|
|
146
|
+
return statSync(x).isDirectory();
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return false;
|
|
150
|
+
} }) {
|
|
151
|
+
const a = ["--unshare-all", "--die-with-parent", "--new-session", "--cap-drop", "ALL"];
|
|
152
|
+
for (const d of ["/usr", "/lib", "/lib64", "/lib32", "/bin", "/sbin"])
|
|
153
|
+
if (exists(d))
|
|
154
|
+
a.push("--ro-bind", d, d);
|
|
155
|
+
for (const f of ["/etc/ld.so.cache", "/etc/ld.so.conf", "/etc/ld.so.conf.d", "/etc/localtime", "/etc/alternatives", "/etc/ssl/openssl.cnf"])
|
|
156
|
+
if (exists(f))
|
|
157
|
+
a.push("--ro-bind", f, f);
|
|
158
|
+
a.push("--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp");
|
|
159
|
+
if (!["/usr", "/lib", "/bin"].some((d) => p.interpreterPrefix === d || p.interpreterPrefix.startsWith(`${d}/`)))
|
|
160
|
+
a.push("--ro-bind", p.interpreterPrefix, p.interpreterPrefix);
|
|
161
|
+
a.push("--ro-bind", p.runDir, p.runDir, "--bind", p.scratch, p.scratch);
|
|
162
|
+
for (const t of p.targets)
|
|
163
|
+
a.push("--ro-bind", t, t);
|
|
164
|
+
// Secrets inside a mounted target are masked; ones outside every mount are simply absent.
|
|
165
|
+
const mounted = (x) => p.targets.some((t) => x === t || x.startsWith(`${t}/`));
|
|
166
|
+
for (const s of p.secrets)
|
|
167
|
+
if (mounted(s) && exists(s))
|
|
168
|
+
a.push(...(isDir(s) ? ["--tmpfs", s] : ["--ro-bind", "/dev/null", s]));
|
|
169
|
+
for (const sh of SHELLS)
|
|
170
|
+
if (exists(sh))
|
|
171
|
+
a.push("--ro-bind", "/dev/null", sh);
|
|
172
|
+
a.push("--chdir", p.cwd ?? p.scratch);
|
|
173
|
+
return a;
|
|
174
|
+
}
|
|
175
|
+
// ---- the Python prelude -----------------------------------------------------------------------------------------
|
|
176
|
+
function pythonMain(programPath, cpuSeconds, fileBytes, memBytes) {
|
|
177
|
+
return `import sys, os, resource
|
|
178
|
+
SCRATCH = os.path.realpath(os.environ["CODEACT_SCRATCH"])
|
|
179
|
+
def _lim(r, v):
|
|
180
|
+
try: resource.setrlimit(r, (v, v))
|
|
181
|
+
except Exception: pass
|
|
182
|
+
_lim(resource.RLIMIT_CPU, ${Math.ceil(cpuSeconds)})
|
|
183
|
+
_lim(resource.RLIMIT_FSIZE, ${Math.ceil(fileBytes)})
|
|
184
|
+
_lim(resource.RLIMIT_CORE, 0)
|
|
185
|
+
if sys.platform.startswith("linux"): _lim(resource.RLIMIT_AS, ${Math.ceil(memBytes)})
|
|
186
|
+
_DENY = ("socket.", "subprocess.", "os.system", "os.exec", "os.posix_spawn", "os.spawn", "os.fork", "os.forkpty", "os.kill", "os.killpg", "pty.", "ctypes.", "os.startfile", "webbrowser.", "urllib.", "http.", "ftplib.", "smtplib.", "_winapi.")
|
|
187
|
+
_PATHS = {"os.remove": 1, "os.rmdir": 1, "os.mkdir": 1, "os.rename": 2, "os.symlink": 2, "os.link": 2, "os.truncate": 1, "os.chmod": 1, "os.chown": 1, "os.utime": 1, "shutil.rmtree": 1, "shutil.move": 2, "shutil.copyfile": 2}
|
|
188
|
+
def _inside(p):
|
|
189
|
+
if isinstance(p, int): return True
|
|
190
|
+
try: r = os.path.realpath(os.fsdecode(p))
|
|
191
|
+
except Exception: return False
|
|
192
|
+
return r == SCRATCH or r.startswith(SCRATCH + os.sep)
|
|
193
|
+
def _hook(ev, args):
|
|
194
|
+
if ev.startswith(_DENY):
|
|
195
|
+
raise PermissionError("codeact: " + ev + " is not allowed in the lane")
|
|
196
|
+
if ev == "open":
|
|
197
|
+
path, mode, flags = (tuple(args) + (None, None, None))[:3]
|
|
198
|
+
writing = (isinstance(mode, str) and any(c in mode for c in "wax+")) or (isinstance(flags, int) and flags & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND))
|
|
199
|
+
if writing and not _inside(path):
|
|
200
|
+
raise PermissionError("codeact: writes go to CODEACT_SCRATCH only")
|
|
201
|
+
elif ev in _PATHS:
|
|
202
|
+
for p in tuple(args)[:_PATHS[ev]]:
|
|
203
|
+
if p is not None and not _inside(p):
|
|
204
|
+
raise PermissionError("codeact: " + ev + " outside CODEACT_SCRATCH")
|
|
205
|
+
sys.addaudithook(_hook)
|
|
206
|
+
del _lim
|
|
207
|
+
_p = ${JSON.stringify(programPath)}
|
|
208
|
+
with open(_p, encoding="utf-8") as _f: _src = _f.read()
|
|
209
|
+
_code = compile(_src, "program.py", "exec")
|
|
210
|
+
del _f, _src
|
|
211
|
+
exec(_code, {"__name__": "__main__", "__file__": "program.py"})
|
|
212
|
+
`;
|
|
213
|
+
}
|
|
214
|
+
// ---- running ----------------------------------------------------------------------------------------------------
|
|
215
|
+
const clipLine = (s, n = 120) => {
|
|
216
|
+
const one = s.replace(/\s+/g, " ").trim();
|
|
217
|
+
return one.length > n ? `${one.slice(0, n - 1)}…` : one;
|
|
218
|
+
};
|
|
219
|
+
/** Resident memory (KB) of `root` and all its descendants, from one `ps` read. */
|
|
220
|
+
function treeRssKb(root) {
|
|
221
|
+
return new Promise((res) => execFile("/bin/ps", ["-A", "-o", "pid=,ppid=,rss="], { timeout: 2000 }, (e, out) => {
|
|
222
|
+
if (e)
|
|
223
|
+
return res(0);
|
|
224
|
+
const kids = new Map();
|
|
225
|
+
const rss = new Map();
|
|
226
|
+
for (const line of String(out).split("\n")) {
|
|
227
|
+
const [pid, ppid, kb] = line.trim().split(/\s+/).map(Number);
|
|
228
|
+
if (!pid)
|
|
229
|
+
continue;
|
|
230
|
+
rss.set(pid, kb || 0);
|
|
231
|
+
kids.set(ppid, [...(kids.get(ppid) ?? []), pid]);
|
|
232
|
+
}
|
|
233
|
+
let sum = 0;
|
|
234
|
+
const stack = [root];
|
|
235
|
+
const seen = new Set();
|
|
236
|
+
while (stack.length) {
|
|
237
|
+
const p = stack.pop();
|
|
238
|
+
if (seen.has(p))
|
|
239
|
+
continue;
|
|
240
|
+
seen.add(p);
|
|
241
|
+
sum += rss.get(p) ?? 0;
|
|
242
|
+
stack.push(...(kids.get(p) ?? []));
|
|
243
|
+
}
|
|
244
|
+
res(sum);
|
|
245
|
+
}));
|
|
246
|
+
}
|
|
247
|
+
async function pruneRuns(root, keep) {
|
|
248
|
+
try {
|
|
249
|
+
const names = (await readdir(root)).filter((n) => /^\d{8}T\d{6}Z-[0-9a-f]{8}$/.test(n)).sort();
|
|
250
|
+
for (const n of names.slice(0, Math.max(0, names.length - keep)))
|
|
251
|
+
await rm(join(root, n), { recursive: true, force: true });
|
|
252
|
+
}
|
|
253
|
+
catch { /* best effort */ }
|
|
254
|
+
}
|
|
255
|
+
/** Run one lane program. Never throws: every outcome is a CodeActResult, and every refusal means nothing ran. */
|
|
256
|
+
export async function runCodeAct(req, opts = {}) {
|
|
257
|
+
const cfg = codeActConfig(req.settings);
|
|
258
|
+
const language = req.language;
|
|
259
|
+
const text = String(req.program ?? "");
|
|
260
|
+
const t0 = Date.now();
|
|
261
|
+
const home = homedir();
|
|
262
|
+
const result = (status, summary, extra = {}) => ({
|
|
263
|
+
status,
|
|
264
|
+
ok: status === "ok",
|
|
265
|
+
summary: clipLine(redactSecrets(summary)),
|
|
266
|
+
program: { language, text, sha256: createHash("sha256").update(text).digest("hex"), bytes: Buffer.byteLength(text, "utf8") },
|
|
267
|
+
sandbox: { mechanism: "none", platform: process.platform, network: "denied", secrets: "masked", writes: "scratch-only" },
|
|
268
|
+
limits: { timeoutMs: cfg.timeoutMs, cpuSeconds: cfg.cpuSeconds, memoryMb: cfg.memoryMb, maxOutputBytes: cfg.maxOutputBytes, maxScratchFileMb: cfg.maxScratchFileMb },
|
|
269
|
+
stats: { wallMs: Date.now() - t0, exitCode: null, signal: null, stdoutBytes: 0, stderrTail: "" },
|
|
270
|
+
actions: 1,
|
|
271
|
+
...extra,
|
|
272
|
+
});
|
|
273
|
+
if (language !== "python" && language !== "node")
|
|
274
|
+
return result("refused", "unknown program language", { reason: `language must be python or node, got ${String(language)}` });
|
|
275
|
+
const screened = screenProgram(language, text, cfg.maxProgramBytes);
|
|
276
|
+
if (screened)
|
|
277
|
+
return result("refused", "program refused before it ran", { reason: screened });
|
|
278
|
+
const targets = [...new Set(req.targets)];
|
|
279
|
+
const missing = targets.filter((t) => !t.startsWith("/") || !existsSync(t));
|
|
280
|
+
if (!targets.length || missing.length)
|
|
281
|
+
return result("refused", "target paths missing", { reason: missing.length ? `not found: ${missing.join(", ")}` : "no targets" });
|
|
282
|
+
let realTargets;
|
|
283
|
+
try {
|
|
284
|
+
realTargets = targets.map((t) => realpathSync(t));
|
|
285
|
+
}
|
|
286
|
+
catch (e) {
|
|
287
|
+
return result("refused", "target paths unreadable", { reason: String(e) });
|
|
288
|
+
}
|
|
289
|
+
const avail = await (opts.availability ?? sandboxAvailability)();
|
|
290
|
+
if (!avail.ok)
|
|
291
|
+
return result("sandbox_unavailable", "no sandbox here, so nothing ran", { reason: avail.reason });
|
|
292
|
+
const mechanism = avail.mechanism;
|
|
293
|
+
const sandbox = { mechanism, platform: process.platform, network: "denied", secrets: "masked", writes: "scratch-only" };
|
|
294
|
+
const interp = language === "python" ? findPython(opts.python) : findNode(opts.node);
|
|
295
|
+
if (!interp)
|
|
296
|
+
return result("sandbox_unavailable", `no ${language} interpreter, so nothing ran`, { sandbox, reason: `${language} not found` });
|
|
297
|
+
const prefix = interpreterPrefix(interp);
|
|
298
|
+
const runsRoot = opts.runsRoot ?? operatorPath("codeact", "runs");
|
|
299
|
+
const id = `${new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${randomUUID().slice(0, 8)}`;
|
|
300
|
+
await mkdir(runsRoot, { recursive: true, mode: 0o700 });
|
|
301
|
+
const runDir = realpathSync(runsRoot) + `/${id}`;
|
|
302
|
+
const scratch = `${runDir}/scratch`;
|
|
303
|
+
await mkdir(join(scratch, "tmp"), { recursive: true, mode: 0o700 });
|
|
304
|
+
const programFile = join(runDir, language === "python" ? "program.py" : "program.mjs");
|
|
305
|
+
await writeFile(programFile, text, { mode: 0o600 });
|
|
306
|
+
const plan = {
|
|
307
|
+
interpreterPrefix: prefix, runDir, scratch, targets: realTargets, home: realpathSync(home),
|
|
308
|
+
secrets: [...new Set([...secretPaths(home, get_operator_home()), ...secretPaths(realpathSync(home), get_operator_home())])],
|
|
309
|
+
};
|
|
310
|
+
try {
|
|
311
|
+
if (statSync(realTargets[0]).isDirectory())
|
|
312
|
+
plan.cwd = realTargets[0];
|
|
313
|
+
}
|
|
314
|
+
catch { /* scratch */ }
|
|
315
|
+
const memBytes = cfg.memoryMb * 1024 * 1024;
|
|
316
|
+
let argv;
|
|
317
|
+
if (language === "python") {
|
|
318
|
+
const main = join(runDir, "main.py");
|
|
319
|
+
await writeFile(main, pythonMain(programFile, cfg.cpuSeconds, cfg.maxScratchFileMb * 1024 * 1024, memBytes), { mode: 0o600 });
|
|
320
|
+
argv = [interp, "-I", "-S", "-B", main, ...realTargets];
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
const perm = await nodePermissionFlag(interp);
|
|
324
|
+
const permArgs = perm ? [perm, `--allow-fs-read=${runDir}`, ...realTargets.map((t) => `--allow-fs-read=${t}`), `--allow-fs-write=${scratch}`] : [];
|
|
325
|
+
argv = [interp, ...permArgs, "--disallow-code-generation-from-strings", `--max-old-space-size=${Math.max(64, Math.floor(cfg.memoryMb * 0.75))}`, programFile, ...realTargets];
|
|
326
|
+
}
|
|
327
|
+
const [file, ...args] = mechanism === "seatbelt"
|
|
328
|
+
? ["/usr/bin/sandbox-exec", "-p", codeActSeatbeltProfile(plan), ...argv]
|
|
329
|
+
: [["/usr/bin/bwrap", "/bin/bwrap", "/usr/local/bin/bwrap"].find((p) => existsSync(p)), ...codeActBwrapArgs(plan), "--", ...argv];
|
|
330
|
+
const env = {
|
|
331
|
+
PATH: "/usr/bin:/bin", HOME: scratch, TMPDIR: `${scratch}/tmp`, LANG: "C.UTF-8", LC_ALL: "C.UTF-8",
|
|
332
|
+
CODEACT_SCRATCH: scratch, CODEACT_TARGETS: JSON.stringify(realTargets), PYTHONDONTWRITEBYTECODE: "1", PYTHONIOENCODING: "utf-8",
|
|
333
|
+
};
|
|
334
|
+
const cwd = plan.cwd ?? scratch; // bwrap also sets it inside (--chdir)
|
|
335
|
+
let stdout = "";
|
|
336
|
+
let stdoutBytes = 0;
|
|
337
|
+
let stderr = "";
|
|
338
|
+
let stopped;
|
|
339
|
+
let peakKb = 0;
|
|
340
|
+
const child = spawn(file, args, { cwd, env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
341
|
+
ownChild(child, "codeact program", { group: true }); // a program still running at /exit is killed with the session
|
|
342
|
+
const kill = (status, why) => {
|
|
343
|
+
if (stopped)
|
|
344
|
+
return;
|
|
345
|
+
stopped = { status, why };
|
|
346
|
+
try {
|
|
347
|
+
process.kill(-child.pid, "SIGKILL");
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
try {
|
|
351
|
+
child.kill("SIGKILL");
|
|
352
|
+
}
|
|
353
|
+
catch { /* gone */ }
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
child.stdout.on("data", (b) => {
|
|
357
|
+
stdoutBytes += b.length;
|
|
358
|
+
if (stdoutBytes > cfg.maxOutputBytes)
|
|
359
|
+
return kill("output_limit", `stdout passed ${cfg.maxOutputBytes} bytes`);
|
|
360
|
+
stdout += b.toString("utf8");
|
|
361
|
+
});
|
|
362
|
+
child.stderr.on("data", (b) => { stderr = (stderr + b.toString("utf8")).slice(-8192); });
|
|
363
|
+
const timer = setTimeout(() => kill("timeout", `ran past ${cfg.timeoutMs} ms`), cfg.timeoutMs);
|
|
364
|
+
let polling = false;
|
|
365
|
+
const poll = setInterval(async () => {
|
|
366
|
+
if (polling || !child.pid)
|
|
367
|
+
return;
|
|
368
|
+
polling = true;
|
|
369
|
+
const kb = await treeRssKb(child.pid);
|
|
370
|
+
polling = false;
|
|
371
|
+
peakKb = Math.max(peakKb, kb);
|
|
372
|
+
if (kb > cfg.memoryMb * 1024)
|
|
373
|
+
kill("memory_limit", `resident memory passed ${cfg.memoryMb} MB`);
|
|
374
|
+
}, 200);
|
|
375
|
+
const { code, signal } = await new Promise((res) => {
|
|
376
|
+
child.on("error", () => res({ code: null, signal: null }));
|
|
377
|
+
child.on("close", (c, s) => res({ code: c, signal: s }));
|
|
378
|
+
});
|
|
379
|
+
clearTimeout(timer);
|
|
380
|
+
clearInterval(poll);
|
|
381
|
+
const stderrTail = clipLine(redactSecrets(stderr.split("\n").filter((l) => l.trim()).slice(-6).join(" | ")), 600);
|
|
382
|
+
const stats = { wallMs: Date.now() - t0, exitCode: code, signal: signal ?? null, stdoutBytes, stderrTail, peakRssMb: Math.round(peakKb / 1024) };
|
|
383
|
+
const base = { sandbox, stats, runDir };
|
|
384
|
+
let out;
|
|
385
|
+
if (stopped)
|
|
386
|
+
out = result(stopped.status, `stopped: ${stopped.why}`, { ...base, reason: stopped.why });
|
|
387
|
+
else if (code !== 0)
|
|
388
|
+
out = result("error", `the program failed (exit ${code ?? signal})`, { ...base, reason: stderrTail || `exit ${code ?? signal}` });
|
|
389
|
+
else {
|
|
390
|
+
const last = stdout.split("\n").map((l) => l.trim()).filter(Boolean).pop() ?? "";
|
|
391
|
+
let parsed;
|
|
392
|
+
try {
|
|
393
|
+
parsed = JSON.parse(last);
|
|
394
|
+
}
|
|
395
|
+
catch {
|
|
396
|
+
parsed = undefined;
|
|
397
|
+
}
|
|
398
|
+
const obj = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
|
|
399
|
+
if (!obj || typeof obj.summary !== "string" || !("data" in obj)) {
|
|
400
|
+
out = result("bad_output", "the program's last line was not {\"summary\", \"data\"}", { ...base, reason: clipLine(last || "(no output)", 200) });
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
out = result("ok", obj.summary, { ...base, data: obj.data });
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
await writeFile(join(runDir, "result.json"), JSON.stringify({ ...out, program: { ...out.program, text: undefined } }, null, 1), { mode: 0o600 }).catch(() => { });
|
|
407
|
+
await pruneRuns(runsRoot, opts.keepRuns ?? 100);
|
|
408
|
+
return out;
|
|
409
|
+
}
|