@omacode/micromanager 0.1.1 → 1.0.0
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 +7 -4
- package/THIRD_PARTY.md +100 -0
- package/decider/.python-version +1 -0
- package/decider/README.md +35 -0
- package/decider/decider/__init__.py +1 -0
- package/decider/decider/server.py +327 -0
- package/decider/pyproject.toml +34 -0
- package/decider/uv.lock +1255 -0
- package/dist/agenda.js +51 -0
- package/dist/agents.js +58 -0
- package/dist/artifact/handoff.js +281 -0
- package/dist/ask.js +200 -0
- package/dist/backends.js +219 -0
- package/dist/backlog.js +414 -0
- package/dist/bench.js +427 -0
- package/dist/board.js +1 -0
- package/dist/brief.js +202 -0
- package/dist/browser.js +679 -0
- package/dist/budget.js +61 -0
- package/dist/catalog.js +187 -0
- package/dist/checkchange.js +145 -0
- package/dist/checkpoint.js +94 -0
- package/dist/cli.js +764 -0
- package/dist/comfy-gate.js +258 -0
- package/dist/compact.js +142 -0
- package/dist/config.js +344 -0
- package/dist/context/capture.js +1 -0
- package/dist/context/digest.js +1 -0
- package/dist/context/embed.js +1 -0
- package/dist/context/index.js +2 -0
- package/dist/context/ledger.js +1 -0
- package/dist/context/manager.js +1 -0
- package/dist/context/memory.js +1 -0
- package/dist/context/policy.js +1 -0
- package/dist/context/prices.js +1 -0
- package/dist/context/recall.js +1 -0
- package/dist/context/rules.js +1 -0
- package/dist/context/search.js +1 -0
- package/dist/context/status.js +1 -0
- package/dist/context/store.js +1 -0
- package/dist/context/summary.js +1 -0
- package/dist/context/tokens.js +1 -0
- package/dist/context/tools.js +1 -0
- package/dist/continuation.js +184 -0
- package/dist/contract.js +294 -0
- package/dist/contractround.js +178 -0
- package/dist/control.js +1 -0
- package/dist/creative-tools.js +237 -0
- package/dist/dataset.js +175 -0
- package/dist/decide.js +676 -0
- package/dist/decider.js +171 -0
- package/dist/design-shell.js +448 -0
- package/dist/design.js +1410 -0
- package/dist/desktop.js +44 -0
- package/dist/egress.js +156 -0
- package/dist/eval.js +60 -0
- package/dist/evolver.js +302 -0
- package/dist/features.js +193 -0
- package/dist/followups.js +32 -0
- package/dist/forms.js +195 -0
- package/dist/gate.js +108 -0
- package/dist/gatebox.js +46 -0
- package/dist/grants.js +189 -0
- package/dist/graph.js +65 -0
- package/dist/guard/index.js +1 -0
- package/dist/guard/wire.js +1 -0
- package/dist/helpers.js +85 -0
- package/dist/hooks.js +158 -0
- package/dist/image-models.js +117 -0
- package/{src/integration.ts → dist/integration.js} +1 -2
- package/dist/journal.js +1 -0
- package/dist/look.js +363 -0
- package/dist/memory.js +1 -0
- package/dist/mode.js +97 -0
- package/dist/native.js +3348 -0
- package/dist/nogit.js +259 -0
- package/dist/outcomes.js +148 -0
- package/dist/permission.js +35 -0
- package/dist/pick.js +89 -0
- package/dist/pipelines.js +262 -0
- package/dist/plan.js +641 -0
- package/dist/plandoc.js +211 -0
- package/dist/plugin.js +4736 -0
- package/dist/policy.js +58 -0
- package/dist/pools.js +1 -0
- package/dist/preview.js +274 -0
- package/dist/profile.js +165 -0
- package/dist/progress.js +1 -0
- package/dist/promote.js +313 -0
- package/dist/redact.js +1 -0
- package/dist/registry.js +179 -0
- package/dist/riskscore.js +126 -0
- package/dist/roles.js +1 -0
- package/dist/routing.js +1 -0
- package/dist/runner.js +1892 -0
- package/{src/sandbox.ts → dist/sandbox.js} +1 -2
- package/dist/sandboxgate.js +90 -0
- package/dist/scheduler.js +170 -0
- package/dist/services-main.js +131 -0
- package/dist/services.js +265 -0
- package/dist/session.js +241 -0
- package/dist/setup.js +423 -0
- package/dist/shell/decide.js +1 -0
- package/dist/shell/index.js +2 -0
- package/dist/shell/sandbox.js +1 -0
- package/dist/shell/wire.js +1 -0
- package/dist/skills.js +103 -0
- package/dist/state.js +1 -0
- package/dist/store.js +1 -0
- package/dist/switcher.js +1 -0
- package/dist/synth.js +418 -0
- package/dist/tools.js +477 -0
- package/dist/trials.js +223 -0
- package/dist/usage.js +1 -0
- package/dist/wait.js +167 -0
- package/dist/watchdog.js +476 -0
- package/dist/web-guidance.js +43 -0
- package/dist/which.js +20 -0
- package/dist/worktree/git.js +545 -0
- package/dist/writeguard.js +311 -0
- package/package.json +36 -17
- package/skills/deck/SKILL.md +98 -0
- package/skills/design/SKILL.md +150 -0
- package/skills/image/SKILL.md +66 -0
- package/skills/orchestrator/SKILL.md +107 -0
- package/skills/video/SKILL.md +97 -0
- package/skills/web/SKILL.md +60 -0
- package/src/agenda.ts +0 -56
- package/src/agents.ts +0 -74
- package/src/ask.ts +0 -243
- package/src/backends.ts +0 -144
- package/src/backlog.ts +0 -436
- package/src/bench.ts +0 -163
- package/src/board.ts +0 -1
- package/src/brief.ts +0 -151
- package/src/browser.ts +0 -624
- package/src/budget.ts +0 -73
- package/src/catalog.ts +0 -214
- package/src/checkchange.ts +0 -180
- package/src/checkpoint.ts +0 -99
- package/src/cli.ts +0 -117
- package/src/compact.ts +0 -162
- package/src/config.ts +0 -340
- package/src/context/capture.ts +0 -1
- package/src/context/digest.ts +0 -1
- package/src/context/embed.ts +0 -1
- package/src/context/index.ts +0 -2
- package/src/context/ledger.ts +0 -1
- package/src/context/manager.ts +0 -1
- package/src/context/memory.ts +0 -1
- package/src/context/policy.ts +0 -1
- package/src/context/prices.ts +0 -1
- package/src/context/recall.ts +0 -1
- package/src/context/rules.ts +0 -1
- package/src/context/search.ts +0 -1
- package/src/context/status.ts +0 -1
- package/src/context/store.ts +0 -1
- package/src/context/summary.ts +0 -1
- package/src/context/tokens.ts +0 -1
- package/src/context/tools.ts +0 -1
- package/src/continuation.ts +0 -122
- package/src/contract.ts +0 -342
- package/src/contractround.ts +0 -225
- package/src/control.ts +0 -1
- package/src/dataset.ts +0 -133
- package/src/decide.ts +0 -690
- package/src/eval.ts +0 -66
- package/src/evolver.ts +0 -369
- package/src/followups.ts +0 -50
- package/src/forms.ts +0 -191
- package/src/gate.ts +0 -90
- package/src/grants.ts +0 -239
- package/src/graph.ts +0 -74
- package/src/guard/index.ts +0 -1
- package/src/guard/wire.ts +0 -1
- package/src/helpers.ts +0 -105
- package/src/hooks.ts +0 -199
- package/src/jev.ts +0 -141
- package/src/journal.ts +0 -1
- package/src/look.ts +0 -390
- package/src/memory.ts +0 -1
- package/src/native.ts +0 -2455
- package/src/nogit.ts +0 -112
- package/src/outcomes.ts +0 -210
- package/src/pick.ts +0 -112
- package/src/pipelines.ts +0 -252
- package/src/plan.ts +0 -449
- package/src/plugin.ts +0 -3187
- package/src/policy.ts +0 -84
- package/src/pools.ts +0 -1
- package/src/profile.ts +0 -186
- package/src/progress.ts +0 -1
- package/src/redact.ts +0 -1
- package/src/registry.ts +0 -207
- package/src/roles.ts +0 -1
- package/src/routing.ts +0 -1
- package/src/runner.ts +0 -1506
- package/src/scheduler.ts +0 -200
- package/src/session.ts +0 -269
- package/src/shell/decide.ts +0 -1
- package/src/shell/index.ts +0 -2
- package/src/shell/sandbox.ts +0 -1
- package/src/shell/wire.ts +0 -1
- package/src/skills.ts +0 -111
- package/src/state.ts +0 -1
- package/src/store.ts +0 -1
- package/src/switcher.ts +0 -1
- package/src/tools.ts +0 -480
- package/src/trials.ts +0 -247
- package/src/usage.ts +0 -1
- package/src/wait.ts +0 -180
- package/src/watchdog.ts +0 -498
- package/src/worktree/git.ts +0 -378
package/dist/decide.js
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
// Every permission request goes to the decider first. It answers itself when it is sure enough for the request's
|
|
2
|
+
// risk and nothing says the user must decide; everything else goes to the user unchanged.
|
|
3
|
+
//
|
|
4
|
+
// Order: hard rules (never automatic) -> the job's own area -> the decider -> floors per risk class. Without the
|
|
5
|
+
// decider (no client, an error) the request goes to the user: nothing is decided on a guess.
|
|
6
|
+
//
|
|
7
|
+
// A shell request that only reads inside the job's own worktree skips the decider entirely (readsOnlyInside): a
|
|
8
|
+
// worker cannot change anything with it, and its own confidence on `git status --porcelain` (0.75) sits below the read
|
|
9
|
+
// floor (0.80), so asking only turned inspection into denials. A writer's command that stays in its own task worktree
|
|
10
|
+
// skips the decider too (staysInWorktree), and a reader's command that does not only read is refused without asking.
|
|
11
|
+
//
|
|
12
|
+
// external_directory is layered, not a blanket "never":
|
|
13
|
+
// 1. a hard rule no layer can pass: the user's keys and credential stores, their home itself, the system
|
|
14
|
+
// directories, the secret files inside ~/.config, another job's branch in the repository's own git data. The
|
|
15
|
+
// user's `allowOutside` setting is the one thing that lifts it, and only for the paths it names (below);
|
|
16
|
+
// 2. the job's own area: any worktree under <project>/<state dir>/worktrees/, this job's integration
|
|
17
|
+
// worktree included. Path-based, never a substring: `worktrees-old` is not `worktrees`;
|
|
18
|
+
// 3. task-vouched: a path the task text names with its full path, for a read only (a named path is a vouch for
|
|
19
|
+
// reading it, not for changing it);
|
|
20
|
+
// 4. everything else is the user, as it always was.
|
|
21
|
+
import { execFileSync } from "node:child_process";
|
|
22
|
+
import { existsSync } from "node:fs";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { basename, dirname, isAbsolute, join, normalize } from "node:path";
|
|
25
|
+
import { DeciderError } from "./decider.js";
|
|
26
|
+
import { WRITERS } from "./profile.js";
|
|
27
|
+
import { MICROMANAGER, roleByAgent } from "./roles.js";
|
|
28
|
+
import { STATE_DIRS } from "./store.js";
|
|
29
|
+
// The node a permission case is journalled under. It is not a configured backend of its own: the mode decides, and the
|
|
30
|
+
// permission path uses the cloud client only (src/backends.ts cloudAnswers). A2b supplies its training export and the
|
|
31
|
+
// per-node gate that has to pass before a measured floor — or the local model itself — may answer these cases.
|
|
32
|
+
export const PERMISSION_NODE = "N13";
|
|
33
|
+
// write 0.85: live a test sub-agent's pytest runs scored 0.82, so 0.92 sent every test run to the user; the
|
|
34
|
+
// destructive cases are caught before (hard rules) and beside it (needs_user, risk).
|
|
35
|
+
export const DEFAULT_FLOORS = { read: 0.8, write: 0.85, needsUser: 0.5, risk: 1.5 };
|
|
36
|
+
const READ_ACTIONS = new Set(["read", "glob", "grep", "list", "webfetch", "websearch", "lsp", "skill", "question"]);
|
|
37
|
+
// Never decided by the decider, whatever it says. The user's allowOutside is passed to every test, so a path the user named
|
|
38
|
+
// falls through to the layers below instead of stopping here.
|
|
39
|
+
const ALWAYS_USER = [
|
|
40
|
+
{
|
|
41
|
+
test: (r, allowed) => r.action === "external_directory" && r.resources.some((p) => forbiddenOutside(p, allowed)),
|
|
42
|
+
why: "a path no layer may allow",
|
|
43
|
+
},
|
|
44
|
+
{ test: (r) => r.action === "read" && r.resources.some((p) => /(^|\/)\.env(\.|$)/.test(p) && !p.endsWith(".example")), why: "a .env file" },
|
|
45
|
+
{
|
|
46
|
+
test: (r) => r.action === "shell" &&
|
|
47
|
+
r.resources.some((c) => /\bgit\s+(push|reset\s+--hard|clean\s+-[a-z]*f)|\bsudo\b|\bmkfs|\bdd\s+if=|\bchmod\s+-R|\bcurl\b[^|]*\|\s*(ba|z)?sh|\bwget\b[^|]*\|\s*(ba|z)?sh/.test(c) ||
|
|
48
|
+
removesOutside(c)),
|
|
49
|
+
why: "a destructive or irreversible command",
|
|
50
|
+
},
|
|
51
|
+
{ test: (r) => r.action === "shell" && r.resources.some(installsIntoSystem), why: "installs software into the system" },
|
|
52
|
+
];
|
|
53
|
+
// Package installs outside the project's own environment (a venv, node_modules) change the machine.
|
|
54
|
+
export function installsIntoSystem(command) {
|
|
55
|
+
if (/\b(pacman|yay|paru|apt(-get)?|dnf|brew|snap|flatpak)\s+(-S\b|install\b)/.test(command))
|
|
56
|
+
return true;
|
|
57
|
+
if (/\bnpm\s+(i|install)\s+(-g|--global)\b/.test(command) || /\b(cargo|go)\s+install\b/.test(command))
|
|
58
|
+
return true;
|
|
59
|
+
for (const match of command.matchAll(/(\S*?)\b(pip3?|python3?\s+-m\s+pip)\s+install\b/g)) {
|
|
60
|
+
const prefix = match[1] ?? "";
|
|
61
|
+
if (!/venv|\.venv|\/env\//.test(prefix) && !/\buv\s+pip\b/.test(command))
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
// `rm -r`/`rm -f` on an absolute path, the home directory, a parent directory or a bare wildcard; a relative
|
|
67
|
+
// path inside the project (a cache, a build directory) is left to the decider.
|
|
68
|
+
// The targets of each `rm -r`/`rm -f` in a command line (an empty list: an `rm` without a target).
|
|
69
|
+
export function rmTargets(command) {
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const match of command.matchAll(/\brm\s+((?:-[a-zA-Z]+(?:\s+|$))+)([^;&|]*)/g)) {
|
|
72
|
+
if (!/[rRf]/.test(match[1] ?? ""))
|
|
73
|
+
continue;
|
|
74
|
+
out.push((match[2] ?? "").trim().split(/\s+/).filter(Boolean));
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
const OUTSIDE = (t) => /^(\/|~|\$HOME|\.\.|\*$|\.$|\.\/?\*?$)/.test(t) || t.includes("/../");
|
|
79
|
+
export function removesOutside(command) {
|
|
80
|
+
return rmTargets(command).some((targets) => targets.length === 0 || targets.some(OUTSIDE));
|
|
81
|
+
}
|
|
82
|
+
export const inspectPaths = (directory, paths) => {
|
|
83
|
+
const git = (args) => {
|
|
84
|
+
try {
|
|
85
|
+
return { ok: true, out: execFileSync("git", ["-C", directory, ...args], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }) };
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return { ok: false, out: "" };
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const repo = git(["rev-parse", "--is-inside-work-tree"]).out.trim() === "true";
|
|
92
|
+
return paths.map((path) => ({
|
|
93
|
+
path,
|
|
94
|
+
exists: existsSync(isAbsolute(path) ? path : join(directory, path)),
|
|
95
|
+
tracked: repo ? git(["ls-files", "--", path]).out.trim() !== "" : undefined,
|
|
96
|
+
ignored: repo ? git(["check-ignore", "-q", "--", path]).ok : undefined,
|
|
97
|
+
}));
|
|
98
|
+
};
|
|
99
|
+
function relevanceFacts(facts) {
|
|
100
|
+
const say = (f) => `- ${f.path}: ${f.exists ? "exists" : "does not exist"}, ${f.tracked ? "under version control" : "not under version control"}, ${f.ignored ? "ignored by git (.gitignore)" : "not ignored by git"}`;
|
|
101
|
+
return `Paths the command deletes:\n${facts.map(say).join("\n")}`;
|
|
102
|
+
}
|
|
103
|
+
const HOME = homedir();
|
|
104
|
+
// Directories outside the project that no layer may allow, each named with what it holds. These are refused whole
|
|
105
|
+
// because nearly everything inside them is a secret, so a per-file rule would be theatre: .ssh, .aws and .gnupg are
|
|
106
|
+
// private keys, .netrc and the keyring are logins, .password-store is a password database.
|
|
107
|
+
//
|
|
108
|
+
// ~/.config is deliberately NOT on this list. It holds application configuration as much as tokens — 61 application
|
|
109
|
+
// directories on the user's own machine and not one file matching the names the old whole-directory ban claimed to
|
|
110
|
+
// protect — and refusing it whole made a real task impossible (2026-10-07: a worker could not read
|
|
111
|
+
// ~/.config/omarchy/shell.json for the plugin id that decides whether a system service restarts in a loop). What is
|
|
112
|
+
// refused there is the secret files themselves, below, at the granularity that actually protects them.
|
|
113
|
+
const FORBIDDEN_OUTSIDE = [
|
|
114
|
+
{ dir: join(HOME, ".ssh"), what: "the user's keys in ~/.ssh" },
|
|
115
|
+
{ dir: join(HOME, ".aws"), what: "the user's AWS credentials in ~/.aws" },
|
|
116
|
+
{ dir: join(HOME, ".gnupg"), what: "the user's GPG keys in ~/.gnupg" },
|
|
117
|
+
{ dir: join(HOME, ".password-store"), what: "the user's password store in ~/.password-store" },
|
|
118
|
+
{ dir: join(HOME, ".local", "share", "keyrings"), what: "the user's keyring in ~/.local/share/keyrings" },
|
|
119
|
+
{ dir: join(HOME, ".netrc"), what: "the user's login credentials in ~/.netrc" },
|
|
120
|
+
// The system itself. /var and /sys stay whole on purpose: they are read-mostly, so refusing them costs a worker
|
|
121
|
+
// little (nothing a task needs lives only there, and a reading tool asks about a file it names), while narrowing
|
|
122
|
+
// them to a file list would mean guessing at every package's and the kernel's own state files.
|
|
123
|
+
{ dir: "/etc", what: "the system directory /etc" },
|
|
124
|
+
{ dir: "/usr", what: "the system directory /usr" },
|
|
125
|
+
{ dir: "/boot", what: "the system directory /boot" },
|
|
126
|
+
{ dir: "/var", what: "the system directory /var" },
|
|
127
|
+
{ dir: "/proc", what: "the system directory /proc" },
|
|
128
|
+
{ dir: "/sys", what: "the system directory /sys" },
|
|
129
|
+
];
|
|
130
|
+
// The secret files inside ~/.config, matched case-insensitively against the LAST path segment only. The segment is the
|
|
131
|
+
// point: `*token*` is a rule about a file's own name (huggingface_token, .netrc_token, a service-token.json), not about
|
|
132
|
+
// a directory that happens to contain the word somewhere in its parents — a directory called token-store is a config
|
|
133
|
+
// directory, and refusing it would reproduce the bug this list replaces.
|
|
134
|
+
const SECRET_IN_CONFIG = [
|
|
135
|
+
/^auth\.json$/, // opencode's own stored credentials
|
|
136
|
+
/^credentials(\..*)?$/, // ~/.aws/credentials' shape, and the git-credential-store default
|
|
137
|
+
/^\.credentials$/, // python keyring's file of the same name
|
|
138
|
+
/^hosts\.yml$/, // the GitHub CLI's token store
|
|
139
|
+
/^logins\.json$/, // a Firefox profile's saved logins
|
|
140
|
+
/^key[34]\.db$/, // Firefox's own key databases
|
|
141
|
+
/\.kdbx$/, // keepass databases
|
|
142
|
+
/token/, // huggingface_token, *-token.json, .token
|
|
143
|
+
/_token$/, // the explicit spelling of the same, kept so the rule reads as one rule per convention
|
|
144
|
+
/\.secret$/, // *.secret, and npm's own .npmrc-adjacent secrets
|
|
145
|
+
/^secrets\./, // secrets.json, secrets.yaml, secrets.toml
|
|
146
|
+
];
|
|
147
|
+
// Another job's worktree metadata and branches live under .git/; a worker never reaches them, whatever its task says.
|
|
148
|
+
const GIT_DATA = /(^|\/)\.git\/(worktrees|refs)\//;
|
|
149
|
+
// What the journal and the refusal messages call the user's own setting, so every layer words it the same way.
|
|
150
|
+
export const ALLOW_OUTSIDE_REASON = "the user's allowOutside setting";
|
|
151
|
+
// What the journal says when the user opened one refused path for one job, and when they turned it down. Both name the
|
|
152
|
+
// user on purpose: a record that only said "allowed" or "denied" would read as though nothing had ever been wrong,
|
|
153
|
+
// and an operator reading the journal after the fact could not tell a rule from an exception to it.
|
|
154
|
+
export const GRANT_OUTSIDE_REASON = "the user opened this path for this job";
|
|
155
|
+
export const REFUSED_OUTSIDE_REASON = "the user refused this path for this job";
|
|
156
|
+
// The user's own `allowOutside` setting: absolute paths or path prefixes the user has decided a worker may reach, even
|
|
157
|
+
// where the rules above refuse. Matching is on whole segments like every other path rule here, so an entry never opens
|
|
158
|
+
// a sibling that merely shares its name (/home/u/.config-x is not /home/u/.config), and the entries are compared
|
|
159
|
+
// through the same normalisation, so `~`, a trailing slash and `..` cannot smuggle a path past a rule.
|
|
160
|
+
export function allowedOutside(resource, allowed = []) {
|
|
161
|
+
const path = normalizeOutside(resource);
|
|
162
|
+
if (path.length === 0 || path === ".")
|
|
163
|
+
return false;
|
|
164
|
+
return allowed.some((entry) => {
|
|
165
|
+
const base = normalizeOutside(entry);
|
|
166
|
+
return base.length > 0 && under(path, base);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
// `~` expanded, a trailing `/*` or `/` dropped, `..` resolved lexically. No filesystem access: a path that does not
|
|
170
|
+
// exist yet has to be classified the same way as one that does.
|
|
171
|
+
//
|
|
172
|
+
// Exported because a grant the user gave is remembered as a path, and the only thing that may decide whether a later
|
|
173
|
+
// request is "the same path" is the same normalisation the rules use. A second copy here would drift from it.
|
|
174
|
+
export function normalizeOutside(path) {
|
|
175
|
+
const trimmed = path.trim();
|
|
176
|
+
const bare = trimmed.replace(/\/+$/, "").replace(/(?<=[^/])\/\*+$/, "");
|
|
177
|
+
const expanded = bare === "~" ? HOME : bare.startsWith("~/") ? join(HOME, bare.slice(2)) : bare;
|
|
178
|
+
return expanded.length === 0 ? trimmed : normalize(expanded);
|
|
179
|
+
}
|
|
180
|
+
function under(path, base) {
|
|
181
|
+
if (base === "/")
|
|
182
|
+
return path.startsWith("/");
|
|
183
|
+
return path === base || path.startsWith(`${base}/`);
|
|
184
|
+
}
|
|
185
|
+
// The user's own `allowOutside`, checked first: it is the one thing that lifts the rules below, and it is only ever the
|
|
186
|
+
// user's own list, never a task's or a vouch's. A refusal that survives it survives everything.
|
|
187
|
+
export function forbiddenOutside(resource, allowed = []) {
|
|
188
|
+
if (allowedOutside(resource, allowed))
|
|
189
|
+
return false;
|
|
190
|
+
const path = normalizeOutside(resource);
|
|
191
|
+
if (path === "/")
|
|
192
|
+
return true; // the whole file system
|
|
193
|
+
if (path.length === 0 || path === ".")
|
|
194
|
+
return false;
|
|
195
|
+
// The home directory itself stays refused whatever the per-path rules above say: a request for `~` is a request to
|
|
196
|
+
// sweep everything in it at once, and the rules for its subdirectories are no answer to that. Naming `~` in
|
|
197
|
+
// allowOutside is the one way past it, and only because the user wrote it down.
|
|
198
|
+
if (path === HOME)
|
|
199
|
+
return true;
|
|
200
|
+
if (FORBIDDEN_OUTSIDE.some((f) => under(path, f.dir)))
|
|
201
|
+
return true;
|
|
202
|
+
// ~/.config is not refused whole; its secret files are, by name, last segment only.
|
|
203
|
+
if (under(path, join(HOME, ".config")) && SECRET_IN_CONFIG.some((pattern) => pattern.test(basename(path).toLowerCase())))
|
|
204
|
+
return true;
|
|
205
|
+
return GIT_DATA.test(path);
|
|
206
|
+
}
|
|
207
|
+
// Why a refusal is written down with, or undefined when nothing refuses the path: what the rule protects, and for a
|
|
208
|
+
// secret file the file's own name, so a worker is told which file was the problem rather than being told about a whole
|
|
209
|
+
// directory. undefined rather than a wrong sentence, so a caller cannot put a reason on a path no rule refused.
|
|
210
|
+
export function forbiddenOutsideWhat(resource) {
|
|
211
|
+
const path = normalizeOutside(resource);
|
|
212
|
+
if (path === "/")
|
|
213
|
+
return "the whole file system";
|
|
214
|
+
if (path === HOME)
|
|
215
|
+
return "the home directory itself";
|
|
216
|
+
const dir = FORBIDDEN_OUTSIDE.find((f) => under(path, f.dir));
|
|
217
|
+
if (dir)
|
|
218
|
+
return dir.what;
|
|
219
|
+
const config = join(HOME, ".config");
|
|
220
|
+
if (under(path, config)) {
|
|
221
|
+
const name = basename(path).toLowerCase();
|
|
222
|
+
if (SECRET_IN_CONFIG.some((pattern) => pattern.test(name)))
|
|
223
|
+
return `${name}, a credential file in ~/.config`;
|
|
224
|
+
}
|
|
225
|
+
if (GIT_DATA.test(path))
|
|
226
|
+
return "another job's branches and worktree metadata in the repository's own git data";
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
export function hardRule(request, allowed = []) {
|
|
230
|
+
return ALWAYS_USER.find((rule) => rule.test(request, allowed))?.why;
|
|
231
|
+
}
|
|
232
|
+
const READ_PROGRAMS = new Set([
|
|
233
|
+
"ls", "cat", "head", "tail", "wc", "sort", "uniq", "grep", "rg", "which", "command", "type", "echo", "printf", "pwd", "file",
|
|
234
|
+
"stat", "du", "df", "tree", "diff", "cut", "tr", "basename", "dirname", "realpath", "env", "date", "true", "test", "[",
|
|
235
|
+
// Reading programs a worker reaches for constantly (a live run denied 67 read-only commands without these).
|
|
236
|
+
"sed", "awk", "jq", "md5sum", "sha256sum", "xxd", "od", "column", "comm", "nl", "fold", "tac", "expr", "seq",
|
|
237
|
+
]);
|
|
238
|
+
// A reading program with a writing form: `sed -i` rewrites the file, `awk -i inplace` (gawk) does the same,
|
|
239
|
+
// `find -delete`/`-exec` change or run things, and `sort -o` writes its output to a file. The flag decides, not the
|
|
240
|
+
// program.
|
|
241
|
+
const MUTATING = [
|
|
242
|
+
["sed", /(^|\s)-{1,2}(i\b|i\.\w|in-place\b)/],
|
|
243
|
+
["awk", /(^|\s)-{1,2}(i\b|in-place\b)/],
|
|
244
|
+
["find", /(^|\s)-(delete|exec|execdir|ok|fprint)\w*/],
|
|
245
|
+
["sort", /(^|\s)-{1,2}(o\S*|output)/],
|
|
246
|
+
];
|
|
247
|
+
// git's read subcommands. Everything else (add, commit, checkout, reset, stash, push, fetch, …) writes, so an
|
|
248
|
+
// unknown subcommand is a write: the list is a whitelist, not a blacklist.
|
|
249
|
+
const GIT_READS = new Set([
|
|
250
|
+
"status", "diff", "log", "show", "branch", "ls-files", "rev-parse", "blame", "ls-tree", "cat-file", "merge-base",
|
|
251
|
+
"describe", "for-each-ref", "shortlog", "rev-list", "diff-tree", "whatchanged", "name-rev", "var", "count-objects",
|
|
252
|
+
"show-ref", "check-ignore", "check-attr", "grep",
|
|
253
|
+
]);
|
|
254
|
+
// Global git flags that carry a value: the subcommand only starts after them.
|
|
255
|
+
const GIT_VALUE_FLAGS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env"]);
|
|
256
|
+
const VERSION = /^\S+\s+(--version|-V|version)\b/;
|
|
257
|
+
const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
258
|
+
const REDIRECT = /(^|\s)(\d?>>?|&>)\s*(\/dev\/null|&\d|\d)/;
|
|
259
|
+
// A redirect to a real path writes it, so it belongs to a write even when the program only reads.
|
|
260
|
+
const WRITING_REDIRECT = /(^|\s)(\d?>>?|&>)\s*(?!\/dev\/null\b|&\d\b|\d\b)\S/;
|
|
261
|
+
// Wrappers that only run the command behind them. Their own arguments are dropped so the wrapped command decides:
|
|
262
|
+
// `timeout 120 pytest` is a write (pytest reads nothing), `timeout 120 git status` a read. `env` is in the list
|
|
263
|
+
// because `env rm -rf …` runs rm; a bare `env` prints the environment and stays a read.
|
|
264
|
+
const TIMEOUT_VALUE_FLAGS = new Set(["-k", "--kill-after", "-s", "--signal"]);
|
|
265
|
+
const WRAPPERS = {
|
|
266
|
+
timeout: (args) => {
|
|
267
|
+
let i = 1;
|
|
268
|
+
while (i < args.length && (args[i] ?? "").startsWith("-"))
|
|
269
|
+
i += TIMEOUT_VALUE_FLAGS.has(args[i]) ? 2 : 1;
|
|
270
|
+
return i + 1; // the duration, then the command
|
|
271
|
+
},
|
|
272
|
+
nohup: (args) => (args[1]?.startsWith("--") ? 2 : 1),
|
|
273
|
+
nice: (args) => (args[1] === "-n" ? 3 : args[1]?.startsWith("-") ? 2 : 1),
|
|
274
|
+
stdbuf: (args) => (args[1] && /^-[ioe]$/.test(args[1]) ? 3 : args[1]?.startsWith("-") ? 2 : 1),
|
|
275
|
+
env: (args) => {
|
|
276
|
+
let i = 1;
|
|
277
|
+
while (i < args.length && (ENV_ASSIGNMENT.test(args[i] ?? "") || (args[i] ?? "").startsWith("-")))
|
|
278
|
+
i++;
|
|
279
|
+
return i;
|
|
280
|
+
},
|
|
281
|
+
};
|
|
282
|
+
// The command that actually runs, behind any wrapper and any leading VAR=value assignments.
|
|
283
|
+
function unwrap(tokens) {
|
|
284
|
+
let rest = tokens;
|
|
285
|
+
for (;;) {
|
|
286
|
+
while (rest.length > 0 && ENV_ASSIGNMENT.test(rest[0] ?? ""))
|
|
287
|
+
rest = rest.slice(1);
|
|
288
|
+
const program = (rest[0] ?? "").replace(/^.*\//, "");
|
|
289
|
+
const consumed = WRAPPERS[program]?.(rest) ?? 0;
|
|
290
|
+
if (consumed <= 0 || consumed >= rest.length)
|
|
291
|
+
return rest;
|
|
292
|
+
rest = rest.slice(consumed);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
// Where git's subcommand starts, behind the global flags: `git -C /repo status`, `git --no-pager diff`,
|
|
296
|
+
// `git -c user.name=x commit`.
|
|
297
|
+
function gitSubcommand(tokens) {
|
|
298
|
+
let i = 1; // tokens[0] is git
|
|
299
|
+
while (i < tokens.length && (tokens[i] ?? "").startsWith("-")) {
|
|
300
|
+
i += GIT_VALUE_FLAGS.has(tokens[i]) && !(tokens[i] ?? "").includes("=") ? 2 : 1;
|
|
301
|
+
}
|
|
302
|
+
return i;
|
|
303
|
+
}
|
|
304
|
+
// git reads when its subcommand only reads. `remote` and `branch` read while they only look: `git branch new`
|
|
305
|
+
// creates one and `git remote add` writes, so a bare word behind them is a write.
|
|
306
|
+
function gitReads(tokens, at) {
|
|
307
|
+
const sub = tokens[at] ?? "";
|
|
308
|
+
const rest = tokens.slice(at + 1);
|
|
309
|
+
if (sub === "remote" || sub === "branch")
|
|
310
|
+
return rest.every((token) => token.startsWith("-"));
|
|
311
|
+
if (sub === "worktree")
|
|
312
|
+
return rest[0] === "list";
|
|
313
|
+
if (sub === "reflog")
|
|
314
|
+
return rest.length === 0 || rest[0] === "show" || rest[0].startsWith("-");
|
|
315
|
+
return GIT_READS.has(sub);
|
|
316
|
+
}
|
|
317
|
+
// One `&&`, `||`, `;` or `|` step of a command line: every step has to read for the line to read. Splitting after the
|
|
318
|
+
// redirects are stripped, so `2>&1` is not an `&&`.
|
|
319
|
+
export function segments(command) {
|
|
320
|
+
return command
|
|
321
|
+
.trim()
|
|
322
|
+
.split(/(?:&&|\|\||;|\|)/)
|
|
323
|
+
.map((part) => part.trim())
|
|
324
|
+
.filter(Boolean);
|
|
325
|
+
}
|
|
326
|
+
function readsSegment(segment) {
|
|
327
|
+
// A command substitution can hide anything, so a line that carries one is not classified as a read.
|
|
328
|
+
if (/\$\(|`/.test(segment))
|
|
329
|
+
return false;
|
|
330
|
+
if (WRITING_REDIRECT.test(segment))
|
|
331
|
+
return false;
|
|
332
|
+
const command = segment.replace(REDIRECT, "$1$2$3");
|
|
333
|
+
const tokens = unwrap(command.split(/\s+/).filter(Boolean));
|
|
334
|
+
const program = (tokens[0] ?? "").replace(/^.*\//, "");
|
|
335
|
+
if (program === "git") {
|
|
336
|
+
const at = gitSubcommand(tokens);
|
|
337
|
+
return at < tokens.length && gitReads(tokens, at);
|
|
338
|
+
}
|
|
339
|
+
const mutating = MUTATING.find(([name]) => name === program);
|
|
340
|
+
if (mutating)
|
|
341
|
+
return !mutating[1].test(command);
|
|
342
|
+
return READ_PROGRAMS.has(program) || VERSION.test(command);
|
|
343
|
+
}
|
|
344
|
+
// A shell request that only reads: every resource, and every step inside each resource, is a known reading program
|
|
345
|
+
// (OpenCode passes a pipe or a chain as several resources, one segment each).
|
|
346
|
+
export function readsOnly(commands) {
|
|
347
|
+
return commands.length > 0 && commands.every((raw) => {
|
|
348
|
+
const parts = segments(raw);
|
|
349
|
+
return parts.length > 0 && parts.every(readsSegment);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
// Every absolute path the command mentions, after the same lexical normalisation readsOnly uses.
|
|
353
|
+
export function absolutePaths(command) {
|
|
354
|
+
return command
|
|
355
|
+
.split(/\s+/)
|
|
356
|
+
.map((token) => normalizeOutside(token.replace(/^--?[\w-]+=/, "")))
|
|
357
|
+
.filter((token) => isAbsolute(token));
|
|
358
|
+
}
|
|
359
|
+
// A read that stays inside the job's own area: nothing can change, and the paths it names cannot leave the
|
|
360
|
+
// worktree, so it needs no decider and no user. Relative paths are the worker's own directory by definition.
|
|
361
|
+
export function readsOnlyInside(request, root) {
|
|
362
|
+
if (request.action !== "shell")
|
|
363
|
+
return false;
|
|
364
|
+
const area = normalizeOutside(root);
|
|
365
|
+
if (area.length === 0)
|
|
366
|
+
return false;
|
|
367
|
+
return (readsOnly(request.resources) &&
|
|
368
|
+
request.resources.every((command) => absolutePaths(command).every((path) => under(path, area))));
|
|
369
|
+
}
|
|
370
|
+
// The task worktree a directory lies in, or undefined. Two layouts, both under the project's state directory (under
|
|
371
|
+
// any of its names, core/paths.ts STATE_DIRS): a build task's
|
|
372
|
+
// <project>/<stateDir>/worktrees/<job>--T<id>, and a plan's own <project>/<stateDir>/plan/<job>/worktrees/<task>.
|
|
373
|
+
// Only a task's own worktree, never the job's integration worktree: that one is the merge train's target and the
|
|
374
|
+
// readers' tree, so nothing may change it outside a merge. A project inside a larger repository works in
|
|
375
|
+
// <worktree>/<rel>; the area is the whole worktree either way.
|
|
376
|
+
const STATE_NAMES = STATE_DIRS.map((dir) => dir.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|");
|
|
377
|
+
const TASK_WORKTREE = new RegExp(`^(.*/(?:${STATE_NAMES})/(?:worktrees/[^/]+--T[\\w.]+|plan/[^/]+/worktrees/[\\w.-]+))(?:/|$)`);
|
|
378
|
+
export function taskWorktree(directory) {
|
|
379
|
+
return directory ? normalizeOutside(directory).match(TASK_WORKTREE)?.[1] : undefined;
|
|
380
|
+
}
|
|
381
|
+
// Programs whose effect reaches past the worktree whatever their arguments say: other processes, services, the
|
|
382
|
+
// network, the desktop, the user's accounts.
|
|
383
|
+
const BEYOND_WORKTREE = new Set([
|
|
384
|
+
"kill", "pkill", "killall", "systemctl", "journalctl", "loginctl", "crontab", "at", "docker", "podman", "ssh", "scp",
|
|
385
|
+
"sftp", "rsync", "curl", "wget", "nc", "ncat", "socat", "shutdown", "reboot", "poweroff", "mount", "umount", "chown",
|
|
386
|
+
"su", "doas", "xdg-open", "open", "notify-send", "hyprctl", "gh", "flatpak", "snap",
|
|
387
|
+
]);
|
|
388
|
+
// git inside a worktree: reading, and changing the working tree and the index. The refs, the stash and the config are
|
|
389
|
+
// shared with the user's checkout and every other worktree, so commit, checkout, branch, reset, stash, fetch, … stay the decider's.
|
|
390
|
+
// `branch` and `remote` are left to gitReads, which tells `git branch` from `git branch -D x` by the arguments.
|
|
391
|
+
const GIT_IN_WORKTREE = new Set([...[...GIT_READS].filter((sub) => sub !== "branch" && sub !== "remote"), "add", "restore", "rm", "mv", "apply", "grep", "check-ignore", "ls-tree", "cat-file"]);
|
|
392
|
+
const PUBLISH = /\b(npm|pnpm|yarn|cargo|twine|gem|poetry|uv)\s+(publish|upload|login|adduser)\b/;
|
|
393
|
+
// Paths outside the worktree that a command may still name: scratch space and the standard streams.
|
|
394
|
+
const SCRATCH = ["/tmp", "/dev/null", "/dev/stdout", "/dev/stderr"];
|
|
395
|
+
// A command a writer runs in its own task worktree that stays there: every path it names is inside the worktree or
|
|
396
|
+
// scratch space, it names no home directory, and no step is a program that acts beyond the tree (processes, services,
|
|
397
|
+
// network, publishing) or a git command that moves shared refs. What it does is the worker's business: the worktree is a
|
|
398
|
+
// throwaway checkout, and only the task's checks and the merge train bring its content anywhere. This judges the command
|
|
399
|
+
// line, not what a program does once it runs, exactly as the test-runner allow rules do: running the project's own code
|
|
400
|
+
// is what a writer is for.
|
|
401
|
+
//
|
|
402
|
+
// cwd is the directory the worker runs in, which for a project below the repository root is <worktree>/<rel>: a `..`
|
|
403
|
+
// there can stay in the worktree (`../.venv/bin/python`), so a relative path is resolved against it. A `cd` anywhere in
|
|
404
|
+
// the request makes that guess unsafe, and then any `..` leaves the fast path.
|
|
405
|
+
export function staysInWorktree(request, worktree, cwd = worktree) {
|
|
406
|
+
if (request.action !== "shell" || request.resources.length === 0)
|
|
407
|
+
return false;
|
|
408
|
+
const area = normalizeOutside(worktree);
|
|
409
|
+
if (area.length === 0)
|
|
410
|
+
return false;
|
|
411
|
+
const allowed = (path) => under(path, area) || SCRATCH.some((dir) => path === dir || under(path, dir));
|
|
412
|
+
const moves = request.resources.some((command) => segments(command).some((segment) => /^cd(\s|$)/.test(segment)));
|
|
413
|
+
// One argument as a path, or undefined when it is none. A lone "/" or "//" is a division or a comment in inline code
|
|
414
|
+
// (`node -e '… r) / f'`, live run 2026-10-13) or a pattern (`grep -E "^ /"`), never a path a command works in.
|
|
415
|
+
const pathOf = (token) => {
|
|
416
|
+
const value = token.startsWith("-") && token.includes("=") ? token.slice(token.indexOf("=") + 1) : token;
|
|
417
|
+
const bare = value.replace(/^['"(]+|['",;)]+$/g, "");
|
|
418
|
+
if (/^\/+$/.test(bare))
|
|
419
|
+
return undefined;
|
|
420
|
+
if (isAbsolute(bare))
|
|
421
|
+
return normalizeOutside(bare);
|
|
422
|
+
if (/(^|\/)\.\.(\/|$)/.test(bare))
|
|
423
|
+
return moves ? "/" : normalize(join(cwd, bare));
|
|
424
|
+
return undefined;
|
|
425
|
+
};
|
|
426
|
+
return request.resources.every((command) => {
|
|
427
|
+
if (PUBLISH.test(command))
|
|
428
|
+
return false;
|
|
429
|
+
if (/(^|[\s"'=:])(~|\$\{?HOME\b)/.test(command))
|
|
430
|
+
return false;
|
|
431
|
+
return segments(command).every((segment) => {
|
|
432
|
+
const tokens = unwrap(segment.split(/\s+/).filter(Boolean));
|
|
433
|
+
const program = (tokens[0] ?? "").replace(/^.*\//, "");
|
|
434
|
+
if (BEYOND_WORKTREE.has(program) || program.startsWith("omarchy"))
|
|
435
|
+
return false;
|
|
436
|
+
if (program === "git") {
|
|
437
|
+
const at = gitSubcommand(tokens);
|
|
438
|
+
if (!GIT_IN_WORKTREE.has(tokens[at] ?? "") && !gitReads(tokens, at))
|
|
439
|
+
return false;
|
|
440
|
+
}
|
|
441
|
+
// The program itself may live anywhere (/usr/bin/python3); its arguments may not.
|
|
442
|
+
return tokens.slice(1).every((token) => {
|
|
443
|
+
const path = pathOf(token);
|
|
444
|
+
return path === undefined || allowed(path);
|
|
445
|
+
});
|
|
446
|
+
});
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
export function riskClass(request) {
|
|
450
|
+
if (READ_ACTIONS.has(request.action))
|
|
451
|
+
return "read";
|
|
452
|
+
return request.action === "shell" && readsOnly(request.resources) ? "read" : "write";
|
|
453
|
+
}
|
|
454
|
+
// The job's own area: any worktree under <directory>/<state dir>/worktrees/, this job's integration worktree included,
|
|
455
|
+
// and the plan's own drafts under <directory>/<state dir>/plan/: a plan worktree is the job's own area too. Under any
|
|
456
|
+
// name the state directory has had (STATE_DIRS): all of them are the plugin's, and a job of a project not yet migrated
|
|
457
|
+
// keeps its worktrees under the old one. Compared segment by segment, so a sibling that merely starts with the same
|
|
458
|
+
// name is outside.
|
|
459
|
+
export function inJobArea(directory, path) {
|
|
460
|
+
if (!directory)
|
|
461
|
+
return false;
|
|
462
|
+
const want = normalizeOutside(path);
|
|
463
|
+
return STATE_DIRS.some((dir) => {
|
|
464
|
+
const state = normalizeOutside(join(directory, dir));
|
|
465
|
+
return [join(state, "worktrees"), join(state, "plan")].some((area) => under(want, area));
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
// The absolute paths a task text names, `~` expanded. A named file vouches for its directory too, as the plugin's own
|
|
469
|
+
// reader rule does (src/plugin.ts namedInTask): a task that says "…/src/main.py" is about that directory.
|
|
470
|
+
const TASK_PATH = /(?:^|[\s"'`(<[])((?:~|\/)[\w.@+~-]*(?:\/[\w.@+-]+)*)/g;
|
|
471
|
+
const NAMED_FILE = /\.[a-z0-9]{1,5}$/i;
|
|
472
|
+
export function taskNamesPath(task, path) {
|
|
473
|
+
if (!task)
|
|
474
|
+
return false;
|
|
475
|
+
const want = normalizeOutside(path);
|
|
476
|
+
if (want.length === 0)
|
|
477
|
+
return false;
|
|
478
|
+
return [...task.matchAll(TASK_PATH)]
|
|
479
|
+
.map((match) => normalizeOutside(match[1] ?? ""))
|
|
480
|
+
.flatMap((named) => (NAMED_FILE.test(named) ? [named, dirname(named)] : [named]))
|
|
481
|
+
.some((named) => want === named || under(want, named));
|
|
482
|
+
}
|
|
483
|
+
// OpenCode asks for external_directory the same way whether a path is read or written, and riskClass() calls the
|
|
484
|
+
// action a write because it is not one of the reading tools. So what decides is the asking agent's role: the roles
|
|
485
|
+
// that change files are not reading, every other one is (the same split the plugin makes at its own layer).
|
|
486
|
+
function readsOutside(request) {
|
|
487
|
+
if (riskClass(request) === "read")
|
|
488
|
+
return true;
|
|
489
|
+
return !WRITERS.has(roleByAgent(request.agent)?.id ?? "code");
|
|
490
|
+
}
|
|
491
|
+
// Layer 2 and 3 of the external_directory policy: the job's own area is mechanical, the user's own allowOutside is
|
|
492
|
+
// their standing decision, everything else is the user unless the task names the path and nothing is written to it.
|
|
493
|
+
// Vouching for a path is not vouching for a write.
|
|
494
|
+
//
|
|
495
|
+
// The allowOutside reason names the setting on purpose. A record that said only "allowed" would leave an operator
|
|
496
|
+
// asking whether anything was wrong with the request; this one says the user's own policy opened it.
|
|
497
|
+
export function externalVerdict(request, allowed = []) {
|
|
498
|
+
if (request.action !== "external_directory" || request.resources.length === 0)
|
|
499
|
+
return undefined;
|
|
500
|
+
if (request.resources.every((path) => inJobArea(request.directory, path))) {
|
|
501
|
+
return { verdict: "allow", reason: "inside the job's own worktrees" };
|
|
502
|
+
}
|
|
503
|
+
if (request.resources.every((path) => allowedOutside(path, allowed))) {
|
|
504
|
+
return { verdict: "allow", reason: ALLOW_OUTSIDE_REASON };
|
|
505
|
+
}
|
|
506
|
+
if (readsOutside(request) && request.resources.every((path) => taskNamesPath(request.task, path))) {
|
|
507
|
+
return { verdict: "allow", reason: "a read of a directory the task names" };
|
|
508
|
+
}
|
|
509
|
+
return undefined;
|
|
510
|
+
}
|
|
511
|
+
function describe(request) {
|
|
512
|
+
const what = request.action === "subagent"
|
|
513
|
+
? `wants to start the sub-agent ${request.resources.join(", ")}`
|
|
514
|
+
: `wants permission for "${request.action}" on: ${request.resources.join(" | ")}`;
|
|
515
|
+
const role = roleByAgent(request.agent);
|
|
516
|
+
const lines = [
|
|
517
|
+
`A coding agent in OpenCode (agent "${request.agent}") ${what}.`,
|
|
518
|
+
role ? `Its role is "${role.id}": ${role.description}` : "",
|
|
519
|
+
request.agent === MICROMANAGER.agent ? `It is the orchestrator: ${MICROMANAGER.description}` : "",
|
|
520
|
+
request.directory ? `Project directory: ${request.directory}` : "",
|
|
521
|
+
request.task ? `What it is working on:\n${request.task}` : "",
|
|
522
|
+
];
|
|
523
|
+
return lines.filter(Boolean).join("\n");
|
|
524
|
+
}
|
|
525
|
+
export const RELEVANCE_QUESTION = {
|
|
526
|
+
type: "score",
|
|
527
|
+
instructions: "How much do the paths this command deletes matter?",
|
|
528
|
+
criteria: [
|
|
529
|
+
"regenerable: a cache, build output or temporary files",
|
|
530
|
+
"project files that cannot simply be regenerated",
|
|
531
|
+
"user data, or files that matter outside the project",
|
|
532
|
+
],
|
|
533
|
+
};
|
|
534
|
+
export const PERMISSION_QUESTIONS = {
|
|
535
|
+
answer: {
|
|
536
|
+
type: "choice",
|
|
537
|
+
instructions: "Should this request be allowed?",
|
|
538
|
+
criteria: { allow: "Allow it: it fits the task and is safe to do.", deny: "Deny it: it does not fit the task or is unsafe." },
|
|
539
|
+
},
|
|
540
|
+
needs_user: {
|
|
541
|
+
type: "noul",
|
|
542
|
+
instructions: "Only the user can decide this: a matter of taste, money, data outside the project, or an effect that cannot be undone.",
|
|
543
|
+
},
|
|
544
|
+
risk: {
|
|
545
|
+
type: "score",
|
|
546
|
+
instructions: "How risky is this action?",
|
|
547
|
+
criteria: ["read only", "changes files in the project", "irreversible or outside the project"],
|
|
548
|
+
},
|
|
549
|
+
};
|
|
550
|
+
export function judge(decision, request, floors = DEFAULT_FLOORS) {
|
|
551
|
+
const answer = decision.answers.answer;
|
|
552
|
+
const needs = decision.answers.needs_user;
|
|
553
|
+
const risk = decision.answers.risk;
|
|
554
|
+
if (answer?.type !== "choice" || needs?.type !== "noul" || risk?.type !== "score") {
|
|
555
|
+
return { verdict: "user", reason: "decider left a question unanswered", latencyMs: decision.latencyMs };
|
|
556
|
+
}
|
|
557
|
+
const base = {
|
|
558
|
+
confidence: answer.confidence,
|
|
559
|
+
probability: answer.probabilities[answer.choice],
|
|
560
|
+
risk: risk.score,
|
|
561
|
+
needsUser: needs.noul,
|
|
562
|
+
latencyMs: decision.latencyMs,
|
|
563
|
+
};
|
|
564
|
+
if (needs.noul >= floors.needsUser)
|
|
565
|
+
return { ...base, verdict: "user", reason: "decider: the user must decide this" };
|
|
566
|
+
const relevance = decision.answers.path_relevance;
|
|
567
|
+
if (relevance?.type === "score" && relevance.score >= 0.5) {
|
|
568
|
+
return { ...base, verdict: "user", reason: `decider: the deleted paths matter (${relevance.score.toFixed(2)})` };
|
|
569
|
+
}
|
|
570
|
+
if (risk.score >= floors.risk)
|
|
571
|
+
return { ...base, verdict: "user", reason: "decider: too risky to decide alone" };
|
|
572
|
+
const cls = riskClass(request) === "read" && risk.score < 0.5 ? "read" : "write";
|
|
573
|
+
const floor = cls === "read" ? floors.read : floors.write;
|
|
574
|
+
if (answer.confidence < floor) {
|
|
575
|
+
return { ...base, verdict: "user", reason: `decider unsure (${answer.confidence.toFixed(2)} < ${floor} for ${cls})` };
|
|
576
|
+
}
|
|
577
|
+
return { ...base, verdict: answer.choice === "allow" ? "allow" : "deny", reason: `decider: ${answer.choice} (${cls})` };
|
|
578
|
+
}
|
|
579
|
+
// preset: the user's policy for this kind of request ("N13.shell": "fixed:allow", design.md §22). It applies after
|
|
580
|
+
// the hard rules and the deleted-path check, which it can never switch off, and replaces the decider.
|
|
581
|
+
//
|
|
582
|
+
// root: the job's worktree (or the project root), where a read needs nobody. It defaults to the request's own
|
|
583
|
+
// directory so a caller that knows nothing more still gets the fast path.
|
|
584
|
+
//
|
|
585
|
+
// allowed: the user's own `allowOutside` setting, the paths they decided a worker may reach. It is threaded into the
|
|
586
|
+
// hard rules (forbiddenOutside) and into the external_directory layers, never asked about: it is a decision the user
|
|
587
|
+
// already made in the config, not one for the decider to re-litigate per request. Default empty: with no setting, a caller's
|
|
588
|
+
// behaviour is exactly what it was before the setting existed.
|
|
589
|
+
// The asker `decide()` takes: the journaling decider, never a raw client (A2-T2b). Each case goes through
|
|
590
|
+
// Decider.ask, so the journal holds the request, the text that was sent, the questions and the answers, and the
|
|
591
|
+
// caller cannot quietly use a client that skips the egress gate. A case the decider could not answer throws, and
|
|
592
|
+
// decide() puts it to the user as it always did.
|
|
593
|
+
export function permissionAsker(decider, options = {}) {
|
|
594
|
+
return {
|
|
595
|
+
async ask(state, questions, context) {
|
|
596
|
+
const request = context?.request;
|
|
597
|
+
const asked = await decider.ask(context?.node ?? PERMISSION_NODE, { text: state }, questions, {
|
|
598
|
+
cloudAnswers: true,
|
|
599
|
+
...(options.job ? { job: options.job } : {}),
|
|
600
|
+
...(typeof request?.sessionID === "string" ? { session: request.sessionID } : {}),
|
|
601
|
+
...(request ? { request } : {}),
|
|
602
|
+
});
|
|
603
|
+
if (asked.error)
|
|
604
|
+
throw new DeciderError(asked.error);
|
|
605
|
+
return asked.decision;
|
|
606
|
+
},
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
export async function decide(asker, request, floors = DEFAULT_FLOORS, inspect = inspectPaths, preset, root = request.directory, allowed = [],
|
|
610
|
+
// Whether the worker's commands run in the sandbox (src/shell/sandbox.ts). Without it a writer's command in its worktree
|
|
611
|
+
// is no longer allowed on its text alone: what the program does is unchecked, so the decider is asked as before.
|
|
612
|
+
sandboxed = true) {
|
|
613
|
+
const rule = hardRule(request, allowed);
|
|
614
|
+
if (rule)
|
|
615
|
+
return { verdict: "user", reason: `always the user: ${rule}` };
|
|
616
|
+
// A read-only command inside the job's own worktree: it changes nothing and names no path outside, and the decider's
|
|
617
|
+
// confidence on these sits under the read floor, so asking it only turned a worker's inspection into a denial.
|
|
618
|
+
// A preset that sends this kind of request to the user still wins: it is the user's own decision.
|
|
619
|
+
const presetRules = preset === "user" || preset === "deny";
|
|
620
|
+
if (!presetRules && request.action !== "external_directory" && root !== undefined && readsOnlyInside(request, root)) {
|
|
621
|
+
return { verdict: "allow", reason: "read-only command inside the job's worktree" };
|
|
622
|
+
}
|
|
623
|
+
// A writer's own task worktree is its sandbox. Asking the decider there turned a worker's verification into denials (live
|
|
624
|
+
// runs: 478 "decider unsure" refusals on writes, among them `npm test`, a render, a screenshot and `git restore` in a
|
|
625
|
+
// worktree nobody else uses), and a worker that cannot check its work cannot finish it. Deleting a tracked file there
|
|
626
|
+
// is allowed too: git has it, and the task's diff shows it before anything merges.
|
|
627
|
+
const role = roleByAgent(request.agent)?.id;
|
|
628
|
+
if (!presetRules && request.action === "shell" && role !== undefined) {
|
|
629
|
+
const worktree = WRITERS.has(role) ? taskWorktree(root) : undefined;
|
|
630
|
+
if (sandboxed && worktree && staysInWorktree(request, worktree, root)) {
|
|
631
|
+
return { verdict: "allow", reason: "a command inside the task's own worktree" };
|
|
632
|
+
}
|
|
633
|
+
// A reader's shell asks about every command its rules do not list, so that a chain of reading programs reaches the
|
|
634
|
+
// read-only check above instead of a flat deny. What does not read is refused here, with the reason, and the decider is
|
|
635
|
+
// not asked to decide whether a role that only reads may write.
|
|
636
|
+
if (!WRITERS.has(role) && !readsOnly(request.resources)) {
|
|
637
|
+
return { verdict: "deny", reason: `a ${request.agent} only reads, and this command changes something; run read-only commands only (no writing redirects, no sed -i), or report what you needed it for` };
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
const outside = presetRules ? undefined : externalVerdict(request, allowed);
|
|
641
|
+
if (outside)
|
|
642
|
+
return outside;
|
|
643
|
+
// Layer 3: anything else outside the project is the user's, as it was before the layers existed (a preset never
|
|
644
|
+
// reached this far either: an ask outside the project was never the policy's to answer).
|
|
645
|
+
// A preset still wins over allowOutside, as it does over the job area and the task's own paths: the user wrote both,
|
|
646
|
+
// and a per-request policy is the narrower word.
|
|
647
|
+
if (request.action === "external_directory") {
|
|
648
|
+
return { verdict: "user", reason: "always the user: access outside the project" };
|
|
649
|
+
}
|
|
650
|
+
// Deleting inside the project: first what the paths are; files under version control are the user's call.
|
|
651
|
+
const deleted = request.action === "shell" ? request.resources.flatMap((c) => rmTargets(c).flat()) : [];
|
|
652
|
+
let facts = [];
|
|
653
|
+
if (deleted.length > 0) {
|
|
654
|
+
if (!request.directory)
|
|
655
|
+
return { verdict: "user", reason: "deletes files, and the project directory is unknown" };
|
|
656
|
+
facts = inspect(request.directory, deleted);
|
|
657
|
+
const kept = facts.find((f) => f.tracked !== false);
|
|
658
|
+
if (kept) {
|
|
659
|
+
const why = kept.tracked === undefined ? "not a git repository" : "under version control";
|
|
660
|
+
return { verdict: "user", reason: `deletes ${kept.path} (${why})` };
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (preset)
|
|
664
|
+
return { verdict: preset, reason: `preset by the user's policy (${preset})` };
|
|
665
|
+
if (!asker)
|
|
666
|
+
return { verdict: "user", reason: "no decision client" };
|
|
667
|
+
try {
|
|
668
|
+
const state = facts.length > 0 ? `${describe(request)}\n${relevanceFacts(facts)}` : describe(request);
|
|
669
|
+
const questions = facts.length > 0 ? { ...PERMISSION_QUESTIONS, path_relevance: RELEVANCE_QUESTION } : PERMISSION_QUESTIONS;
|
|
670
|
+
const caseFacts = { sessionID: request.sessionID, agent: request.agent, action: request.action, resources: request.resources, directory: request.directory, task: request.task };
|
|
671
|
+
return judge(await asker.ask(state, questions, { node: PERMISSION_NODE, request: caseFacts }), request, floors);
|
|
672
|
+
}
|
|
673
|
+
catch (err) {
|
|
674
|
+
return { verdict: "user", reason: `the decision client failed: ${err instanceof Error ? err.message : String(err)}` };
|
|
675
|
+
}
|
|
676
|
+
}
|