@0perator/operator 0.1.360-next.2 → 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 +5 -4
- 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 +159 -0
- package/dist/autonomy/delegate.js +42 -15
- package/dist/autonomy/headless.js +7 -4
- package/dist/autonomy/index.js +2 -4
- package/dist/autonomy/session-factory.js +13 -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 +336 -45
- 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/resume.js +125 -0
- package/dist/background/synthesis.js +25 -0
- package/dist/browser/engine.js +163 -0
- package/dist/browser/session.js +130 -140
- package/dist/bus/inbox.js +150 -6
- package/dist/cli.js +343 -86
- package/dist/config/features.js +3 -3
- package/dist/config/persona.js +29 -3
- package/dist/config/settings.js +262 -21
- package/dist/config/staff-prompt.js +12 -0
- package/dist/engine/agent.js +52 -41
- package/dist/engine/aurora.js +40 -8
- package/dist/engine/batch-scheduler.js +4 -13
- package/dist/engine/compaction.js +2 -2
- 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 +18 -2
- package/dist/engine/native-vision-node.js +72 -0
- package/dist/engine/native-vision.js +103 -0
- package/dist/engine/selfheal.js +1 -1
- package/dist/engine/toolcalls.js +6 -6
- package/dist/engine/verify-gate.js +37 -7
- package/dist/gateway-cli.js +14 -3
- package/dist/index.js +3 -0
- package/dist/mcp/phone-server.js +30 -0
- 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/index.js +33 -17
- package/dist/permissions/signature.js +5 -0
- package/dist/permissions/tier.js +4 -2
- package/dist/phone-cli.js +65 -0
- package/dist/products/craft.js +2 -2
- package/dist/remote/grants.js +119 -0
- package/dist/remote/host.js +63 -6
- package/dist/router/models.js +29 -29
- package/dist/selfimprove/index.js +9 -7
- package/dist/services/preflight.js +35 -91
- package/dist/session.js +173 -46
- 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/deferred.js +1 -0
- package/dist/tools/device/android.js +227 -0
- package/dist/tools/device/classify.js +127 -0
- package/dist/tools/device/deps.js +69 -0
- package/dist/tools/device/desktop.js +82 -0
- package/dist/tools/device/harness.js +262 -0
- package/dist/tools/device/iphone.js +206 -0
- package/dist/tools/device/mirroring-jxa.js +146 -0
- package/dist/tools/device/setup.js +90 -0
- package/dist/tools/device/tools.js +70 -0
- package/dist/tools/device/types.js +19 -0
- package/dist/tools/executor.js +25 -15
- package/dist/tools/generation-gateway.js +94 -0
- package/dist/tools/registry.js +95 -155
- package/dist/ui/App.js +18 -6
- package/dist/ui/ApprovalPrompt.js +10 -4
- package/dist/ui/BgPanel.js +17 -12
- 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/UpdatePrompt.js +40 -0
- 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/modelPicker.js +1 -1
- package/dist/ui/opsMode.js +20 -0
- package/dist/ui/slashCommands.js +1 -0
- package/dist/ui/types.js +0 -2
- package/dist/update-check.js +145 -0
- package/dist/update.js +59 -15
- package/dist/util/slash.js +2 -2
- package/package.json +4 -2
- package/src/tools/device/NOTICE +37 -0
- package/dist/browser/cdp.js +0 -271
- package/dist/tools/mutating.js +0 -15
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// The MoA CodeAct lane (2026-11-27, James): for a step that is bulk, read-only and deterministic, the executor writes ONE
|
|
2
|
+
// short program that does the whole step inside a sandbox (moa/codeact-sandbox.ts) instead of N tool-call round trips.
|
|
3
|
+
// This module is the pure half: settings, the eligibility check the planner's step goes through, and the result shape
|
|
4
|
+
// that goes back to the planner and into the trace. Whether a step may take the lane is decided here, in code, never by
|
|
5
|
+
// the prompt. Anything that changes the world (an edit, a commit, a push, the network, a message) stays a normal gated
|
|
6
|
+
// tool call. Why: _ai-docs/decisions/2026-11-27-moa-codeact-lane.md (repo root).
|
|
7
|
+
export const CODEACT_DEFAULTS = {
|
|
8
|
+
enabled: true,
|
|
9
|
+
minItems: 20,
|
|
10
|
+
minRoundTrips: 6,
|
|
11
|
+
deniedAuthors: ["scout", "ghost-4b"],
|
|
12
|
+
language: "auto",
|
|
13
|
+
timeoutMs: 60_000,
|
|
14
|
+
cpuSeconds: 60,
|
|
15
|
+
memoryMb: 1024,
|
|
16
|
+
maxOutputBytes: 256 * 1024,
|
|
17
|
+
maxScratchFileMb: 64,
|
|
18
|
+
maxProgramBytes: 32 * 1024,
|
|
19
|
+
};
|
|
20
|
+
/** The one switch: unset means on, a boolean is taken as given, anything else is off. */
|
|
21
|
+
export function codeActEnabled(s) {
|
|
22
|
+
if (s?.enabled === undefined)
|
|
23
|
+
return CODEACT_DEFAULTS.enabled;
|
|
24
|
+
return s.enabled === true;
|
|
25
|
+
}
|
|
26
|
+
/** Settings over the defaults. Bad numbers fall back to the default instead of loosening a limit. */
|
|
27
|
+
export function codeActConfig(s) {
|
|
28
|
+
const d = CODEACT_DEFAULTS;
|
|
29
|
+
const pos = (v, dv) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : dv);
|
|
30
|
+
const lang = s?.language;
|
|
31
|
+
return {
|
|
32
|
+
enabled: codeActEnabled(s),
|
|
33
|
+
minItems: pos(s?.minItems, d.minItems),
|
|
34
|
+
minRoundTrips: pos(s?.minRoundTrips, d.minRoundTrips),
|
|
35
|
+
deniedAuthors: Array.isArray(s?.deniedAuthors) ? s.deniedAuthors.filter((x) => typeof x === "string") : d.deniedAuthors,
|
|
36
|
+
language: lang === "python" || lang === "node" || lang === "auto" ? lang : d.language,
|
|
37
|
+
timeoutMs: pos(s?.timeoutMs, d.timeoutMs),
|
|
38
|
+
cpuSeconds: pos(s?.cpuSeconds, d.cpuSeconds),
|
|
39
|
+
memoryMb: pos(s?.memoryMb, d.memoryMb),
|
|
40
|
+
maxOutputBytes: pos(s?.maxOutputBytes, d.maxOutputBytes),
|
|
41
|
+
maxScratchFileMb: pos(s?.maxScratchFileMb, d.maxScratchFileMb),
|
|
42
|
+
maxProgramBytes: pos(s?.maxProgramBytes, d.maxProgramBytes),
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function resolvePath(p, cwd) {
|
|
46
|
+
const abs = p.startsWith("/") ? p : `${cwd.replace(/\/+$/, "")}/${p}`;
|
|
47
|
+
const out = [];
|
|
48
|
+
for (const seg of abs.split("/")) {
|
|
49
|
+
if (seg === "" || seg === ".")
|
|
50
|
+
continue;
|
|
51
|
+
if (seg === "..")
|
|
52
|
+
out.pop();
|
|
53
|
+
else
|
|
54
|
+
out.push(seg);
|
|
55
|
+
}
|
|
56
|
+
return `/${out.join("/")}`;
|
|
57
|
+
}
|
|
58
|
+
const under = (p, root) => p === root || p.startsWith(root.endsWith("/") ? root : `${root}/`);
|
|
59
|
+
/** Paths a program may never read, relative to the home directory. Masked by the sandbox too (codeact-sandbox.ts). */
|
|
60
|
+
export const SECRET_HOME_PATHS = [
|
|
61
|
+
".ssh", ".aws", ".gnupg", ".config/gcloud", ".axe/secrets", ".kube", ".docker", ".config/switchboard",
|
|
62
|
+
"Library/Keychains", ".netrc", ".git-credentials", ".npmrc", ".pypirc", ".cloudflared",
|
|
63
|
+
];
|
|
64
|
+
/** The secret paths for this home and Operator home, absolute. */
|
|
65
|
+
export function secretPaths(home, operatorHome) {
|
|
66
|
+
const h = home.replace(/\/+$/, "");
|
|
67
|
+
const op = operatorHome?.replace(/\/+$/, "");
|
|
68
|
+
return [
|
|
69
|
+
...SECRET_HOME_PATHS.map((p) => `${h}/${p}`),
|
|
70
|
+
"/Library/Keychains",
|
|
71
|
+
...(op ? [`${op}/credentials.json`, `${op}/byo.json`, `${op}/vault`, `${op}/identity.json`] : []),
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
const REASON_TEXT = {
|
|
75
|
+
disabled: "the lane is off (moa.codeact.enabled)",
|
|
76
|
+
not_read_only: "the step changes something",
|
|
77
|
+
not_deterministic: "the step is not deterministic",
|
|
78
|
+
needs_network: "the step needs the network",
|
|
79
|
+
needs_secrets: "the step needs secrets",
|
|
80
|
+
not_bulk: "the step is small",
|
|
81
|
+
author_not_eligible: "the author model may not write programs",
|
|
82
|
+
no_targets: "the step names no paths to read",
|
|
83
|
+
target_secret: "a target is a secret path",
|
|
84
|
+
target_too_broad: "a target is the home folder, the root or above them",
|
|
85
|
+
};
|
|
86
|
+
/** The deterministic check: a step takes the lane only when the lane is on, the step is read-only, deterministic, needs
|
|
87
|
+
* neither network nor secrets, is bulk (≥ minItems items or ≥ minRoundTrips round trips), its author is allowed, and
|
|
88
|
+
* every target is a readable, bounded path. Otherwise the step runs on structured tools. */
|
|
89
|
+
export function codeActEligibility(step, settings, env) {
|
|
90
|
+
const cfg = codeActConfig(settings);
|
|
91
|
+
const reasons = [];
|
|
92
|
+
const home = resolvePath(env.home, "/");
|
|
93
|
+
const targets = (Array.isArray(step.targets) ? step.targets : []).filter((t) => typeof t === "string" && t.trim()).map((t) => resolvePath(t.trim().replace(/^~(?=\/|$)/, home), env.cwd));
|
|
94
|
+
if (!cfg.enabled)
|
|
95
|
+
reasons.push("disabled");
|
|
96
|
+
if (step.readOnly !== true)
|
|
97
|
+
reasons.push("not_read_only");
|
|
98
|
+
if (step.deterministic !== true)
|
|
99
|
+
reasons.push("not_deterministic");
|
|
100
|
+
if (step.needsNetwork === true)
|
|
101
|
+
reasons.push("needs_network");
|
|
102
|
+
if (step.needsSecrets === true)
|
|
103
|
+
reasons.push("needs_secrets");
|
|
104
|
+
const items = typeof step.items === "number" && Number.isFinite(step.items) ? step.items : 0;
|
|
105
|
+
const trips = typeof step.estRoundTrips === "number" && Number.isFinite(step.estRoundTrips) ? step.estRoundTrips : 0;
|
|
106
|
+
if (items < cfg.minItems && trips < cfg.minRoundTrips)
|
|
107
|
+
reasons.push("not_bulk");
|
|
108
|
+
const author = String(step.author ?? "").trim().toLowerCase();
|
|
109
|
+
if (!author || cfg.deniedAuthors.some((a) => a.trim().toLowerCase() === author))
|
|
110
|
+
reasons.push("author_not_eligible");
|
|
111
|
+
if (!targets.length)
|
|
112
|
+
reasons.push("no_targets");
|
|
113
|
+
const secrets = secretPaths(home, env.operatorHome && resolvePath(env.operatorHome, "/"));
|
|
114
|
+
if (targets.some((t) => secrets.some((s) => under(t, s))))
|
|
115
|
+
reasons.push("target_secret");
|
|
116
|
+
if (targets.some((t) => t === "/" || under(home, t)))
|
|
117
|
+
reasons.push("target_too_broad");
|
|
118
|
+
const eligible = reasons.length === 0;
|
|
119
|
+
const detail = eligible
|
|
120
|
+
? `codeact lane: eligible (${items ? `${items} items` : `~${trips} round trips`}, read-only, ${targets.length} target${targets.length === 1 ? "" : "s"})`
|
|
121
|
+
: `structured tools: ${reasons.map((r) => REASON_TEXT[r]).join("; ")}`;
|
|
122
|
+
return { eligible, reasons, detail, targets };
|
|
123
|
+
}
|
|
124
|
+
/** "auto" language: node for a JS/TS project without a Python project file, else python. `exists` is injected so this
|
|
125
|
+
* stays free of node:fs. */
|
|
126
|
+
export function pickLanguage(pref, targets, exists) {
|
|
127
|
+
if (pref === "python" || pref === "node")
|
|
128
|
+
return pref;
|
|
129
|
+
const has = (f) => targets.some((t) => exists(`${t}/${f}`));
|
|
130
|
+
const py = has("pyproject.toml") || has("setup.py") || has("requirements.txt");
|
|
131
|
+
return has("package.json") && !py ? "node" : "python";
|
|
132
|
+
}
|
|
133
|
+
/** The planner-facing text of a result: the summary line, then the data as JSON, capped. */
|
|
134
|
+
export function codeActReport(r, maxChars = 12_000) {
|
|
135
|
+
const head = `[codeact ${r.status}] ${r.summary}`;
|
|
136
|
+
if (!r.ok)
|
|
137
|
+
return `${head}${r.reason ? `\nreason: ${r.reason}` : ""}${r.stats.stderrTail ? `\nstderr: ${r.stats.stderrTail}` : ""}\nThe step was not done; do it with structured tools.`;
|
|
138
|
+
const body = JSON.stringify(r.data, null, 1) ?? "null";
|
|
139
|
+
return `${head}\n${body.length > maxChars ? `${body.slice(0, maxChars)}\n… (${body.length - maxChars} more chars in ${r.runDir ?? "the run dir"}/result.json)` : body}`;
|
|
140
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** The visibility to send, or an error to return to the model. `onCreate` fills the seat's default; an update
|
|
2
|
+
* with no visibility leaves the artifact's own unchanged. */
|
|
3
|
+
export function artifactVisibility(tier, requested, onCreate) {
|
|
4
|
+
const v = typeof requested === "string" && /^(private|link|public)$/.test(requested) ? requested : undefined;
|
|
5
|
+
if (tier !== "enterprise")
|
|
6
|
+
return { visibility: v ?? (onCreate ? "link" : undefined) };
|
|
7
|
+
if (v === "public")
|
|
8
|
+
return { error: "public artifacts are off for enterprise seats: use link (anyone with the link) or private" };
|
|
9
|
+
return { visibility: v ?? (onCreate ? "private" : undefined) };
|
|
10
|
+
}
|
|
@@ -4,6 +4,8 @@ import { centralRecording } from "../telemetry/ingest.js";
|
|
|
4
4
|
import { runBatch, defaultClassify, defaultKeys, cancelledResult } from "../engine/batch-scheduler.js";
|
|
5
5
|
import { registrySafeTools } from "./tier.js";
|
|
6
6
|
import { heldForPlanReview } from "./plan-review.js";
|
|
7
|
+
import { isPhoneLine } from "./signature.js";
|
|
8
|
+
import { grantPhone, phonePreview } from "../tools/device/classify.js";
|
|
7
9
|
export { PermissionPolicy } from "./policy.js";
|
|
8
10
|
const NO_RETRY = "Do not retry this call or an equivalent; choose another approach or ask the user.";
|
|
9
11
|
const DENIED = (name, why) => `Permission denied: "${name}" was denied ` +
|
|
@@ -62,27 +64,41 @@ export function withPermissions(inner, policy, opts = {}) {
|
|
|
62
64
|
// A human-signature line (money/prod/destructive) surfaces as its own control event so a dashboard/
|
|
63
65
|
// mobile flags WHY a human was pulled in — and a background sub-agent (no approver) is denied below.
|
|
64
66
|
const line = policy.signatureLineFor(name, args);
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
//
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
return heldForPlanReview(name, line, policy.approvedPlanClasses());
|
|
72
|
-
}
|
|
73
|
-
if (plan === "run") {
|
|
74
|
-
approved = true; // the owner approved this class with the plan
|
|
75
|
-
// still a signature-line call: the dashboard's critical feed shows it ran, and on whose say-so
|
|
76
|
-
sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (run under approved plan)` } });
|
|
77
|
-
}
|
|
78
|
-
else {
|
|
79
|
-
if (line)
|
|
80
|
-
sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
|
|
81
|
-
approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
|
|
67
|
+
if (isPhoneLine(line)) {
|
|
68
|
+
// A phone line: the owner, every time, in every mode — no plan answers it — shown the screen it will act on. The
|
|
69
|
+
// approval becomes a one-shot grant the tool itself checks (tools/device/classify.ts).
|
|
70
|
+
sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
|
|
71
|
+
const pv = opts.approve ? await phonePreview(name, args) : {};
|
|
72
|
+
approved = opts.approve ? await opts.approve(name, args, { line, once: true, ...(pv.screenshot ? { preview: pv.screenshot } : {}), ...(pv.target ? { target: pv.target } : {}) }) : false;
|
|
82
73
|
if (!approved) {
|
|
83
74
|
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
|
|
84
75
|
return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
|
|
85
76
|
}
|
|
77
|
+
grantPhone(name, args);
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
const plan = line ? policy.planAnswer(line) : null;
|
|
81
|
+
if (line && plan === "hold") {
|
|
82
|
+
// Autonomous: the plan the owner approved does not list this class. Held, never prompted, and not remembered as
|
|
83
|
+
// a denial — the same call runs once a plan that lists it is approved.
|
|
84
|
+
sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (held for plan review)` } });
|
|
85
|
+
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
|
|
86
|
+
return heldForPlanReview(name, line, policy.approvedPlanClasses());
|
|
87
|
+
}
|
|
88
|
+
if (plan === "run") {
|
|
89
|
+
approved = true; // the owner approved this class with the plan
|
|
90
|
+
// still a signature-line call: the dashboard's critical feed shows it ran, and on whose say-so
|
|
91
|
+
sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name} (run under approved plan)` } });
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
if (line)
|
|
95
|
+
sinkNow()?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
|
|
96
|
+
approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
|
|
97
|
+
if (!approved) {
|
|
98
|
+
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch }, argHash);
|
|
99
|
+
return refuse(DENIED(name, opts.approve ? "user" : "no-approver"));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
86
102
|
}
|
|
87
103
|
}
|
|
88
104
|
// An esc during the (human) approval wait: the approval may land AFTER the interrupt, and an approved edit
|
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
// Precedence: a signature line beats a per-tool "allow" rule and the mode — it can only ever be relaxed by
|
|
9
9
|
// the policy being fully inert (the local owner in bypass+admin+no-rules, where the wrapper is skipped
|
|
10
10
|
// entirely). The moment any enforcement is on (a tier, audit/gated mode, or a rule), the lines are live.
|
|
11
|
+
import { phoneLine, PHONE_LINES } from "../tools/device/classify.js";
|
|
12
|
+
export const isPhoneLine = (l) => !!l && PHONE_LINES.includes(l);
|
|
11
13
|
// Tool-NAME patterns: money-moving integrations (mostly MCP tools) — pay/charge/refund/payout/transfer/
|
|
12
14
|
// wire/invoice/billing/subscription changes. Conservative: a false positive just adds one approval.
|
|
13
15
|
const MONEY_NAME = /(pay(ment|out|ee)?|charge|refund|transfer|wire|invoice|billing|subscription|checkout|stripe|disburse)/i;
|
|
@@ -61,6 +63,9 @@ function blob(name, args) {
|
|
|
61
63
|
/** Which signature line a call crosses, or null. Checked on every gated call: null lets the normal
|
|
62
64
|
* policy decide; a non-null value forces approval (and, absent an approver, a deny). */
|
|
63
65
|
export function signatureLine(name, args) {
|
|
66
|
+
const phone = phoneLine(name, args);
|
|
67
|
+
if (phone)
|
|
68
|
+
return phone;
|
|
64
69
|
if (MONEY_NAME.test(name))
|
|
65
70
|
return "money";
|
|
66
71
|
const b = blob(name, args);
|