zcode-acp-server 0.86.1 → 0.88.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.
Files changed (61) hide show
  1. package/README.md +11 -9
  2. package/README.zh-CN.md +8 -5
  3. package/dist/backend/index.d.ts +1 -1
  4. package/dist/backend/index.d.ts.map +1 -1
  5. package/dist/backend/index.js +1 -1
  6. package/dist/backend/index.js.map +1 -1
  7. package/dist/backend/resolve.d.ts +10 -0
  8. package/dist/backend/resolve.d.ts.map +1 -1
  9. package/dist/backend/resolve.js +60 -3
  10. package/dist/backend/resolve.js.map +1 -1
  11. package/dist/backend/sandbox.d.ts +85 -83
  12. package/dist/backend/sandbox.d.ts.map +1 -1
  13. package/dist/backend/sandbox.js +314 -222
  14. package/dist/backend/sandbox.js.map +1 -1
  15. package/dist/code-fingerprint.json +2 -2
  16. package/dist/config/deferred-probe-capability.d.ts +4 -0
  17. package/dist/config/deferred-probe-capability.d.ts.map +1 -1
  18. package/dist/config/deferred-probe-capability.js +110 -33
  19. package/dist/config/deferred-probe-capability.js.map +1 -1
  20. package/dist/config/options.d.ts +49 -0
  21. package/dist/config/options.d.ts.map +1 -1
  22. package/dist/config/options.js +194 -49
  23. package/dist/config/options.js.map +1 -1
  24. package/dist/config/settings.d.ts +1 -1
  25. package/dist/config/settings.d.ts.map +1 -1
  26. package/dist/config/settings.js +1 -1
  27. package/dist/config/settings.js.map +1 -1
  28. package/dist/config/user-config.d.ts +3 -3
  29. package/dist/config/user-config.d.ts.map +1 -1
  30. package/dist/handlers/account.d.ts +20 -1
  31. package/dist/handlers/account.d.ts.map +1 -1
  32. package/dist/handlers/account.js +29 -3
  33. package/dist/handlers/account.js.map +1 -1
  34. package/dist/handlers/dispatch.js +1 -1
  35. package/dist/handlers/dispatch.js.map +1 -1
  36. package/dist/handlers/sandbox-allow.d.ts +5 -4
  37. package/dist/handlers/sandbox-allow.d.ts.map +1 -1
  38. package/dist/handlers/sandbox-allow.js +22 -30
  39. package/dist/handlers/sandbox-allow.js.map +1 -1
  40. package/dist/handlers/session.d.ts.map +1 -1
  41. package/dist/handlers/session.js +25 -9
  42. package/dist/handlers/session.js.map +1 -1
  43. package/dist/i18n.js +14 -14
  44. package/dist/i18n.js.map +1 -1
  45. package/dist/quota/startplan.d.ts +100 -0
  46. package/dist/quota/startplan.d.ts.map +1 -0
  47. package/dist/quota/startplan.js +218 -0
  48. package/dist/quota/startplan.js.map +1 -0
  49. package/dist/server.d.ts +10 -10
  50. package/dist/server.d.ts.map +1 -1
  51. package/dist/server.js +22 -17
  52. package/dist/server.js.map +1 -1
  53. package/dist/translators/event-translator.d.ts.map +1 -1
  54. package/dist/translators/event-translator.js +12 -0
  55. package/dist/translators/event-translator.js.map +1 -1
  56. package/docs/CONFIG-OPTIONS.md +112 -0
  57. package/docs/SANDBOX.md +59 -35
  58. package/docs/TROUBLESHOOTING.md +1 -1
  59. package/docs/proposals/0002-plan-quota-usage.md +10 -0
  60. package/package.json +3 -2
  61. package/scripts/postinstall.mjs +27 -0
@@ -12,11 +12,17 @@
12
12
  * (name-banning executables would be trivially bypassed and is deliberately
13
13
  * not done).
14
14
  *
15
- * Arming is dual-switch (see sandboxActive): ZCODE_ACP_SANDBOX=1 forces it
16
- * globally, or a workspace opts in via `enabled: true` in its own
17
- * .zcode/acp/sandbox.json — the template is auto-created with enabled:false
18
- * only while the sandbox is globally armed (an unarmed bridge leaves the
19
- * workspace untouched), so opting in is always an explicit user edit.
15
+ * Arming is the GLOBAL switch only (`sandbox.enabled` in the user config
16
+ * file, or ZCODE_ACP_SANDBOX=1). The per-project switch
17
+ * (`<workspace>/.zcode/acp/sandbox.json`) was REMOVED (2026-11-17): all
18
+ * path grants now live in one machine-global file next to the user config
19
+ * (`~/.config/zcode-acp/sandbox.json`, XDG aware), auto-created on first
20
+ * backend spawn with a pre-granted toolchain template (~/go, ~/.gradle,
21
+ * ~/.m2, ...). A legacy per-project file still lying around is migrated
22
+ * once — its allow/deny/strictGit merged into the global file, and its
23
+ * `enabled: true` carried onto the global switch so an upgrade never
24
+ * silently disarms a machine that had the sandbox on. Workspaces stay
25
+ * untouched (#332): nothing is ever written into the project tree.
20
26
  *
21
27
  * Whitelist (frozen at spawn, rebuilt on backend restart):
22
28
  * - workspace roots of all live sessions (union of server.sessionCwds)
@@ -24,26 +30,32 @@
24
30
  * denying it breaks session/create itself)
