@commonlyai/cli 0.1.341 → 0.1.343

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.
@@ -2,11 +2,13 @@ import { Transform } from 'node:stream';
2
2
  import { StringDecoder } from 'node:string_decoder';
3
3
  /** The per-spawn loopback proxy that holds a provider key for a CLI (OpenAI chat, Anthropic Messages, OpenAI Responses). */
4
4
  import { randomBytes, timingSafeEqual } from 'crypto';
5
- import { constants as fsConstants, realpathSync } from 'fs';
5
+ import { constants as fsConstants, realpathSync, statSync } from 'fs';
6
6
  import { createServer, request as httpRequest } from 'http';
7
7
  import { request as httpsRequest } from 'https';
8
8
  import { chmod, lstat, open, unlink, writeFile } from 'fs/promises';
9
- import { isAbsolute, relative, sep } from 'path';
9
+ import {
10
+ dirname, isAbsolute, relative, sep,
11
+ } from 'path';
10
12
 
11
13
  // Providers sometimes echo request headers in an error response. Redact the
12
14
  // material across arbitrary stream chunk boundaries before any model sees it.
@@ -112,8 +114,64 @@ const isPathWithin = (parent, candidate) => {
112
114
  && !fromParent.startsWith(`..${sep}`)
113
115
  && !isAbsolute(fromParent));
114
116
  };
