@commonlyai/cli 0.1.262 → 0.1.264

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.
@@ -24,7 +24,7 @@ import { requireSeatModel, seatModelRequired } from './seat-model.js';
24
24
  import { isPatchAfterNewestTested } from './tested-version.js';
25
25
  import { spawn as childSpawn, spawnSync } from 'child_process';
26
26
  import { createHash } from 'crypto';
27
- import { realpathSync } from 'fs';
27
+ import { existsSync, readdirSync, realpathSync, rmSync } from 'fs';
28
28
  import {
29
29
  chmod,
30
30
  lstat,
@@ -39,7 +39,7 @@ import {
39
39
  import { homedir, tmpdir } from 'os';
40
40
  import { fileURLToPath } from 'url';
41
41
  import {
42
- dirname, join, resolve as pathResolve,
42
+ dirname, isAbsolute, join, relative, resolve as pathResolve,
43
43
  } from 'path';
44
44
  import { writeCredentialFile } from '../credential-file.js';
45
45
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
@@ -86,6 +86,7 @@ const DISABLED_ENV = [
86
86
  'OPENCODE_DISABLE_AUTOUPDATE',
87
87
  ];
88
88
  const PLACEHOLDER_RE = /\$\{(COMMONLY_[A-Z_]+)\}/g;
89
+ const SPAWN_ROOT_DENY = '**/commonly-opencode-*/**';
89
90
  const PUBLIC_READ_DENIES = [
90
91
  '**/.commonly/**',
91
92
  '**/.codex/**',
@@ -93,10 +94,401 @@ const PUBLIC_READ_DENIES = [
93
94
  '**/*.env',
94
95
  '**/.env.*',
95
96
  '**/*.env.*',
97
+ // Every per-spawn root (mkdtemp `commonly-opencode-`), by name: OpenCode's
98
+ // older tools compare paths as text without following symlinks, so a
99
+ // workspace link to the temp root would otherwise reach the credential.
100
+ SPAWN_ROOT_DENY,
101
+ ];
102
+ // `.git` (a directory, or a linked worktree's file): its config can widen the
103
+ // project (`core.worktree`, Opus review #3487) or run code (`core.fsmonitor`).
104
+ const PUBLIC_EDIT_DENIES = [
105
+ ...PUBLIC_READ_DENIES, '**/.npmrc', '**/.yarnrc*', '.git', '.git/**', '**/.git', '**/.git/**',
96
106
  ];
97
- const PUBLIC_EDIT_DENIES = [...PUBLIC_READ_DENIES, '**/.npmrc', '**/.yarnrc*'];
98
107
  const PUBLIC_SAFE_ENV = /^(?:PATH|LANG|LC_[A-Z_]+|TERM|USER|LOGNAME|NO_COLOR|CI|SSL_CERT_FILE|SSL_CERT_DIR)$/;
99
108
 
109
+ // `realpathSync.native` (realpath(3)) returns the on-disk spelling, case
110
+ // included, on a case-insensitive APFS volume; the JS realpath keeps the case
111
+ // it was given, so `/PRIVATE/...` would not compare equal to `/private/...`.
112
+ const canonicalPath = (path) => realpathSync.native(path);
113
+
114
+ const realOrSelf = (path) => {
115
+ try {
116
+ return canonicalPath(path);
117
+ } catch {
118
+ return path;
119
+ }
120
+ };
121
+
122
+ const isWithin = (parent, child) => {
123
+ const rel = relative(parent, child);
124
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
125
+ };
126
+
127
+ /**
128
+ * F175a: what hides a public seat's per-spawn files (the credential file the
129
+ * grant broker's bearer names, the provider-proxy token) from OpenCode's own
130
+ * read, glob, grep and lsp tools is OpenCode's permission layer, not the jail:
131
+ * OpenCode itself must read the credential to expand `{file:}`, so Seatbelt and
132
+ * bwrap both admit the spawn root. Those tools read anything under `--dir`
133
+ * without asking and ask `external_directory` (denied here) for anything else
134
+ * (Tool.assertExternalDirectory, OpenCode 1.19.4). So the spawn root must lie
135
+ * OUTSIDE the workspace, or the deny never fires. Compared both as written and
136
+ * resolved, since macOS spells the temp root two ways (/var and /private/var).
137
+ */
138
+ /**
139
+ * The nearest ancestor of `dir` (itself included) holding a `.git` entry, by a
140
+ * plain filesystem walk. OpenCode counts the whole git worktree as inside the
141
+ * project (Instance.containsPath), so its tools reach it without asking
142
+ * external_directory, exactly as they reach --dir.
143
+ */
144
+ const gitToplevel = (dir) => {
145
+ let current = dir;
146
+ for (;;) {
147
+ if (existsSync(join(current, '.git'))) return current;
148
+ const parent = dirname(current);
149
+ if (parent === current) return null;
150
+ current = parent;
151
+ }
152
+ };
153
+
154
+ const GIT_TOPLEVEL_TIMEOUT_MS = 5000;
155
+
156
+ // Round 8 (#3487): OpenCode matches permission patterns case-sensitively and
157
+ // APFS does not, so `.GIT/config` slips past the `.git` edit deny. Config from
158
+ // the environment outranks the repo's own, however the path was spelled, so a
159
+ // public seat's git (OpenCode's and this adapter's check alike) runs no
160
+ // fsmonitor and no hook. Added after the public env filter, which drops every
161
+ // GIT_* the launcher had.
162
+ const PUBLIC_GIT_ENV = Object.freeze({
163
+ GIT_CONFIG_COUNT: '2',
164
+ GIT_CONFIG_KEY_0: 'core.fsmonitor',
165
+ GIT_CONFIG_VALUE_0: 'false',
166
+ GIT_CONFIG_KEY_1: 'core.hooksPath',
167
+ GIT_CONFIG_VALUE_1: '/dev/null',
168
+ });
169
+
170
+ /**
171
+ * The worktree git reports for the repo whose `.git` sits in `holder`, the way
172
+ * OpenCode 1.19.4 computes `Instance.worktree` (GitV2 `Git.repo.discover`: find
173
+ * `.git` upward, then `git rev-parse --show-toplevel` with that folder as cwd,
174
+ * falling back to the folder itself when git fails). `env` is the seat's own
175
+ * child environment, so both read the same config. Returns `{ top }`,
176
+ * `{ notRepo: true }` when git finds no repository there (OpenCode then has no
177
+ * worktree beyond --dir), or `{ error }`.
178
+ */
179
+ const gitReportedWorktree = (holder, env) => {
180
+ const run = spawnSync('git', ['rev-parse', '--show-toplevel'], {
181
+ cwd: holder, env, encoding: 'utf8', timeout: GIT_TOPLEVEL_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'pipe'],
182
+ });
183
+ if (run.error) return { error: run.error.code || run.error.message };
184
+ const stderr = String(run.stderr || '').trim();
185
+ if (run.status !== 0) {
186
+ if (/not a git repository/i.test(stderr)) return { notRepo: true };
187
+ return { error: `exit ${run.status}${stderr ? `: ${stderr.slice(0, 200)}` : ''}` };
188
+ }
189
+ const text = String(run.stdout || '').trim();
190
+ return text ? { top: pathResolve(holder, text) } : { error: 'empty output' };
191
+ };
192
+
193
+ // Bounds for the pre-spawn symlink walk. Reaching either one leaves the
194
+ // workspace unproven, and a seat carrying the grant broker then refuses
195
+ // (`assertSpawnRootOutsideWorkspace`), so the depth sits well above real source
196
+ // trees: it guards against a pathological tree, not an ordinary one.
197
+ const SYMLINK_WALK_BOUNDS = Object.freeze({ maxDepth: 32, maxEntries: 20000 });
198
+ // CodeRabbit round 4 (#3487): a grant-bearing spawn also walks every
199
+ // node_modules tree, links only, under its own bound. Measured 2026-11-05 on
200
+ // this repo's backend/node_modules: 44,664 entries, 63 symlinks (none leaving
201
+ // the workspace), 0.5-1.4 s on a host at load average ~90.
202
+ const DEPENDENCY_WALK_BOUNDS = Object.freeze({ maxDepth: 64, maxEntries: 200000 });
203
+ const SYMLINK_WALK_SKIP = new Set(['.git']);
204
+ const DEPENDENCY_DIR = 'node_modules';
205
+
206
+ /**
207
+ * Scan `workspace` for a symlink OpenCode's tools could follow to the per-spawn
208
+ * credential directory. Measured in OpenCode 1.19.4: `grep` and `glob` judge
209
+ * only their argument (the regex, the glob) against permission rules and check
210
+ * the search PATH as text through external_directory, so `grep` with
211
+ * `path: <workspace link to the temp root>` searches the credential's contents
212
+ * with nothing asked. This walk is what stops that, not a permission pattern.
213
+ *
214
+ * Returns `{ link, reason }` for the first offending link, `{ incomplete }` when
215
+ * a bound stopped the walk before it saw the whole tree, or null.
216
+ * - `reaches_spawn_root`: the link's target holds or lies inside `spawnRoot`.
217
+ * A dangling link (an old spawn root, since removed) can't, and is skipped.
218
+ * - `outside_workspace`: a link AT a node_modules top level (or under an
219
+ * @scope there) leading out of `boundary`. node_modules is not walked into,
220
+ * since a typical one exhausts the entry bound on every spawn; its packages'
221
+ * links are installed by the package manager inside it, while a top-level
222
+ * link out (`npm link`, a `file:` dependency) reaches a tree this walk never
223
+ * read.
224
+ *
225
+ * `deepDependencies` (a spawn that hands its credential to a remote server):
226
+ * every workspace link is held to `boundary` as well, and every node_modules tree, nested ones and @scopes included, is walked too,
227
+ * links only, under `dependencyBounds`, its own budget. A link anywhere in it
228
+ * that reaches the spawn root, or that leaves `boundary`, is refused, since a
229
+ * package tarball or postinstall script can plant `dist/x -> /tmp`, or a chain
230
+ * through a directory outside (CodeRabbit #3487). Nothing is followed, and
231
+ * only a symlink costs a realpath; a regular entry costs its dirent. A stopped
232
+ * walk reports `{ incomplete: 'dependency_entries' | 'dependency_depth' }`.
233
+ * The same mode walks every `.git` directory links-only, and treats what it
234
+ * cannot see as unproven (Opus review, #3487): a directory it cannot list
235
+ * (`incomplete: 'unreadable'`; a 0111 directory is still traversable by the
236
+ * OS) or a link realpath cannot resolve for a reason other than a missing
237
+ * target (`incomplete: 'unresolvable'`, a loop say), each with `problem:
238
+ * { path, code }`. `root` is where the walk starts: the git worktree root for a
239
+ * grant seat, since OpenCode's tools reach the whole worktree.
240
+ */
241
+ const scanWorkspaceLinks = (workspace, spawnRoot, {
242
+ boundary = workspace,
243
+ root = workspace,
244
+ bounds = SYMLINK_WALK_BOUNDS,
245
+ deepDependencies = false,
246
+ dependencyBounds = DEPENDENCY_WALK_BOUNDS,
247
+ } = {}) => {
248
+ const target = realOrSelf(spawnRoot);
249
+ const inside = realOrSelf(boundary);
250
+ let budget = bounds.maxEntries;
251
+ let dependencyBudget = dependencyBounds.maxEntries;
252
+ let incomplete = null;
253
+ let problem = null;
254
+ // A missing path (a dangling link, a directory removed mid-walk) is no route.
255
+ const ABSENT = new Set(['ENOENT', 'ENOTDIR']);
256
+ const unproven = (kind, path, err) => {
257
+ if (ABSENT.has(err?.code) || !deepDependencies) return;
258
+ incomplete = incomplete || kind;
259
+ problem = problem || { path, code: err?.code || String(err) };
260
+ };
261
+ const linkFinding = (path, { dependencyTop }) => {
262
+ let resolved;
263
+ try {
264
+ resolved = canonicalPath(path);
265
+ } catch (err) {
266
+ unproven('unresolvable', path, err);
267
+ return null;
268
+ }
269
+ if (isWithin(resolved, target) || isWithin(target, resolved)) return { link: path, reason: 'reaches_spawn_root' };
270
+ if (dependencyTop && !isWithin(inside, resolved)) return { link: path, reason: 'outside_workspace' };
271
+ return null;
272
+ };
273
+ const readEntries = (dir) => {
274
+ try {
275
+ return readdirSync(dir, { withFileTypes: true });
276
+ } catch (err) {
277
+ unproven('unreadable', dir, err);
278
+ return [];
279
+ }
280
+ };
281
+ // The top level of a node_modules, and of each @scope in it: links checked,
282
+ // nothing descended into.
283
+ const scanDependencyTop = (dir, { scoped = false } = {}) => {
284
+ const entries = readEntries(dir);
285
+ if (incomplete) return null;
286
+ for (const entry of entries) {
287
+ budget -= 1;
288
+ if (budget < 0) {
289
+ incomplete = incomplete || 'entries';
290
+ return null;
291
+ }
292
+ const path = join(dir, entry.name);
293
+ if (entry.isSymbolicLink()) {
294
+ const hit = linkFinding(path, { dependencyTop: true });
295
+ if (hit || incomplete) return hit;
296
+ } else if (!scoped && entry.isDirectory() && entry.name.startsWith('@')) {
297
+ const hit = scanDependencyTop(path, { scoped: true });
298
+ if (hit || incomplete) return hit;
299
+ }
300
+ }
301
+ return null;
302
+ };
303
+ // Every entry under one node_modules, iteratively: a link is resolved and
304
+ // judged, never descended into; a real directory is queued. The node_modules
305
+ // directory itself is level 1. A deep link is held to the top-level rule:
306
+ // one leaving `boundary` is refused, since a path argument resolves a chain
307
+ // (node_modules/x/y -> /outside/dir/y -> /tmp) in a tree never read.
308
+ const scanDependencyTree = (modulesDir) => {
309
+ const stack = [[modulesDir, 1]];
310
+ while (stack.length) {
311
+ const [dir, depth] = stack.pop();
312
+ if (depth > dependencyBounds.maxDepth) {
313
+ incomplete = incomplete || 'dependency_depth';
314
+ return null;
315
+ }
316
+ const entries = readEntries(dir);
317
+ if (incomplete) return null;
318
+ for (const entry of entries) {
319
+ dependencyBudget -= 1;
320
+ if (dependencyBudget < 0) {
321
+ incomplete = incomplete || 'dependency_entries';
322
+ return null;
323
+ }
324
+ const path = join(dir, entry.name);
325
+ if (entry.isSymbolicLink()) {
326
+ const hit = linkFinding(path, { dependencyTop: true });
327
+ if (hit || incomplete) return hit;
328
+ } else if (entry.isDirectory()) {
329
+ stack.push([path, depth + 1]);
330
+ }
331
+ }
332
+ }
333
+ return null;
334
+ };
335
+ const walk = (dir, depth) => {
336
+ if (depth > bounds.maxDepth) {
337
+ incomplete = incomplete || 'depth';
338
+ return null;
339
+ }
340
+ const entries = readEntries(dir);
341
+ if (incomplete) return null;
342
+ for (const entry of entries) {
343
+ budget -= 1;
344
+ if (budget < 0) {
345
+ incomplete = incomplete || 'entries';
346
+ return null;
347
+ }
348
+ const path = join(dir, entry.name);
349
+ if (entry.isSymbolicLink()) {
350
+ // A grant seat holds every workspace link to the boundary: a chain
351
+ // through a tree outside it (src/vendor -> /outside, a node_modules
352
+ // that is itself a link) is resolved by the OS, unread by this walk.
353
+ const hit = linkFinding(path, { dependencyTop: deepDependencies });
354
+ if (hit || incomplete) return hit;
355
+ } else if (entry.isDirectory() && entry.name === DEPENDENCY_DIR) {
356
+ const hit = scanDependencyTop(path) || (!incomplete && deepDependencies ? scanDependencyTree(path) : null);
357
+ if (hit || incomplete) return hit;
358
+ } else if (deepDependencies && entry.isDirectory() && SYMLINK_WALK_SKIP.has(entry.name)) {
359
+ // `.git` on a grant seat: links only, under the dependency budget
360
+ // (8,243 entries in this repo's own checkout, no links).
361
+ const hit = scanDependencyTree(path);
362
+ if (hit || incomplete) return hit;
363
+ } else if (entry.isDirectory() && !SYMLINK_WALK_SKIP.has(entry.name)) {
364
+ const hit = walk(path, depth + 1);
365
+ if (hit || incomplete) return hit;
366
+ }
367
+ }
368
+ return null;
369
+ };
370
+ const hit = walk(pathResolve(root), 0);
371
+ if (hit) return hit;
372
+ if (!incomplete) return null;
373
+ return problem ? { incomplete, problem } : { incomplete };
374
+ };
375
+
376
+ /**
377
+ * Refuse a public seat whose workspace lets OpenCode's tools reach the
378
+ * per-spawn credential directory. `carriesGrant` says whether this spawn hands
379
+ * its credential file to a remote MCP server (buildMcpConfig's report, the
380
+ * grant broker among them): a walk stopped by its bound refuses only then,
381
+ * since a huge monorepo should not be refused when there is no grant to protect.
382
+ */
383
+ const assertSpawnRootOutsideWorkspace = (workspace, spawnRoot, {
384
+ carriesGrant = false,
385
+ bounds = SYMLINK_WALK_BOUNDS,
386
+ dependencyBounds = DEPENDENCY_WALK_BOUNDS,
387
+ gitEnv = null,
388
+ } = {}) => {
389
+ if (typeof workspace !== 'string' || !workspace) return;
390
+ const pairs = [[pathResolve(workspace), spawnRoot], [realOrSelf(workspace), realOrSelf(spawnRoot)]];
391
+ if (pairs.some(([parent, child]) => isWithin(parent, child))) {
392
+ throw new Error(
393
+ `public OpenCode agents refuse a workspace (${workspace}) that contains the per-spawn credential directory `
394
+ + `(${spawnRoot}): OpenCode's tools could read the credential there; choose a workspace outside the temp directory`,
395
+ );
396
+ }
397
+ // Containment first: a real repo holding the spawn root also trips the
398
+ // core.worktree check below, whose message would blame a setting that isn't
399
+ // there (CI #3487).
400
+ const toplevels = pairs
401
+ .map(([parent, child]) => [gitToplevel(parent), child])
402
+ .filter(([top]) => top);
403
+ const hit = toplevels.find(([top, child]) => isWithin(top, child));
404
+ if (hit) {
405
+ throw new Error(
406
+ `public OpenCode agents refuse a workspace (${workspace}) whose git worktree (${hit[0]}) contains the per-spawn `
407
+ + `credential directory (${spawnRoot}): OpenCode's tools could read the credential there; `
408
+ + 'choose a workspace outside that repository or set TMPDIR outside it',
409
+ );
410
+ }
411
+ // Opus review round 7 (#3487): the folder holding .git is the boundary only
412
+ // while git agrees. `core.worktree` makes `--show-toplevel` (OpenCode's
413
+ // worktree) name any folder, $TMPDIR and every spawn root included.
414
+ if (gitEnv) {
415
+ const holders = [...new Set(pairs.map(([parent]) => gitToplevel(parent)).filter(Boolean))];
416
+ for (const holder of holders) {
417
+ const reported = gitReportedWorktree(holder, gitEnv);
418
+ if (reported.error) {
419
+ // A git that cannot answer (missing, timed out, failing) leaves the
420
+ // boundary a guess; no public seat runs on one (round 8, #3487).
421
+ throw new Error(
422
+ `public OpenCode agents could not confirm the git worktree of the workspace (${workspace}): `
423
+ + `git rev-parse --show-toplevel in ${holder} failed (${reported.error}); `
424
+ + 'make git available to the seat, or choose a workspace outside a git repository',
425
+ );
426
+ }
427
+ if (!reported.top) continue;
428
+ const top = realOrSelf(reported.top);
429
+ const widened = top !== realOrSelf(holder);
430
+ if (widened || isWithin(top, realOrSelf(spawnRoot)) || isWithin(top, realOrSelf(tmpdir()))) {
431
+ throw new Error(
432
+ `public OpenCode agents refuse a workspace (${workspace}) whose git reports the worktree as ${reported.top}, `
433
+ + `not ${holder}, the folder holding .git: OpenCode's tools reach the whole of that worktree, which a `
434
+ + 'core.worktree setting can widen to the temp directory and the per-spawn credential; remove the setting',
435
+ );
436
+ }
437
+ }
438
+ }
439
+ // OpenCode counts the whole git worktree as inside the project, so a
440
+ // node_modules link into it is not a link out.
441
+ const boundary = toplevels[0]?.[0] || gitToplevel(pathResolve(workspace)) || workspace;
442
+ // A grant seat walks the whole worktree OpenCode's tools can reach, sibling
443
+ // packages and .git included (Opus review, #3487); a seat without one, its
444
+ // workspace.
445
+ const finding = scanWorkspaceLinks(workspace, spawnRoot, {
446
+ boundary,
447
+ root: carriesGrant ? realOrSelf(boundary) : workspace,
448
+ bounds,
449
+ deepDependencies: carriesGrant,
450
+ dependencyBounds,
451
+ });
452
+ if (finding?.incomplete === 'unreadable' || finding?.incomplete === 'unresolvable') {
453
+ const { path, code } = finding.problem;
454
+ throw new Error(
455
+ `public OpenCode agents could not ${finding.incomplete === 'unreadable' ? 'list the directory' : 'resolve the symlink'} `
456
+ + `${path} (${code}) while checking the workspace (${workspace}) for symlinks to the per-spawn credential directory; `
457
+ + 'what the walk cannot see is not proven clean, and this seat carries a connector grant; fix its permissions, '
458
+ + 'remove it, or drop the grant broker from this seat',
459
+ );
460
+ }
461
+ if (finding?.reason === 'reaches_spawn_root') {
462
+ throw new Error(
463
+ `public OpenCode agents refuse a workspace (${workspace}) holding a symlink (${finding.link}) that reaches the per-spawn `
464
+ + `credential directory (${spawnRoot}): OpenCode's tools could read the credential through it; remove the link`,
465
+ );
466
+ }
467
+ if (finding?.reason === 'outside_workspace') {
468
+ throw new Error(
469
+ `public OpenCode agents refuse a workspace (${workspace}) holding a symlink (${finding.link}) that leads outside `
470
+ + 'the workspace, into a tree not checked for links to the per-spawn credential directory; '
471
+ + 'move the seat to a workspace without links that leave it, or remove the link',
472
+ );
473
+ }
474
+ if (finding?.incomplete?.startsWith('dependency_')) {
475
+ throw new Error(
476
+ `public OpenCode agents could not finish checking the workspace's node_modules and .git trees (${workspace}) for symlinks `
477
+ + `to the per-spawn credential directory: the link walk stopped at its ${finding.incomplete === 'dependency_depth'
478
+ ? `depth bound (${dependencyBounds.maxDepth} levels)` : `entry bound (${dependencyBounds.maxEntries} entries)`}, `
479
+ + 'and this seat carries a connector grant; prune the dependency tree, or drop the grant broker from this seat',
480
+ );
481
+ }
482
+ if (finding?.incomplete && carriesGrant) {
483
+ throw new Error(
484
+ `public OpenCode agents could not finish checking the workspace (${workspace}) for symlinks to the per-spawn `
485
+ + `credential directory: the walk stopped at its ${finding.incomplete === 'depth'
486
+ ? `depth bound (${bounds.maxDepth} levels)` : `entry bound (${bounds.maxEntries} entries)`}, and this seat `
487
+ + 'carries a connector grant; choose a smaller workspace, or drop the grant broker from this seat',
488
+ );
489
+ }
490
+ };
491
+
100
492
  const statOrNull = async (path) => {
101
493
  try {
102
494
  return await lstat(path);
@@ -219,6 +611,12 @@ const buildMcpConfig = (servers, ctx = {}) => {
219
611
  enabled: true,
220
612
  ...(Object.keys(headers).length ? { headers } : {}),
221
613
  };
614
+ // What delivered the credential file to a remote server, whatever its URL:
615
+ // the spawn's grant checks read this, not a guess at which entry is the
616
+ // broker (CodeRabbit #3487).
617
+ if (Object.values(headers).some((value) => value.includes(`{file:${ctx.credentialFile}}`))) {
618
+ ctx.bearerFileServers?.push(server.name);
619
+ }
222
620
  }
223
621
  return mcp;
224
622
  };
@@ -230,13 +628,18 @@ const publicPermissions = (mode, mcpNames) => {
230
628
  read[pattern] = 'deny';
231
629
  }
232
630
  for (const pattern of PUBLIC_EDIT_DENIES) edit[pattern] = 'deny';
631
+ // The spawn-folder rule on the search tools. OpenCode 1.19.4 matches these
632
+ // against the tool's own argument (the glob string, the grep regex), not the
633
+ // searched path or the results, and ships no `list` tool, so this stops only
634
+ // a search that names the folder; scanWorkspaceLinks stops one through a link.
635
+ const search = () => ({ '*': 'allow', [SPAWN_ROOT_DENY]: 'deny' });
233
636
  return {
234
637
  '*': 'deny',
235
638
  read,
236
639
  edit,
237
- glob: 'allow',
238
- grep: 'allow',
239
- list: 'allow',
640
+ glob: search(),
641
+ grep: search(),
642
+ list: search(),
240
643
  bash: 'deny',
241
644
  task: 'deny',
242
645
  external_directory: 'deny',
@@ -323,6 +726,7 @@ const makeEventParser = () => {
323
726
  let errorMessage = null;
324
727
  // Any text, tool call or step result means the model acted this run.
325
728
  let turnOutput = false;
729
+ let stepStarted = false;
326
730
  // Every tool call that came back as an error, for the public-seat check in
327
731
  // spawn (publicToolFailure).
328
732
  const toolErrors = [];
@@ -333,6 +737,7 @@ const makeEventParser = () => {
333
737
  if (event.sessionID) sessionId = event.sessionID;
334
738
  // Any step event means the run started a turn, so it is not safe to replay.
335
739
  if (String(event.type || '').startsWith('step_') || event.type === 'tool_use') turnOutput = true;
740
+ if (event.type === 'step_start') stepStarted = true;
336
741
  if (event.type === 'text' && typeof event.part?.text === 'string') {
337
742
  turnOutput = true;
338
743
  text += event.part.text;
@@ -355,6 +760,7 @@ const makeEventParser = () => {
355
760
  };
356
761
  return {
357
762
  get turnOutput() { return turnOutput; },
763
+ get stepStarted() { return stepStarted; },
358
764
  consume(chunk) {
359
765
  buffer += chunk.toString();
360
766
  let newline;
@@ -416,7 +822,9 @@ const publicToolFailedError = ({ tool, error }) => {
416
822
  return failure;
417
823
  };
418
824
 
419
- const runOpenCode = ({ cmd, args, cwd, env, timeoutMs, credentials, spawnImpl = childSpawn, onSpawn, controls = {} }) => new Promise((resolve, reject) => {
825
+ const runOpenCode = ({
826
+ cmd, args, cwd, env, timeoutMs, credentials, spawnImpl = childSpawn, onSpawn, controls = {}, onFirstStep,
827
+ }) => new Promise((resolve, reject) => {
420
828
  let proc;
421
829
  try {
422
830
  proc = spawnImpl(cmd, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
@@ -438,7 +846,24 @@ const runOpenCode = ({ cmd, args, cwd, env, timeoutMs, credentials, spawnImpl =
438
846
  clearTimeout(timer);
439
847
  if (killTimer) clearTimeout(killTimer);
440
848
  };
441
- proc.stdout?.on('data', (chunk) => events.consume(chunk));
849
+ let stepSeen = false;
850
+ let stepHookError = null;
851
+ proc.stdout?.on('data', (chunk) => {
852
+ events.consume(chunk);
853
+ if (!stepSeen && events.stepStarted) {
854
+ stepSeen = true;
855
+ // Synchronous, in the same tick the event is parsed, so the gap before
856
+ // the model's first tool call is as short as this process can make it.
857
+ // A hook that throws ends the turn: the child is killed, and the error
858
+ // is the turn's result.
859
+ try {
860
+ onFirstStep?.();
861
+ } catch (err) {
862
+ stepHookError = err;
863
+ proc.kill('SIGKILL');
864
+ }
865
+ }
866
+ });
442
867
  proc.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
443
868
  proc.on('error', (err) => {
444
869
  clearTimers();
@@ -447,6 +872,7 @@ const runOpenCode = ({ cmd, args, cwd, env, timeoutMs, credentials, spawnImpl =
447
872
  proc.on('close', (code) => {
448
873
  clearTimers();
449
874
  events.flush();
875
+ if (stepHookError) return reject(stepHookError);
450
876
  if (timedOut) return reject(new Error(`opencode timed out after ${timeoutMs}ms`));
451
877
  if (events.errorMessage) {
452
878
  const err = adapterFailure('opencode turn failed', events.errorMessage, {
@@ -564,6 +990,7 @@ const makeChildEnvironment = ({
564
990
  home,
565
991
  tempWork,
566
992
  credentialFile,
993
+ publicSeat = false,
567
994
  }) => {
568
995
  const env = { ...source };
569
996
  // A parent launcher may itself have received injected OpenCode config. These
@@ -584,6 +1011,7 @@ const makeChildEnvironment = ({
584
1011
  env.TMPDIR = tempWork;
585
1012
  env.OPENCODE_AUTO_SHARE = 'false';
586
1013
  for (const key of DISABLED_ENV) env[key] = '1';
1014
+ if (publicSeat) Object.assign(env, PUBLIC_GIT_ENV);
587
1015
  return withholdRuntimeCredential(env, { credentialFile });
588
1016
  };
589
1017
 
@@ -758,7 +1186,7 @@ export default {
758
1186
  // F118: a public seat reads its memory but is not offered a write.
759
1187
  memoryReadOnly: isPublic,
760
1188
  });
761
- const tempDir = await mkdtemp(join(tmpdir(), 'commonly-opencode-'));
1189
+ const tempDir = await mkdtemp(join(ctx._tempRoot || tmpdir(), 'commonly-opencode-'));
762
1190
  await chmod(tempDir, 0o700);
763
1191
  const configPath = join(tempDir, 'opencode.json');
764
1192
  const configDir = join(tempDir, 'config-dir');
@@ -818,6 +1246,7 @@ export default {
818
1246
  ]);
819
1247
  const unavailableMcp = [];
820
1248
  const mcpReadDirectories = [];
1249
+ const bearerFileServers = [];
821
1250
  const mcp = buildMcpConfig(ctx.environment?.mcp, {
822
1251
  runtimeToken: ctx.runtimeToken,
823
1252
  instanceUrl: instanceProxy
@@ -826,14 +1255,28 @@ export default {
826
1255
  publicSeat: isPublic,
827
1256
  unavailableMcp,
828
1257
  mcpReadDirectories,
1258
+ bearerFileServers,
829
1259
  });
830
1260
  if (unavailableMcp.length) throw publicMcpUnavailableError(unavailableMcp);
1261
+ // A remote server that holds this spawn's credential file can spend
1262
+ // whatever the credential reaches, a connector grant included. The broker
1263
+ // entry that reaches the adapter has passed the daemon's withhold
1264
+ // (grant-broker-guard.js), but buildMcpConfig hands the file to any http
1265
+ // entry declaring `Bearer ${COMMONLY_AGENT_TOKEN}`, whatever its URL, so
1266
+ // the walk's fail-closed rule keys on what was written (CodeRabbit #3487).
1267
+ const carriesGrant = bearerFileServers.length > 0;
831
1268
  const config = {
832
1269
  permission: isPublic
833
1270
  ? publicPermissions(sandboxMode, Object.keys(mcp))
834
1271
  : 'allow',
835
1272
  share: 'disabled',
836
1273
  autoupdate: false,
1274
+ // A public seat runs no LSP server or formatter: both execute workspace
1275
+ // code (a planted tsserver.js, a prettier config) inside the jail, where
1276
+ // the credential is readable. Off by OpenCode's default in 1.19.x
1277
+ // (`if (!cfg.lsp)`, `if (!cfg.formatter)`); pinned here so a default
1278
+ // flip in a later release changes nothing.
1279
+ ...(isPublic ? { lsp: false, formatter: false } : {}),
837
1280
  ...(provider ? {
838
1281
  enabled_providers: [provider.id],
839
1282
  provider: buildProviderConfig(providerProxy
@@ -858,7 +1301,18 @@ export default {
858
1301
  home,
859
1302
  tempWork,
860
1303
  credentialFile: credential?.path || null,
1304
+ publicSeat: isPublic,
861
1305
  });
1306
+ if (isPublic) {
1307
+ // After the child env exists: the git check runs under the very env
1308
+ // OpenCode gets (its HOME, its XDG config, no GIT_* from the launcher).
1309
+ assertSpawnRootOutsideWorkspace(ctx.cwd || process.cwd(), tempDir, {
1310
+ carriesGrant,
1311
+ bounds: ctx._symlinkWalkBounds || SYMLINK_WALK_BOUNDS,
1312
+ dependencyBounds: ctx._dependencyWalkBounds || DEPENDENCY_WALK_BOUNDS,
1313
+ gitEnv: childEnv,
1314
+ });
1315
+ }
862
1316
  const args = buildArgs({
863
1317
  prompt: fullPrompt,
864
1318
  sessionId: ctx.sessionId,
@@ -934,6 +1388,30 @@ export default {
934
1388
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
935
1389
  credentials,
936
1390
  spawnImpl: ctx._spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(args.slice(0, -1), { modelFlag: '-m', effortFlag: '--variant', valueFlags: ['-s', '--dir', '--title', '--format'] }),
1391
+ // CodeRabbit #3487: the walk cannot prove a whole node_modules tree
1392
+ // free of a deep link to the temp root, so a credential handed to a
1393
+ // remote server stops existing once OpenCode has read it. Measured in
1394
+ // the 1.19.4 binary: {file:} is expanded once, over the config text at
1395
+ // load; every MCP connect (a reconnect included) takes its headers from
1396
+ // that cached config; and `run` emits step_start only after tools are
1397
+ // resolved and each MCP server, the shipped stdio one included (it reads
1398
+ // COMMONLY_TOKEN_FILE at startup), has connected. A config reload after
1399
+ // this point would fail on the missing file, closed, not open.
1400
+ // A delete that fails leaves the credential readable, so the turn ends
1401
+ // rather than run on with it (`force` already ignores a missing file).
1402
+ onFirstStep: isPublic && carriesGrant && credential
1403
+ ? () => {
1404
+ try {
1405
+ (ctx._rmSync || rmSync)(credential.path, { force: true });
1406
+ } catch (err) {
1407
+ throw new Error(
1408
+ `public OpenCode seat could not delete its connector credential (${credential.path}) once OpenCode `
1409
+ + `had loaded its config: ${err?.message || err}; the turn was stopped so the credential does not `
1410
+ + 'stay readable to its tools',
1411
+ );
1412
+ }
1413
+ }
1414
+ : undefined,
937
1415
  });
938
1416
  if (isPublic) {
939
1417
  const failure = publicToolFailure(result.toolErrors, ctx.environment?.mcp);
@@ -965,5 +1443,6 @@ export {
965
1443
  readOpenCodeVersion,
966
1444
  qualifiedProviderModel,
967
1445
  resolveProviderKeyFile,
1446
+ scanWorkspaceLinks,
968
1447
  startProviderProxy,
969
1448
  };
@@ -225,8 +225,8 @@ export const resolveMcpServers = (mcpServers, ctx = {}) => {
225
225
  }
226
226
  // The grant broker is the one http entry that carries AUTHORITY rather
227
227
  // than data: a granted seat acts on external systems as the granter. pi is
228
- // not admitted to grant-broker confinement (ADAPTERS_WITH_GRANT_BROKER is
229
- // claude and codex; a public pi's Seatbelt jail, F113b, has not been
228
+ // not admitted to grant-broker confinement (it is not in
229
+ // ADAPTERS_WITH_GRANT_BROKER; a public pi's Seatbelt jail, F113b, has not been
230
230
  // reviewed for that), so the reach is refused here as well as at the
231
231
  // server's projection — this
232
232
  // layer is what holds when the backend predates that refusal, when the
@@ -52,10 +52,12 @@ export const ADAPTERS_WITH_DEFAULT_SANDBOX = new Set(['claude', 'codex', 'openco
52
52
  // adapter runs (D247 walk, 11-04; F113b).
53
53
  export const ADAPTERS_WITH_SANDBOX_ENFORCEMENT = new Set([...ADAPTERS_WITH_DEFAULT_SANDBOX, 'goose', 'pi']);
54
54
 
55
- // The server has not yet admitted OpenCode to its grant-broker confinement
56
- // allowlist. Keep runtime sandbox support separate from the narrower set of
57
- // adapters that may receive a room grant.
58
- export const ADAPTERS_WITH_GRANT_BROKER = new Set(['claude', 'codex']);
55
+ // Adapters that may receive a room grant: each confines a public seat AND keeps
56
+ // the per-spawn credential out of its own tools' reach (OpenCode: F175a, its
57
+ // external_directory deny with the credential outside --dir). Narrower than the
58
+ // sandbox sets above on purpose, and mirrored by the server's
59
+ // CONFINING_ADAPTERS (backend/services/grantBrokerConfinement.ts).
60
+ export const ADAPTERS_WITH_GRANT_BROKER = new Set(['claude', 'codex', 'opencode']);
59
61
 
60
62
  /**
61
63
  * The sandbox an unconfigured seat gets.