25
31
  * - system temp + regenerable cache dirs (zero-value targets, constant
26
32
  * toolchain traffic)
27
- * - each project's `.zcode/acp/sandbox.json` `allow` list
28
- * - bridge-lifetime once-allows granted via the dynamic allow flow
33
+ * - the global config's `allow` list + bridge-lifetime once-allows granted
34
+ * via the dynamic allow flow
29
35
  *
30
- * `<workspace>/.zcode/acp/` is a DENY island inside every allowed workspace:
31
- * the sandbox forbids writes there while the bridge — outside the sandbox —
32
- * persists "always allow" entries on the user's behalf. The agent cannot
33
- * edit its own allowlist.
36
+ * The global config directory (`~/.config/zcode-acp/`) is DENIED in every
37
+ * profile: the bridge — outside the sandbox — persists popup grants there on
38
+ * the user's behalf, and the agent must not be able to edit its own
39
+ * allowlist or the hub credentials that live beside it. The base write-deny
40
+ * already covers it; the explicit deny also holds in the
41
+ * workspace-root-is-its-ancestor edge (a workspace rooted at $HOME would
42
+ * otherwise re-permit it).
34
43
  *
35
44
  * macOS-only: Seatbelt is a macOS facility. Setting the env elsewhere warns
36
45
  * once and runs unsandboxed (see sandboxActive()).
37
46
  */
38
- import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync, } from "node:fs";
47
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
39
48
  import os from "node:os";
40
49
  import path from "node:path";
41
50
  import process from "node:process";
42
51
  import { log, warn } from "../utils.js";
43
52
  import { globalSandboxEnabled } from "../config/settings.js";
53
+ import { userConfigPath } from "../config/user-config.js";
54
+ import { readJsonDocument, writeJsonAtomic } from "../settings/atomic-write.js";
44
55
  /**
45
56
  * The global env/config switch (`ZCODE_ACP_SANDBOX`, or `sandbox.enabled` in
46
- * the user config file). Every other knob is project config.
57
+ * the user config file). Path grants live in the global sandbox.json — this
58
+ * switch only arms.
47
59
  */
48
60
  export const SANDBOX_ENV = "ZCODE_ACP_SANDBOX";
49
61
  /** Regenerable cache dirs trusted as default-writable (ADR-0011). */