115
- /** Validate the key path without reading the key. The proxy reads it at spawn. */
116
- export const resolveProviderKeyFile = async (provider, workspacePath, adapterLabel = 'OpenCode') => {
117
+ // What the file system says a path IS, not how it was spelled: one device and
118
+ // inode, whatever the letter case on a case-insensitive volume, a macOS
119
+ // firmlink (/System/Volumes/Data/opt is /opt) or a symlinked directory.
120
+ // BigInt: inodes on the macOS sealed system volume exceed 2^53, and as numbers
121
+ // /usr and /usr/bin round to the same value.
122
+ const identityOf = (path) => {
123
+ try {
124
+ const details = statSync(path, { bigint: true });
125
+ return `${details.dev}:${details.ino}`;
126
+ } catch {
127
+ return null;
128
+ }
129
+ };
130
+
131
+ const realOrSelf = (path) => {
132
+ try { return realpathSync(path); } catch { return path; }
133
+ };
134
+
135
+ /**
136
+ * The root a sandbox could read this key file through, or null. A subpath root
137
+ * holds the file when it is the file's directory or one of its ancestors; a
138
+ * literal root only when it is the file itself. Either of two tests refuses:
139
+ * the paths as written and real-pathed (which also covers a root that doesn't
140
+ * exist yet), and file identity, so any spelling the file system resolves to
141
+ * the same place is treated as that place. A second hard link is refused by
142
+ * resolveProviderKeyFile (one link only), not here.
143
+ */
144
+ export const keyFileReadableRoot = (keyFile, { subpaths = [], literals = [] } = {}) => {
145
+ const ancestors = new Set();
146
+ for (let current = keyFile; ; current = dirname(current)) {
147
+ const id = identityOf(current);
148
+ if (id) ancestors.add(id);
149
+ if (dirname(current) === current) break;
150
+ }
151
+ for (const root of subpaths) {
152
+ if (isPathWithin(root, keyFile) || isPathWithin(realOrSelf(root), keyFile)) return root;
153
+ const id = identityOf(root);
154
+ if (id && ancestors.has(id)) return root;
155
+ }
156
+ const own = identityOf(keyFile);
157
+ for (const root of literals) {
158
+ if (root === keyFile || realOrSelf(root) === keyFile) return root;
159
+ if (own && identityOf(root) === own) return root;
160
+ }
161
+ return null;
162
+ };
163
+
164
+ /**
165
+ * Validate the key path without reading the key. The proxy reads it at spawn.
166
+ * `readableRoots` ({ subpaths, literals }) is what a sandboxed seat can read;
167
+ * the proxy reads the key outside the sandbox, so a key file there is refused.
168
+ */
169
+ export const resolveProviderKeyFile = async (
170
+ provider,
171
+ workspacePath,
172
+ adapterLabel = 'OpenCode',
173
+ { readableRoots } = {},
174
+ ) => {
117
175
  if (!provider) return null;
118
176
  const keyFile = provider.keyFile;
119
177
  if (typeof keyFile !== 'string' || !isAbsolute(keyFile)) {
@@ -134,6 +192,11 @@ export const resolveProviderKeyFile = async (provider, workspacePath, adapterLab
134
192
  if ((details.mode & 0o777) !== 0o600) {
135
193
  throw new Error(`${adapterLabel} provider.keyFile must have mode 0600`);
136
194
  }
195
+ // One name only: a second link elsewhere is the same file under a path the
196
+ // checks below never look at.
197
+ if (details.nlink !== 1) {
198
+ throw new Error(`${adapterLabel} provider.keyFile must have exactly one link (no hard links)`);
199
+ }
137
200
  if (typeof workspacePath !== 'string' || !isAbsolute(workspacePath)) {
138
201
  throw new Error(`${adapterLabel} provider.keyFile requires an absolute workspace path`);
139
202
  }
@@ -145,9 +208,15 @@ export const resolveProviderKeyFile = async (provider, workspacePath, adapterLab
145
208
  } catch (err) {
146
209
  throw new Error(`${adapterLabel} provider key path could not be resolved: ${err.message}`);
147
210
  }
148
- if (isPathWithin(realWorkspace, realKeyFile)) {
211
+ if (isPathWithin(realWorkspace, realKeyFile) || keyFileReadableRoot(realKeyFile, { subpaths: [realWorkspace] })) {
149
212
  throw new Error(`${adapterLabel} provider.keyFile must be outside the workspace`);
150
213
  }
214
+ const readableRoot = readableRoots ? keyFileReadableRoot(realKeyFile, readableRoots) : null;
215
+ if (readableRoot) {
216
+ throw new Error(
217
+ `${adapterLabel} provider.keyFile ${realKeyFile} is inside the seat's sandbox; move it outside ${readableRoot}`,
218
+ );
219
+ }
151
220
  return realKeyFile;
152
221
  };
153
222
 
@@ -156,8 +225,8 @@ const readProviderKey = async (keyFile, adapterLabel) => {
156
225
  const handle = await open(keyFile, fsConstants.O_RDONLY | noFollow);
157
226
  try {
158
227
  const details = await handle.stat();
159
- if (!details.isFile() || (details.mode & 0o777) !== 0o600) {
160
- throw new Error(`${adapterLabel} provider.keyFile changed after validation; expected a regular mode-0600 file`);
228
+ if (!details.isFile() || (details.mode & 0o777) !== 0o600 || details.nlink !== 1) {
229
+ throw new Error(`${adapterLabel} provider.keyFile changed after validation; expected a regular mode-0600 file with one link`);
161
230
  }
162
231
  const value = (await handle.readFile()).toString('utf8').trim();
163
232
  if (!value) throw new Error(`${adapterLabel} provider.keyFile must not be empty`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.341",
3
+ "version": "0.1.343",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -154,6 +154,7 @@ import {
154
154
  isClaudeSignedOut,
155
155
  spawnFailureReason,
156
156
  } from '../lib/turn-failure-notice.js';
157
+ import { missingHarnessHint, reportMissingHarness } from '../lib/missing-harness.js';
157
158
  import {
158
159
  ADDRESSED_EVENT_TYPES,
159
160
  isPersonMention,
@@ -557,9 +558,10 @@ export const bootstrapAgentRecordFromEnv = async ({
557
558
  const instanceUrl = (env.COMMONLY_API_URL || '').trim() || resolveInstanceUrl(undefined);
558
559
 
559
560
  let identity;
561
+ let client;
560
562
  try {
561
- identity = await clientFactory({ instance: instanceUrl, token: runtimeToken })
562
- .get('/api/agents/runtime/installations');
563
+ client = clientFactory({ instance: instanceUrl, token: runtimeToken });
564
+ identity = await client.get('/api/agents/runtime/installations');
563
565
  } catch (err) {
564
566
  throw new Error(
565
567
  `Could not resolve the agent behind COMMONLY_AGENT_TOKEN against ${instanceUrl}: ${err.message}. `
@@ -580,7 +582,10 @@ export const bootstrapAgentRecordFromEnv = async ({
580
582
  throw new Error(`Unknown adapter '${adapterOverride}'. Known: ${(adapterRegistry.listPublicAdapterNames || adapterRegistry.listAdapterNames)().join(', ')}`);
581
583
  }
582
584
  if (!await adapter.detect()) {
583
- throw new Error(`Adapter '${adapterOverride}' not found on PATH.`);
585
+ // F457: this run exits before it checks in, so the page would wait for
586
+ // it forever. Say what was missing there, and how to get it here.
587
+ await reportMissingHarness(client, adapterOverride);
588
+ throw new Error(`Adapter '${adapterOverride}' not found on PATH. ${missingHarnessHint(adapterOverride)}`);
584
589
  }
585
590
  } else {
586
591
  const missing = [];
@@ -591,6 +596,7 @@ export const bootstrapAgentRecordFromEnv = async ({
591
596
  missing.push(candidate);
592
597
  }
593
598
  if (!adapterName) {
599
+ await reportMissingHarness(client, null);
594
600
  const err = new Error(
595
601
  `No supported agent CLI found on PATH (looked for: ${BOOTSTRAP_ADAPTER_DETECT_ORDER.join(', ')}). `
596
602
  + 'Install one, or pass --adapter <name>.',
@@ -358,7 +358,10 @@ export default {
358
358
  if (!TESTED_DSH_VERSIONS.includes(detected?.version)) {
359
359
  throw new Error(`dsh adapter: installed version ${detected?.version || 'unknown'} is not smoke-tested (${TESTED_DSH_VERSIONS.join(', ')})`);
360
360
  }
361
- return resolveProviderKeyFile(environment.provider, workspacePath, 'dsh');
361
+ // A confined dsh is a private seat under Seatbelt, so it is checked too.
362
+ return resolveProviderKeyFile(environment.provider, workspacePath, 'dsh', {
363
+ environment, sandboxed: isConfinedDsh(environment),
364
+ });
362
365
  },
363
366
 
364
367
  async detect() {
@@ -396,7 +399,10 @@ export default {
396
399
  if (!TESTED_DSH_VERSIONS.includes(version)) {
397
400
  throw new Error(`dsh adapter: installed version ${version || 'unknown'} is not smoke-tested (${TESTED_DSH_VERSIONS.join(', ')})`);
398
401
  }
399
- const keyFile = await resolveProviderKeyFile(ctx.environment.provider, ctx.cwd, 'dsh');
402
+ // The seat home is the confined run's statePath: stable and writable in the jail.
403
+ const keyFile = await resolveProviderKeyFile(ctx.environment.provider, ctx.cwd, 'dsh', {
404
+ environment: ctx.environment, platform: ctx._platform, sandboxed: confined, seatDirectories: [home],
405
+ });
400
406
  const tempDir = await mkdtemp(join(tmpdir(), 'commonly-dsh-'));
401
407
  await chmod(tempDir, 0o700);
402
408
  let proxy;
@@ -312,7 +312,7 @@ export default {
312
312
  assertSandboxSupported(environment);
313
313
  const validation = validateEnvironmentSpec(environment || {});
314
314
  if (!validation.ok) throw new Error(validation.errors.join('; '));
315
- return resolveProviderKeyFile(environment?.provider, workspacePath, 'Goose');
315
+ return resolveProviderKeyFile(environment?.provider, workspacePath, 'Goose', { environment });
316
316
  },
317
317
 
318
318
  async detect() {
@@ -716,7 +716,7 @@ const buildProviderConfig = (provider, model, keyFile) => {
716
716
  };
717
717
  };
718
718
 
719
- const validateProviderEnvironment = async (environment, workspacePath) => {
719
+ const validateProviderEnvironment = async (environment, workspacePath, options = {}) => {
720
720
  if (environment?.provider === undefined) return null;
721
721
  const validation = validateEnvironmentSpec({
722
722
  provider: environment.provider,
@@ -725,7 +725,7 @@ const validateProviderEnvironment = async (environment, workspacePath) => {
725
725
  if (!validation.ok) {
726
726
  throw new Error(`Invalid OpenCode provider configuration: ${validation.errors.join('; ')}`);
727
727
  }
728
- return resolveProviderKeyFile(environment.provider, workspacePath);
728
+ return resolveProviderKeyFile(environment.provider, workspacePath, undefined, { environment, ...options });
729
729
  };
730
730
 
731
731
  const STALE_SESSION_PATTERN = /session not found/i;
@@ -939,6 +939,10 @@ const seatIdentity = (ctx) => [
939
939
  ctx.metadata?.event?.podId || 'default-pod',
940
940
  ].join('\0');
941
941
 
942
+ /** A public seat's stable data home: Seatbelt's statePath, bwrap's write-outside. */
943
+ const openCodeSeatRoot = (ctx) => ctx._opencodeHomeRoot
944
+ || join(homedir(), '.commonly', 'opencode-homes', createHash('sha256').update(seatIdentity(ctx)).digest('hex').slice(0, 24));
945
+
942
946
  const prepareOpenCodeDataHome = async (ctx, { publicSeat = false } = {}) => {
943
947
  const operatorDataHome = ctx.env?.XDG_DATA_HOME
944
948
  || process.env.XDG_DATA_HOME
@@ -951,8 +955,7 @@ const prepareOpenCodeDataHome = async (ctx, { publicSeat = false } = {}) => {
951
955
  authPath: null,
952
956
  };
953
957
  }
954
- const identity = createHash('sha256').update(seatIdentity(ctx)).digest('hex').slice(0, 24);
955
- const root = ctx._opencodeHomeRoot || join(homedir(), '.commonly', 'opencode-homes', identity);
958
+ const root = openCodeSeatRoot(ctx);
956
959
  const operatorAppData = join(pathResolve(operatorDataHome), 'opencode');
957
960
  if (pathResolve(root) === pathResolve(operatorAppData)) {
958
961
  throw new Error('OpenCode seat data must be isolated from the operator OpenCode data directory');
@@ -1181,7 +1184,11 @@ export default {
1181
1184
  if (ctx.providerKey && (!isPublic || !['workspace', 'read-only', 'bwrap'].includes(sandboxMode))) {
1182
1185
  throw new Error('Own provider keys require a confined OpenCode runtime');
1183
1186
  }
1184
- const providerKeyFile = ctx.providerKey ? null : await validateProviderEnvironment(ctx.environment, ctx.cwd);
1187
+ // The public seat home is readable and writable in the sandbox, so a key
1188
+ // file there is refused with the platform roots, before anything opens it.
1189
+ const providerKeyFile = ctx.providerKey ? null : await validateProviderEnvironment(ctx.environment, ctx.cwd, {
1190
+ platform: ctx._platform, seatDirectories: isPublic ? [openCodeSeatRoot(ctx)] : [],
1191
+ });
1185
1192
 
1186
1193
  const sourceEnv = ctx.env || process.env;
1187
1194
  const childSourceEnv = Object.fromEntries(Object.entries(sourceEnv)
@@ -53,7 +53,7 @@ import {
53
53
  } from 'fs/promises';
54
54
  import { homedir } from 'os';
55
55
  import {
56
- dirname, isAbsolute, join, relative, sep,
56
+ dirname, isAbsolute, join,
57
57
  } from 'path';
58
58
  import { fileURLToPath } from 'url';
59
59
  import {
@@ -72,7 +72,7 @@ import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } fro
72
72
  import { removeCredentialFile, writeCredentialFile } from '../credential-file.js';
73
73
  import { resolvePublicSandboxMode } from '../sandbox/mode.js';
74
74
  import { seatbeltSystemReadRoots, wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
75
- import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
75
+ import { keyFileReadableRoot, resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
76
76
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
77
77
  import { promptTokens } from '../session-recycle.js';
78
78
 
@@ -335,11 +335,11 @@ const SHARED_PROVIDER_KEYS = ['id', 'baseURL', 'keyFile', 'models'];
335
335
  const isSharedProvider = (spec) => Boolean(spec) && SHARED_PROVIDER_KEYS.some((key) => spec[key] !== undefined);
336
336
 
337
337
  /** The real key file of a shared provider, validated without reading it; null for any other seat. */
338
- const sharedProviderKeyFile = async (environment, workspacePath) => {
338
+ const sharedProviderKeyFile = async (environment, workspacePath, platform) => {
339
339
  if (!isSharedProvider(environment?.provider)) return null;
340
340
  const validation = validateEnvironmentSpec(environment);
341
341
  if (!validation.ok) throw new Error(validation.errors.join('; '));
342
- return resolveProviderKeyFile(environment.provider, workspacePath, 'pi');
342
+ return resolveProviderKeyFile(environment.provider, workspacePath, 'pi', { environment, platform });
343
343
  };
344
344
 
345
345
  /**
@@ -348,25 +348,19 @@ const sharedProviderKeyFile = async (environment, workspacePath) => {
348
348
  * own directories (the seat home is a stable path a key file could be put in),
349
349
  * and the Seatbelt baseline admits system trees such as /etc, /opt/homebrew/lib
350
350
  * and /usr/local/lib (seatbeltSystemReadRoots, read from the profile itself).
351
- * A key under any of them would be readable from inside, so it is refused.
352
- * Each root is compared as written and through its real path (/etc is
353
- * /private/etc on macOS); a root that does not exist is compared as written.
351
+ * A key under any of them would be readable from inside, so it is refused. The
352
+ * comparison is the shared keyFileReadableRoot (F453): as written, real-pathed
353
+ * and by identity, so another spelling of the same path is caught too. The
354
+ * system roots are also checked when the key file is first resolved; this is
355
+ * where the per-turn directories join them.
354
356
  */
355
- const realOrSelf = (path) => { try { return realpathSync(path); } catch { return path; } };
356
- const within = (root, path) => {
357
- const fromRoot = relative(root, path);
358
- return fromRoot !== '..' && !fromRoot.startsWith(`..${sep}`) && !isAbsolute(fromRoot);
359
- };
360
357
  export const refuseKeyFileInJail = (keyFile, readableDirectories, systemRoots = seatbeltSystemReadRoots()) => {
361
- const refuse = (root) => {
358
+ const root = keyFileReadableRoot(keyFile, {
359
+ subpaths: [...readableDirectories, ...systemRoots.subpaths],
360
+ literals: systemRoots.literals,
361
+ });
362
+ if (root) {
362
363
  throw new Error(`pi adapter: provider.keyFile ${keyFile} is inside the sandbox of a public seat; move it outside ${root}`);
363
- };
364
- const forms = (root) => [...new Set([root, realOrSelf(root)])];
365
- for (const directory of [...readableDirectories, ...systemRoots.subpaths]) {
366
- if (forms(directory).some((root) => within(root, keyFile))) refuse(directory);
367
- }
368
- for (const literal of systemRoots.literals) {
369
- if (forms(literal).includes(keyFile)) refuse(literal);
370
364
  }
371
365
  };
372
366
 
@@ -788,7 +782,7 @@ export default {
788
782
  assertSandboxSupported(ctx.environment, platform);
789
783
  const sandbox = normalizeSandboxTrust(ctx.environment?.sandbox);
790
784
  const isPublic = effectiveSandboxTrust(sandbox?.trust) === 'public';
791
- const keyFile = await sharedProviderKeyFile(ctx.environment, ctx.cwd);
785
+ const keyFile = await sharedProviderKeyFile(ctx.environment, ctx.cwd, platform);
792
786
  const provider = resolveProvider(ctx.environment);
793
787
  const model = seatModel;
794
788
  const thinking = thinkingFor(ctx.environment?.effort);
@@ -874,21 +868,6 @@ export default {
874
868
  });
875
869
  let proxy = null;
876
870
  try {
877
- // A public pi never holds the provider key: it talks to a loopback proxy
878
- // with a per-turn token, and the proxy, in this process, adds the key and
879
- // pins the model (the same shape as Goose and Qwen).
880
- if (isPublic) {
881
- proxy = await (ctx._startProviderProxy || startProviderProxy)({
882
- provider: { baseURL: provider.baseUrl },
883
- ...(keyFile ? { keyFile } : { keyMaterial: baseEnv[provider.apiKeyEnv] }),
884
- adapterLabel: 'pi',
885
- pinnedModel: model,
886
- });
887
- }
888
- await writeFile(join(agentDir, 'models.json'), `${JSON.stringify(buildModelsJson(
889
- proxy ? { ...provider, baseUrl: proxy.baseURL } : provider, model,
890
- ), null, 2)}\n`, { mode: 0o600 });
891
-
892
871
  const unavailableMcp = [];
893
872
  const mcpReadDirectories = [];
894
873
  const grantBrokers = [];
@@ -902,9 +881,25 @@ export default {
902
881
  grantBrokers,
903
882
  });
904
883
  if (unavailableMcp.length) throw publicMcpUnavailableError(unavailableMcp);
884
+ // Every refusal comes before the proxy opens the key file (F453): nothing
885
+ // touches a refused key file, this process included.
905
886
  if (keyFile && isPublic) {
906
887
  refuseKeyFileInJail(keyFile, [home, packageRoot, EXTENSION_CODE_ROOT, ...mcpReadDirectories]);
907
888
  }
889
+ // A public pi never holds the provider key: it talks to a loopback proxy
890
+ // with a per-turn token, and the proxy, in this process, adds the key and
891
+ // pins the model (the same shape as Goose and Qwen).
892
+ if (isPublic) {
893
+ proxy = await (ctx._startProviderProxy || startProviderProxy)({
894
+ provider: { baseURL: provider.baseUrl },
895
+ ...(keyFile ? { keyFile } : { keyMaterial: baseEnv[provider.apiKeyEnv] }),
896
+ adapterLabel: 'pi',
897
+ pinnedModel: model,
898
+ });
899
+ }
900
+ await writeFile(join(agentDir, 'models.json'), `${JSON.stringify(buildModelsJson(
901
+ proxy ? { ...provider, baseUrl: proxy.baseURL } : provider, model,
902
+ ), null, 2)}\n`, { mode: 0o600 });
908
903
  const childEnv = isPublic ? {
909
904
  // A scrubbed environment: nothing of the operator's crosses into the
910
905
  // jail, and the provider variable holds the proxy's token, not the key.
@@ -294,7 +294,7 @@ export default {
294
294
  if (!environment?.provider || !environment?.model) {
295
295
  throw new Error('Qwen requires environment.provider and environment.model');
296
296
  }
297
- return resolveProviderKeyFile(environment.provider, workspacePath, 'Qwen');
297
+ return resolveProviderKeyFile(environment.provider, workspacePath, 'Qwen', { environment });
298
298
  },
299
299
 
300
300
  async detect() {
@@ -0,0 +1,31 @@
1
+ // F457: what a quick-try run says when the harness it needs isn't on PATH, and
2
+ // the report it leaves first. The run exits before it ever checks in, so
3
+ // without the report the connect page waits for it forever.
4
+
5
+ import { NPM } from './cli-hint.js';
6
+
7
+ // Only harnesses whose install command we have run ourselves get one here.
8
+ const INSTALL = {
9
+ claude: { label: 'Claude Code', command: `${NPM} i -g @anthropic-ai/claude-code`, signIn: 'claude' },
10
+ codex: { label: 'Codex', command: `${NPM} i -g @openai/codex`, signIn: 'codex' },
11
+ };
12
+
13
+ /** One sentence on how to get the named harness, ending with "run this line again". */
14
+ export const missingHarnessHint = (name) => {
15
+ const known = INSTALL[name];
16
+ if (!known) return `Install ${name}, then run this line again.`;
17
+ return `Install ${known.label} (${known.command}), sign in once by running ${known.signIn}, then run this line again.`;
18
+ };
19
+
20
+ /**
21
+ * Tell the instance what this run looked for (a harness id, or null for none
22
+ * of the ones it probes). Best effort: an older instance without the route, or
23
+ * a failed call, must not hide the message the person needs in the terminal.
24
+ */
25
+ export const reportMissingHarness = async (client, harness) => {
26
+ try {
27
+ await client?.post?.('/api/agents/runtime/harness-missing', { harness });
28
+ } catch {
29
+ // The terminal message below is the answer either way.
30
+ }
31
+ };
@@ -1 +1,42 @@
1
+ import { resolveProviderKeyFile as resolveKeyFileShared } from '@commonlyai/seats/wire/provider-proxy';
2
+ import { effectiveSandboxTrust } from './environment.js';
3
+ import { bwrapReadRoots } from './sandbox/bwrap.js';
4
+ import { seatbeltSystemReadRoots } from './sandbox/seatbelt.js';
5
+
1
6
  export * from '@commonlyai/seats/wire/provider-proxy';
7
+
8
+ /**
9
+ * F453. What a sandboxed seat can read on this platform, as roots, or
10
+ * undefined for a spawn that runs in no sandbox. macOS: the Seatbelt
11
+ * baseline's read grants, read from the profile itself. Linux: bwrap's read
12
+ * binds, including the seat's declared read-outside and write-outside.
13
+ * `sandboxed` is the adapter's word on whether this spawn is confined; left
14
+ * out, a public seat is confined and any other is not.
15
+ */
16
+ export const sandboxReadableRoots = (environment, platform = process.platform, { sandboxed } = {}) => {
17
+ const confined = sandboxed ?? effectiveSandboxTrust(environment?.sandbox?.trust) === 'public';
18
+ if (!confined) return undefined;
19
+ if (platform === 'darwin') return seatbeltSystemReadRoots();
20
+ if (platform === 'linux') return bwrapReadRoots(environment);
21
+ return { subpaths: [], literals: [] };
22
+ };
23
+
24
+ /**
25
+ * The shared key-file validation, with the sandbox check every adapter gets:
26
+ * the proxy reads a confined seat's key file outside the sandbox, so a key
27
+ * file the sandbox can read is refused before the seat starts, and before
28
+ * anything opens the file. Adapters pass their environment; `seatDirectories`
29
+ * names stable directories the adapter itself gives the sandbox (a seat home),
30
+ * checked whenever the spawn is confined. Without options nothing changes.
31
+ */
32
+ export const resolveProviderKeyFile = (provider, workspacePath, adapterLabel, {
33
+ environment, platform, sandboxed, seatDirectories = [],
34
+ } = {}) => {
35
+ const roots = sandboxReadableRoots(environment, platform, { sandboxed });
36
+ return resolveKeyFileShared(provider, workspacePath, adapterLabel, {
37
+ readableRoots: roots && {
38
+ subpaths: [...roots.subpaths, ...seatDirectories.filter(Boolean)],
39
+ literals: roots.literals,
40
+ },
41
+ });
42
+ };
@@ -55,6 +55,23 @@ const DEFAULT_RO_BINDS = [
55
55
  '/lib64',
56
56
  ];
57
57
 
58
+ /**
59
+ * What a bwrap sandbox binds for reading, as roots (F453): the default binds
60
+ * plus the seat's declared read-outside and write-outside, tilde-expanded the
61
+ * way wrapArgvWithBwrap expands them. A caller keeping a secret out of the
62
+ * sandbox (a public seat's provider key file) checks against this rather than
63
+ * a copy of the bind list. Per-turn paths (workspace, state, adapter inputs)
64
+ * are the caller's.
65
+ */
66
+ export const bwrapReadRoots = (env) => {
67
+ const declared = (key) => (Array.isArray(env?.sandbox?.filesystem?.[key])
68
+ ? env.sandbox.filesystem[key].map(expandHome) : []);
69
+ return {
70
+ subpaths: [...new Set([...DEFAULT_RO_BINDS, ...declared('read-outside'), ...declared('write-outside')])],
71
+ literals: [],
72
+ };
73
+ };
74
+
58
75
  // `bwrap --version` only proves the binary is there. On Ubuntu 24.04 and later
59
76
  // AppArmor restricts unprivileged user namespaces, so bwrap is installed and
60
77
  // every sandbox it starts fails (`setting up uid map: Permission denied`,