@@ -68,193 +80,305 @@ const DEFAULT_CACHE_DIRS = [
68
80
  const DEFAULT_TEMP_DIRS = ["/private/tmp", "/private/var/tmp", "/private/var/folders"];
69
81
  /** Backend state roots that must stay writable for the bridge to function. */
70
82
  const ZCODE_STATE_DIRS = ["~/.zcode", "~/.zcode-beta", "~/.zcode-plugin"];
71
- /** Path of the per-project sandbox config inside a workspace root. */
72
- export function sandboxConfigPath(workspaceRoot) {
73
- return path.join(workspaceRoot, ".zcode", "acp", "sandbox.json");
83
+ /**
84
+ * Toolchain home dirs the auto-created template pre-grants. All are
85
+ * regenerable-or-reinstallable targets with constant build traffic; the user
86
+ * edits the file to trim or extend the list (~/Library/Caches-style cache
87
+ * trees are already covered by DEFAULT_CACHE_DIRS). Same risk class as the
88
+ * long-default-writable ~/.npm (which also carries .npmrc tokens).
89
+ */
90
+ const TOOLCHAIN_TEMPLATE_ALLOW = [
91
+ "~/go", // GOPATH default: module cache (pkg/mod) + go install bin
92
+ "~/.gradle", // wrapper dists, dependency caches, daemon registry
93
+ "~/.m2", // Maven local repository
94
+ "~/.cargo", // Rust registry + installed cargo binaries
95
+ "~/.rustup", // Rust toolchains
96
+ "~/.cocoapods", // CocoaPods specs/repos
97
+ "~/.pub-cache", // Dart/Flutter packages
98
+ "~/.nuget", // .NET package cache
99
+ "~/.pnpm-store", // pnpm content-addressable store
100
+ "~/.bun", // Bun install cache + binaries
101
+ "~/.android", // Android debug keystores, AVD data
102
+ "~/Library/Android/sdk", // Android SDK (gradle writes build artifacts)
103
+ ];
104
+ /** Path of the machine-global sandbox config, beside the user config file. */
105
+ export function globalSandboxConfigPath() {
106
+ return path.join(path.dirname(userConfigPath()), "sandbox.json");
74
107
  }
75
- /** Roots whose template auto-creation already failed — warn once, not per call. */
76
- const templateFailedRoots = new Set();
77
- /** Config issues already warned — once per root(+issue), not per read. */
78
- const warnedConfigIssues = new Set();
79
108
  /**
80
- * Last enabled value successfully parsed per config file. A config that
81
- * becomes unreadable (EACCES/ENOTDIR) or VANISHES after parsing enabled:true
82
- * must fail closed: the sandboxed agent can produce all of those from inside
83
- * the sandbox (chmod 0000 `.zcode`, replace `.zcode` with a file, rename it
84
- * away) — falling back to the disabled template would silently disarm.
109
+ * Directory holding the global config (and config.json itself). Denied in
110
+ * every profile — the agent must not edit its own allowlist or the hub
111
+ * credentials next to it, and this deny must survive a workspace allow that
112
+ * covers the directory (workspace rooted at $HOME).
85
113
  */
86
- const lastEnabledSeen = new Map();
87
- function defaultConfig(enabled) {
88
- return { enabled, allow: [], deny: [], strictGit: false };
114
+ export function globalSandboxConfigDir() {
115
+ return resolveReal(path.dirname(userConfigPath()));
89
116
  }
117
+ /** Config issues already warned — once per issue, not per read. */
118
+ const warnedGlobalIssues = new Set();
90
119
  /**
91
- * The config file must be a REGULAR file whose real location is exactly
92
- * <root>/.zcode/acp/sandbox.json. A symlinked or hardlinked-away config
93
- * pierces the deny island: the agent writes the link target inside the
94
- * allowed workspace and thereby edits its own allowlist. Missing files are
95
- * fine — that is the auto-create path.
120
+ * Filter to absolute/`~/` entries and warn once about the dropped rest.
121
+ * Relative entries would anchor to the BRIDGE's cwd — a shared file must
122
+ * speak in absolute paths or `~/` only.
96
123
  */
97
- function configIntegrityOk(workspaceRoot, file) {
98
- try {
99
- const st = lstatSync(file);
100
- if (!st.isFile() || st.nlink > 1)
101
- return false;
102
- return realpathSync(file) === sandboxConfigPath(resolveReal(workspaceRoot));
103
- }
104
- catch {
105
- return true; // missing (or unreadable parents) → template path
106
- }
124
+ function sanitizePathList(raw, file, issueKey) {
125
+ if (!Array.isArray(raw))
126
+ return [];
127
+ const list = raw.filter((p) => typeof p === "string");
128
+ const absolute = list.filter((p) => p.startsWith("/") || p.startsWith("~/"));
129
+ if (absolute.length !== list.length && !warnedGlobalIssues.has(`${file}:${issueKey}`)) {
130
+ warnedGlobalIssues.add(`${file}:${issueKey}`);
131
+ warn(`sandbox: dropped ${list.length - absolute.length} non-absolute ${issueKey} entries in ${file}`);
132
+ }
133
+ return absolute;
134
+ }
135
+ /** Parse a global-config-shaped object (unknown fields ignored). */
136
+ function sanitizeGlobalSandboxConfig(parsed) {
137
+ return {
138
+ allow: Array.isArray(parsed.allow) ? parsed.allow : [],
139
+ deny: Array.isArray(parsed.deny) ? parsed.deny : [],
140
+ strictGit: parsed.strictGit === true,
141
+ };
107
142
  }
108
143
  /**
109
- * Read the project sandbox config. While the sandbox is globally armed, a
110
- * missing config is auto-created as the discovery template (enabled: false)
111
- * so the user finds the file and can flip the switch — the PRESENCE of the
112
- * file is never the switch, only `enabled` is, so the auto-create cannot arm
113
- * anything by itself. An unarmed bridge writes NOTHING: headless per-task
114
- * runs must not leave an untracked .zcode/ in every workspace they touch
115
- * (#332). A malformed or non-object file
116
- * falls back to enabled:true WITHOUT rewriting it: corruption must fail
117
- * CLOSED (the user opted in; losing that to a half-saved file would silently
118
- * disarm), and clobbering the user's mid-edit bytes with a template would be
119
- * worse than the transient read. A symlinked/hardlinked config is treated
120
- * the same way (armed, persistence disabled) — see configIntegrityOk. So is
121
- * a config that was armed and then became unreadable or disappeared — only
122
- * the agent could do that from inside the sandbox.
144
+ * Live-read the machine-global sandbox config. Absent = nothing granted (the
145
+ * file is only auto-created once, by ensureGlobalSandboxConfig; a user
146
+ * DELETING it chose empty grants, and it is not resurrected). Malformed
147
+ * bytes read as empty + a one-time warn, and persistGlobalSandboxConfig
148
+ * refuses to overwrite them — the user's half-saved buffer survives.
123
149
  */
124
- export function readSandboxConfig(workspaceRoot) {
125
- const file = sandboxConfigPath(workspaceRoot);
126
- if (!configIntegrityOk(workspaceRoot, file)) {
127
- if (!warnedConfigIssues.has(file)) {
128
- warnedConfigIssues.add(file);
129
- warn(`sandbox: ${file} is symlinked/hardlinked outside the deny island — reading as armed; fix the link (persistence stays disabled until then)`);
130
- }
131
- return defaultConfig(true);
132
- }
150
+ export function readGlobalSandboxConfig() {
151
+ const file = globalSandboxConfigPath();
133
152
  let text;
134
153
  try {
135
154
  text = readFileSync(file, "utf8");
136
155
  }
137
- catch (e) {
138
- const code = e.code;
139
- // ENOENT on a never-armed project is the normal pre-template state.
140
- // Everything else — EACCES/ENOTDIR (agent tampered with `.zcode`), or a
141
- // miss on a config this bridge already read as armed — fails closed.
142
- if (code === "ENOENT" && lastEnabledSeen.get(file) !== true) {
143
- // The discovery template is written ONLY while the sandbox is globally
144
- // armed (user config sandbox.enabled or ZCODE_ACP_SANDBOX=1): a
145
- // headless client that starts a bridge per task must not litter every
146
- // workspace with an untracked .zcode/ the user never opted into
147
- // (#332). The project switch cannot be on while the file is missing,
148
- // so the global arm is the only one that can license the write.
149
- // Best-effort either way; a read-only workspace just never gets one —
150
- // the sandbox can still be env-armed.
151
- if (globalWanted() && !templateFailedRoots.has(workspaceRoot)) {
152
- try {
153
- mkdirSync(path.dirname(file), { recursive: true });
154
- writeFileSync(file, JSON.stringify(defaultConfig(false), null, 2) + "\n");
155
- }
156
- catch (err) {
157
- templateFailedRoots.add(workspaceRoot);
158
- warn(`sandbox: could not create ${file}: ${err instanceof Error ? err.message : String(err)}`);
159
- }
160
- }
161
- return defaultConfig(false);
162
- }
163
- const issue = code ?? "vanished";
164
- if (!warnedConfigIssues.has(`${file}:${issue}`)) {
165
- warnedConfigIssues.add(`${file}:${issue}`);
166
- warn(`sandbox: ${file} unreadable (${issue}) — reading as armed`);
167
- }
168
- return defaultConfig(true);
156
+ catch {
157
+ return { allow: [], deny: [], strictGit: false };
169
158
  }
170
159
  let parsed;
171
160
  try {
172
161
  parsed = JSON.parse(text);
173
162
  }
174
163
  catch {
175
- lastEnabledSeen.set(file, true);
176
- return defaultConfig(true);
164
+ if (!warnedGlobalIssues.has(`${file}:malformed`)) {
165
+ warnedGlobalIssues.add(`${file}:malformed`);
166
+ warn(`sandbox: ${file} is not valid JSON — reading as empty grants`);
167
+ }
168
+ return { allow: [], deny: [], strictGit: false };
177
169
  }
178
170
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
179
- lastEnabledSeen.set(file, true);
180
- return defaultConfig(true);
171
+ if (!warnedGlobalIssues.has(`${file}:shape`)) {
172
+ warnedGlobalIssues.add(`${file}:shape`);
173
+ warn(`sandbox: ${file} is not a JSON object — reading as empty grants`);
174
+ }
175
+ return { allow: [], deny: [], strictGit: false };
181
176
  }
182
- const cfg = parsed;
183
- const allow = Array.isArray(cfg.allow) ? cfg.allow.filter((p) => typeof p === "string") : [];
184
- const deny = Array.isArray(cfg.deny) ? cfg.deny.filter((p) => typeof p === "string") : [];
185
- // Relative (or `~user`) entries would silently anchor to the BRIDGE's cwd —
186
- // a committed config must speak in absolute paths or `~/` only.
187
- const absoluteAllow = allow.filter((p) => p.startsWith("/") || p.startsWith("~/"));
188
- const absoluteDeny = deny.filter((p) => p.startsWith("/") || p.startsWith("~/"));
189
- if (absoluteAllow.length !== allow.length && !warnedConfigIssues.has(`${file}:relative`)) {
190
- warnedConfigIssues.add(`${file}:relative`);
191
- warn(`sandbox: dropped ${allow.length - absoluteAllow.length} non-absolute allow entries in ${file}`);
192
- }
193
- if (absoluteDeny.length !== deny.length && !warnedConfigIssues.has(`${file}:relative-deny`)) {
194
- warnedConfigIssues.add(`${file}:relative-deny`);
195
- warn(`sandbox: dropped ${deny.length - absoluteDeny.length} non-absolute deny entries in ${file}`);
196
- }
197
- lastEnabledSeen.set(file, cfg.enabled === true);
177
+ const cfg = sanitizeGlobalSandboxConfig(parsed);
198
178
  return {
199
- enabled: cfg.enabled === true,
200
- allow: absoluteAllow,
201
- deny: absoluteDeny,
202
- strictGit: cfg.strictGit === true,
179
+ allow: sanitizePathList(cfg.allow, file, "allow"),
180
+ deny: sanitizePathList(cfg.deny, file, "deny"),
181
+ strictGit: cfg.strictGit,
203
182
  };
204
183
  }
205
184
  /**
206
- * Bridge-side persistence for "always allow" (the deny island keeps the
207
- * agent from writing this file itself). Round-trips the whole config so the
208
- * enabled flag survives the write. Dedupes by exact string. Returns false
209
- * when persistence is impossible (symlinked config, unwritable path) — the
210
- * caller then downgrades to a bridge-lifetime once-allow.
185
+ * Sync read-modify-write persistence (temp file + rename, lazy-alias-store
186
+ * pattern). The only writers are bridge processes outside the sandbox, so a
187
+ * lost update between two concurrent bridges costs one re-asked popup, never
188
+ * a torn file. REFUSES to write over unparseable bytes.
211
189
  */
212
- export function appendSandboxAllow(workspaceRoot, allowedPath) {
213
- const file = sandboxConfigPath(workspaceRoot);
214
- if (!configIntegrityOk(workspaceRoot, file)) {
215
- warn(`sandbox: refusing to persist through a symlinked/hardlinked ${file}`);
216
- return false;
190
+ function persistGlobalSandboxConfig(mutate) {
191
+ const file = globalSandboxConfigPath();
192
+ let cfg;
193
+ let raw;
194
+ try {
195
+ raw = readFileSync(file, "utf8");
217
196
  }
218
- const cfg = readSandboxConfig(workspaceRoot);
219
- if (cfg.allow.includes(allowedPath))
220
- return true;
221
- cfg.allow.push(allowedPath);
197
+ catch {
198
+ raw = ""; // absent — mutate starts from empty
199
+ }
200
+ if (raw !== "") {
201
+ let parsed;
202
+ try {
203
+ parsed = JSON.parse(raw);
204
+ }
205
+ catch {
206
+ parsed = undefined;
207
+ }
208
+ if (parsed === undefined ||
209
+ parsed === null ||
210
+ typeof parsed !== "object" ||
211
+ Array.isArray(parsed)) {
212
+ if (!warnedGlobalIssues.has(`${file}:refuse-write`)) {
213
+ warnedGlobalIssues.add(`${file}:refuse-write`);
214
+ warn(`sandbox: ${file} is unparseable — refusing to overwrite it (fix the file by hand)`);
215
+ }
216
+ return false;
217
+ }
218
+ cfg = sanitizeGlobalSandboxConfig(parsed);
219
+ }
220
+ else {
221
+ cfg = { allow: [], deny: [], strictGit: false };
222
+ }
223
+ const next = mutate(cfg);
222
224
  try {
223
225
  mkdirSync(path.dirname(file), { recursive: true });
224
- writeFileSync(file, JSON.stringify({ enabled: cfg.enabled, allow: cfg.allow, deny: cfg.deny, strictGit: cfg.strictGit }, null, 2) + "\n");
225
- log(`sandbox: allowlisted ${allowedPath} in ${file}`);
226
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
227
+ writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n");
228
+ renameSync(tmp, file);
226
229
  return true;
227
230
  }
228
231
  catch (e) {
229
- warn(`sandbox: could not persist allowlist: ${e instanceof Error ? e.message : String(e)}`);
232
+ warn(`sandbox: could not persist ${file}: ${e instanceof Error ? e.message : String(e)}`);
230
233
  return false;
231
234
  }
232
235
  }
233
236
  /**
234
- * Bridge-side persistence for the popup's "永不放行" choice — the visible
235
- * counterpart of appendSandboxAllow: a denied path is RECORDED in the
236
- * config (never hidden in bridge memory), so the ask never resurfaces for
237
- * it and the user can review or undo the decision by editing the file.
237
+ * Bridge-side persistence for the popup's "始终允许" choice: append to the
238
+ * global allow list. Returns false when persistence is impossible
239
+ * (unparseable/unwritable file) — the caller downgrades to a bridge-lifetime
240
+ * once-allow.
238
241
  */
239
- export function appendSandboxDeny(workspaceRoot, deniedPath) {
240
- const file = sandboxConfigPath(workspaceRoot);
241
- if (!configIntegrityOk(workspaceRoot, file)) {
242
- warn(`sandbox: refusing to persist through a symlinked/hardlinked ${file}`);
243
- return false;
242
+ export function appendGlobalSandboxAllow(allowedPath) {
243
+ const ok = persistGlobalSandboxConfig((cfg) => cfg.allow.includes(allowedPath) ? cfg : { ...cfg, allow: [...cfg.allow, allowedPath] });
244
+ if (ok)
245
+ log(`sandbox: allowlisted ${allowedPath} in ${globalSandboxConfigPath()}`);
246
+ return ok;
247
+ }
248
+ /**
249
+ * The visible counterpart for "永不放行": a denied path is RECORDED in the
250
+ * global config, so the ask never resurfaces for it and the user can review
251
+ * or undo the decision by editing the file.
252
+ */
253
+ export function appendGlobalSandboxDeny(deniedPath) {
254
+ const ok = persistGlobalSandboxConfig((cfg) => cfg.deny.includes(deniedPath) ? cfg : { ...cfg, deny: [...cfg.deny, deniedPath] });
255
+ if (ok)
256
+ log(`sandbox: denylisted ${deniedPath} in ${globalSandboxConfigPath()}`);
257
+ return ok;
258
+ }
259
+ /** Path of the deprecated per-project config (migration reads only). */
260
+ export function sandboxConfigPath(workspaceRoot) {
261
+ return path.join(workspaceRoot, ".zcode", "acp", "sandbox.json");
262
+ }
263
+ /**
264
+ * Tolerant legacy read for migration: missing/unparseable → null (nothing to
265
+ * migrate — a corrupt leftover must not block the global template), relative
266
+ * entries dropped (same rule the file always had).
267
+ */
268
+ function readLegacySandboxConfig(workspaceRoot) {
269
+ let parsed;
270
+ try {
271
+ parsed = JSON.parse(readFileSync(sandboxConfigPath(workspaceRoot), "utf8"));
244
272
  }
245
- const cfg = readSandboxConfig(workspaceRoot);
246
- if (cfg.deny.includes(deniedPath))
247
- return true;
248
- cfg.deny.push(deniedPath);
273
+ catch {
274
+ return null;
275
+ }
276
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
277
+ return null;
278
+ const cfg = parsed;
279
+ const keep = (list) => Array.isArray(list)
280
+ ? list.filter((p) => typeof p === "string" && (p.startsWith("/") || p.startsWith("~/")))
281
+ : [];
282
+ return {
283
+ enabled: cfg.enabled === true,
284
+ allow: keep(cfg.allow),
285
+ deny: keep(cfg.deny),
286
+ strictGit: cfg.strictGit === true,
287
+ };
288
+ }
289
+ /** Settled flag: the global config settle (create+migrate) runs once per process. */
290
+ let globalConfigSettled = false;
291
+ /**
292
+ * One-shot per process: materialize the machine-global sandbox config.
293
+ * Absent file → create it (O_EXCL — a sibling bridge winning the race is
294
+ * fine, its content stands) from the toolchain template UNIONed with any
295
+ * legacy per-project configs of the live roots. A legacy `enabled: true`
296
+ * arms the GLOBAL switch (never silently disarm an upgraded machine); an
297
+ * explicit `sandbox.enabled: false` in the user config wins over the
298
+ * migration. Never writes into workspaces (#332).
299
+ */
300
+ export async function ensureGlobalSandboxConfig(cwdRoots) {
301
+ if (globalConfigSettled)
302
+ return;
303
+ globalConfigSettled = true; // set first: a failure must not retry every spawn
304
+ const file = globalSandboxConfigPath();
305
+ if (existsSync(file))
306
+ return; // user-managed from here on; deletion = empty grants
307
+ const legacyAllow = [];
308
+ const legacyDeny = [];
309
+ let legacyStrictGit = false;
310
+ let legacyArmed = false;
311
+ for (const root of cwdRoots) {
312
+ const legacy = readLegacySandboxConfig(resolveReal(root));
313
+ if (!legacy)
314
+ continue;
315
+ for (const p of legacy.allow)
316
+ if (!legacyAllow.includes(p))
317
+ legacyAllow.push(p);
318
+ for (const p of legacy.deny)
319
+ if (!legacyDeny.includes(p))
320
+ legacyDeny.push(p);
321
+ legacyStrictGit = legacyStrictGit || legacy.strictGit;
322
+ legacyArmed = legacyArmed || legacy.enabled;
323
+ }
324
+ const config = {
325
+ allow: [...new Set([...TOOLCHAIN_TEMPLATE_ALLOW, ...legacyAllow])],
326
+ deny: [...new Set(legacyDeny)],
327
+ strictGit: legacyStrictGit,
328
+ };
249
329
  try {
250
330
  mkdirSync(path.dirname(file), { recursive: true });
251
- writeFileSync(file, JSON.stringify({ enabled: cfg.enabled, allow: cfg.allow, deny: cfg.deny, strictGit: cfg.strictGit }, null, 2) + "\n");
252
- log(`sandbox: denylisted ${deniedPath} in ${file}`);
253
- return true;
331
+ writeFileSync(file, JSON.stringify(config, null, 2) + "\n", { flag: "wx" });
332
+ log(`sandbox: created ${file}` +
333
+ (legacyAllow.length + legacyDeny.length > 0
334
+ ? ` (migrated ${legacyAllow.length} allow / ${legacyDeny.length} deny legacy entries)`
335
+ : " (toolchain template)"));
254
336
  }
255
337
  catch (e) {
256
- warn(`sandbox: could not persist denylist: ${e instanceof Error ? e.message : String(e)}`);
257
- return false;
338
+ if (e.code !== "EEXIST") {
339
+ warn(`sandbox: could not create ${file}: ${e instanceof Error ? e.message : String(e)}`);
340
+ return; // the read path treats absence as empty grants; nothing else to do
341
+ }
342
+ // EEXIST: a sibling bridge won the create race — its content stands.
343
+ }
344
+ if (legacyArmed)
345
+ await migrateLegacyArming();
346
+ }
347
+ /**
348
+ * Carry a legacy per-project `enabled: true` onto the global switch. The
349
+ * project switch no longer exists, so doing nothing would silently disarm a
350
+ * machine that had the sandbox on — the arming intent migrates instead
351
+ * (fail-closed direction). An explicit `sandbox.enabled: false` in the user
352
+ * config is the user's later decision and wins; then we only warn.
353
+ */
354
+ async function migrateLegacyArming() {
355
+ const file = userConfigPath();
356
+ try {
357
+ if (globalSandboxEnabled())
358
+ return; // already armed (env or file)
359
+ const current = await readJsonDocument(file);
360
+ const sandbox = current !== null && typeof current["sandbox"] === "object" && current["sandbox"] !== null
361
+ ? current["sandbox"]
362
+ : null;
363
+ if (sandbox !== null && sandbox["enabled"] === false) {
364
+ warn(`sandbox: a legacy project config had enabled:true, but ${file} explicitly sets ` +
365
+ "sandbox.enabled:false — NOT arming; flip that key to re-arm");
366
+ return;
367
+ }
368
+ await writeJsonAtomic(file, (cur) => {
369
+ const section = typeof cur["sandbox"] === "object" && cur["sandbox"] !== null
370
+ ? { ...cur["sandbox"] }
371
+ : {};
372
+ if (section["enabled"] === true)
373
+ return cur;
374
+ return { ...cur, sandbox: { ...section, enabled: true } };
375
+ });
376
+ warn(`sandbox: legacy per-project sandbox switch migrated — armed globally via ` +
377
+ `sandbox.enabled:true in ${file} (edit that file to turn it off)`);
378
+ }
379
+ catch (e) {
380
+ warn(`sandbox: legacy arm migration failed (${e instanceof Error ? e.message : String(e)}) — ` +
381
+ `set sandbox.enabled:true in ${file} to re-arm`);
258
382
  }
259
383
  }
260
384
  /** Expand a leading `~` to the real home dir. */
@@ -300,30 +424,32 @@ function sb(p) {
300
424
  * Build the SBPL profile text. SBPL resolves overlapping rules by LAST
301
425
  * match (verified empirically: an allow emitted after a deny re-permits the
302
426
  * write), so the layout is: base deny-all, then every allow, then the deny
303
- * carve-outs (island, strictGit) LAST so nothing can override them.
427
+ * carve-outs (global config dir, strictGit, profile dirs) LAST so nothing
428
+ * can override them.
304
429
  */
305
430
  export function buildSandboxProfile(input) {
306
431
  const allows = [];
307
432
  const denies = [];
308
- for (const ws of input.workspaces) {
433
+ const seenRoots = new Set();
434
+ for (const root of input.workspaceRoots) {
309
435
  // Resolve here too (idempotent): direct callers may pass symlinked
310
436
  // roots (/tmp → /private/tmp) that would silently fail subpath match.
311
- const root = resolveReal(ws.root);
312
- allows.push(`(allow file-write* (subpath ${sb(root)}))`);
313
- // Deny island: the sandbox config lives INSIDE the writable workspace —
314
- // without this carve-out the agent could grant itself permissions.
315
- denies.push(`(deny file-write* (subpath ${sb(path.join(root, ".zcode", "acp"))}))`);
316
- if (ws.config.strictGit) {
317
- denies.push(`(deny file-write* (subpath ${sb(path.join(root, ".git"))}))`);
318
- }
319
- for (const allowed of ws.config.allow) {
320
- allows.push(`(allow file-write* (subpath ${sb(resolveReal(allowed))}))`);
437
+ const real = resolveReal(root);
438
+ if (seenRoots.has(real))
439
+ continue;
440
+ seenRoots.add(real);
441
+ allows.push(`(allow file-write* (subpath ${sb(real)}))`);
442
+ if (input.config.strictGit) {
443
+ denies.push(`(deny file-write* (subpath ${sb(path.join(real, ".git"))}))`);
321
444
  }
322
445
  }
446
+ for (const allowed of input.config.allow) {
447
+ allows.push(`(allow file-write* (subpath ${sb(resolveReal(allowed))}))`);
448
+ }
323
449
  for (const p of [...ZCODE_STATE_DIRS, ...DEFAULT_CACHE_DIRS, ...DEFAULT_TEMP_DIRS]) {
324
450
  allows.push(`(allow file-write* (subpath ${sb(resolveReal(p))}))`);
325
451
  }
326
- for (const allowed of input.extraAllow) {
452
+ for (const allowed of input.onceAllows ?? []) {
327
453
  allows.push(`(allow file-write* (subpath ${sb(resolveReal(allowed))}))`);
328
454
  }
329
455
  allows.push(`(allow file-write* (subpath ${sb(resolveReal(process.env.TMPDIR ?? os.tmpdir()))}))`);
@@ -343,6 +469,11 @@ export function buildSandboxProfile(input) {
343
469
  allows.push(`(allow file-write* (literal "/dev/ptmx"))`);
344
470
  allows.push(`(allow file-write* (require-all (regex #"^/dev/ttys[0-9]+$") ` +
345
471
  `(extension "com.apple.sandbox.pty")))`);
472
+ // The global config dir (sandbox.json + config.json + hub credentials):
473
+ // agent-unreachable by policy — the bridge persists grants there from
474
+ // OUTSIDE the sandbox. Emitted in the deny tail so a workspace allow that
475
+ // covers it (a workspace rooted at $HOME) can never re-permit it.
476
+ denies.push(`(deny file-write* (subpath ${sb(globalSandboxConfigDir())}))`);
346
477
  if (input.profileDir) {
347
478
  denies.push(`(deny file-write* (subpath ${sb(input.profileDir)}))`);
348
479
  }
@@ -351,65 +482,27 @@ export function buildSandboxProfile(input) {
351
482
  }
352
483
  return (["(version 1)", "(allow default)", "(deny file-write*)", ...allows, ...denies].join("\n") + "\n");
353
484
  }
354
- /** Resolved arm input for the CURRENT spawn: union of all live workspaces. */
355
- export function collectSandboxWorkspaces(cwdRoots) {
356
- const seen = new Set();
357
- const workspaces = [];
358
- const extraAllow = [];
359
- for (const root of cwdRoots) {
360
- const real = resolveReal(root);
361
- if (seen.has(real))
362
- continue;
363
- seen.add(real);
364
- const config = readSandboxConfig(real);
365
- workspaces.push({ root: real, config });
366
- // Allowlists from OTHER workspaces still apply when they share this
367
- // backend: the agent may hop projects in one bridge lifetime.
368
- for (const allowed of config.allow)
369
- extraAllow.push(allowed);
370
- }
371
- // A workspace's own allow entries are emitted with its block above; drop
372
- // them from extraAllow so they don't appear twice (harmless, but noisy).
373
- const own = new Set(workspaces.flatMap((ws) => ws.config.allow.map(resolveReal)));
374
- return {
375
- workspaces,
376
- extraAllow: [...new Set(extraAllow.map(resolveReal))].filter((p) => !own.has(p)),
377
- };
378
- }
379
485
  let platformWarned = false;
380
- /**
381
- * Global arm request: `sandbox.enabled` in the user config file (file wins)
382
- * or ZCODE_ACP_SANDBOX=1/true. Live read — a config flip mid-run is seen at
383
- * the next sandboxActive call (applySandboxFlip applies it at prompt entry).
384
- */
486
+ /** Global arm request: `sandbox.enabled` in the user config file (file wins) or ZCODE_ACP_SANDBOX=1/true. */
385
487
  function globalWanted() {
386
488
  return globalSandboxEnabled();
387
489
  }
388
490
  /**
389
- * The project-level switch: `enabled: true` inside the workspace's sandbox
390
- * config. Reading also materializes the template for discovery — but only
391
- * while the sandbox is globally armed (see readSandboxConfig). Once the
392
- * sandbox is armed the deny island keeps the agent from flipping the switch
393
- * back off.
394
- */
395
- export function projectSandboxEnabled(workspaceRoot) {
396
- return readSandboxConfig(workspaceRoot).enabled;
397
- }
398
- /**
399
- * Whether the sandbox should arm for this bridge: the global switch
400
- * (config file `sandbox.enabled` or ZCODE_ACP_SANDBOX=1) OR any given
401
- * workspace root opted in via sandbox.json `enabled` (project switch,
402
- * re-checked per call so a flip mid-run is seen). macOS-only: elsewhere a
403
- * requested sandbox warns once and runs unsandboxed.
491
+ * Whether the sandbox should arm for this bridge: the GLOBAL switch only
492
+ * (user config `sandbox.enabled` or ZCODE_ACP_SANDBOX=1) — the per-project
493
+ * opt-in was removed with the per-project config (2026-11-17; a legacy
494
+ * enabled:true was migrated onto the global switch by
495
+ * ensureGlobalSandboxConfig). Live read — a config flip mid-run is seen at
496
+ * the next sandboxActive call (applySandboxFlip applies it at prompt entry).
497
+ * macOS-only: elsewhere a requested sandbox warns once and runs unsandboxed.
404
498
  */
405
- export function sandboxActive(roots = [process.cwd()]) {
406
- const wanted = globalWanted() || [...roots].some(projectSandboxEnabled);
407
- if (!wanted)
499
+ export function sandboxActive() {
500
+ if (!globalWanted())
408
501
  return false;
409
502
  if (process.platform !== "darwin") {
410
503
  if (!platformWarned) {
411
504
  platformWarned = true;
412
- warn(`sandbox: requested (${SANDBOX_ENV}=1, config file, or project config) but Seatbelt is macOS-only — running WITHOUT sandbox`);
505
+ warn(`sandbox: requested (${SANDBOX_ENV}=1 or config file) but Seatbelt is macOS-only — running WITHOUT sandbox`);
413
506
  }
414
507
  return false;
415
508
  }
@@ -418,9 +511,8 @@ export function sandboxActive(roots = [process.cwd()]) {
418
511
  /** Test hook: reset cached decisions and warn-once sets. */
419
512
  export function resetSandboxDecisionForTest() {
420
513
  platformWarned = false;
421
- templateFailedRoots.clear();
422
- warnedConfigIssues.clear();
423
- lastEnabledSeen.clear();
514
+ warnedGlobalIssues.clear();
515
+ globalConfigSettled = false;
424
516
  }
425
517
  /** Previous respawn's profile dir — removed once superseded (its backend is dead). */
426
518
  let lastProfileDir = null;