@commonlyai/cli 0.1.326 → 0.1.328

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.326",
3
+ "version": "0.1.328",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -97,6 +97,7 @@ import {
97
97
  } from '../lib/default-environment.js';
98
98
  import { mergeGrantBrokers, withholdGrantBroker } from '../lib/grant-broker-guard.js';
99
99
  import { withPublicSeatMcpFlag } from '../lib/public-seat-mcp-flag.js';
100
+ import { UNCONFINED_TURN_REFUSAL, seatRunsUnconfined, unconfinedPodRefusalReason } from '../lib/unconfined-seat-guard.js';
100
101
  import {
101
102
  OUTSIDER_GRANT_MCP_UNCONFINED, outsiderGrantMcpRefusal, seatIsConfined, unshippedMcpEntries,
102
103
  } from '../lib/outsider-grant-mcp.js';
@@ -1096,10 +1097,10 @@ export const buildDefaultEnvironment = (adapterName) => {
1096
1097
  * work while the OS-level sandbox never engaged at all.
1097
1098
  *
1098
1099
  * Deny-by-default only means something if ABSENT is refused, so this is a hard
1099
- * error rather than a warning. If the pod's visibility cannot be determined
1100
- * (older server, network failure, permissions), attach proceeds — failing the
1101
- * attach on an unrelated fault would be its own footgun — but says so, because
1102
- * a silent skip is how the original hole stayed invisible.
1100
+ * error rather than a warning. A seat the adapters do not confine
1101
+ * (lib/unconfined-seat-guard.js `seatRunsUnconfined`) attaches only to a pod
1102
+ * confirmed private and invite-only; a pod whose visibility cannot be read
1103
+ * fails closed, and each turn checks again.
1103
1104
  * dsh is private-only, so it requires a successful visibility read and rejects
1104
1105
  * a public pod even without a sandbox declaration.
1105
1106
  */
@@ -1108,7 +1109,8 @@ export const assertSandboxDeclaredForPublicPod = async ({
1108
1109
  podId,
1109
1110
  environment,
1110
1111
  adapterName,
1111
- log = () => {},
1112
+ // Kept for callers; every outcome here is now a return or a refusal.
1113
+ log: _log = () => {},
1112
1114
  }) => {
1113
1115
  if (!podId || !client) return;
1114
1116
 
@@ -1125,7 +1127,9 @@ export const assertSandboxDeclaredForPublicPod = async ({
1125
1127
  if (pod?.publicRead || pod?.communityListed) {
1126
1128
  throw new Error('dsh supports private pods only; this pod is publicly readable');
1127
1129
  }
1128
- return;
1130
+ // dsh's confined shape stops here; an unconfined dsh runs as its owner and
1131
+ // meets the invite-only requirement below.
1132
+ if (!seatRunsUnconfined({ environment, adapterName })) return;
1129
1133
  }
1130
1134
 
1131
1135
  // A `workspace` seat lets the room read its start directory (TASK-294), so it
@@ -1153,41 +1157,45 @@ export const assertSandboxDeclaredForPublicPod = async ({
1153
1157
  );
1154
1158
  }
1155
1159
 
1156
- // Normalized FIRST: the predicate below reads a
1157
- // legacy `internal` record as the `public` it means, the same mapping the
1158
- // attach gate and both adapters use. Reading it raw refused a record that
1159
- // means public one call before the gate #1840 fixes — TASK-113 claims
1160
- // attach's inconsistent derivation is closed, and this path is attach's.
1161
- const sandbox = normalizeSandboxTrust(environment?.sandbox);
1162
- const mode = sandbox?.mode;
1163
- const trust = sandbox?.trust;
1164
- // An ENFORCED declaration is one the adapters act on: a public trust (whose
1165
- // mode they resolve per host at spawn) or an explicit non-'none' mode. This
1166
- // mirrors the daemon's predicate in lib/default-environment.js, so the shape
1167
- // the daemon writes for an unconfigured seat is one attach also accepts.
1168
- const declared = mode !== 'none'
1169
- && (trust === 'public' || typeof mode === 'string');
1170
- if (declared) return;
1160
+ // Confined means what the adapters enforce: a public trust (normalized, so a
1161
+ // legacy `internal` counts), or dsh's own confined shape. A `sandbox.mode`
1162
+ // with no trust is spawned bare by claude and codex, so it is unconfined here
1163
+ // and per turn alike (lib/unconfined-seat-guard.js).
1164
+ if (!seatRunsUnconfined({ environment, adapterName })) return;
1171
1165
 
1166
+ // No enforced sandbox: the agent runs as its owner, so the pod has to be
1167
+ // confirmed private, not merely not known to be public. A pod anyone can join
1168
+ // is refused as a public one is, and one whose visibility cannot be read
1169
+ // fails closed (lib/unconfined-seat-guard.js; each turn checks again).
1172
1170
  let pod = null;
1173
1171
  try {
1174
1172
  pod = await client.get(`/api/pods/${podId}`);
1175
1173
  } catch {
1176
- log(
1177
- 'warning: could not read pod visibility, so the public-pod sandbox check '
1178
- + 'was skipped. If this pod is public, attach with sandbox.trust=public.',
1174
+ throw new Error(
1175
+ 'This agent runs without a sandbox, so it would run with your own access, and this pod\'s '
1176
+ + 'visibility could not be read. An agent without a sandbox attaches only to a pod confirmed '
1177
+ + 'private and invite-only. Try again, or add "sandbox": { "trust": "public" } to its environment file.',
1179
1178
  );
1180
- return;
1181
1179
  }
1180
+ if (podIsConfirmedPrivate(pod)) return;
1182
1181
 
1183
1182
  const isPublic = Boolean(pod?.publicRead) || Boolean(pod?.communityListed);
1184
- if (!isPublic) return;
1183
+ if (!isPublic) {
1184
+ const label = pod?.name ? `"${pod.name}"` : podId;
1185
+ const why = pod?.joinPolicy === 'invite-only' ? 'did not report whether it is publicly readable' : 'is open to join';
1186
+ throw new Error(
1187
+ `${label} ${why}, and this agent runs without a sandbox, so anyone who joins could direct it with your `
1188
+ + 'own access to files, commands and logins. Make the pod invite-only (its owner sets "Who can join" '
1189
+ + 'to Invite-only in the pod\'s side panel in Commonly) and try again, or add '
1190
+ + '"sandbox": { "trust": "public" } to its environment file.',
1191
+ );
1192
+ }
1185
1193
 
1186
1194
  const label = pod?.name ? `"${pod.name}"` : podId;
1187
1195
  throw new Error(
1188
1196
  `${label} is publicly readable, so this agent would take instructions from `
1189
- + 'people you do not control — but its environment declares no sandbox, and '
1190
- + 'an undeclared sandbox means NO sandbox.\n\n'
1197
+ + 'people you do not control — but its environment declares no sandbox trust, and '
1198
+ + 'without one this agent runs with NO sandbox.\n\n'
1191
1199
  + 'Add a sandbox block to the environment file and retry:\n\n'
1192
1200
  + ' "sandbox": { "trust": "public" }\n\n'
1193
1201
  + 'That is the whole declaration: the adapters pick the enforced mode for '
@@ -2361,22 +2369,35 @@ export const performRun = ({
2361
2369
  && effortRefusedByDevice(inventory, desiredEnvironment.effort)
2362
2370
  ? { ...desiredEnvironment, effort: undefined } : desiredEnvironment;
2363
2371
  };
2364
- const placeTurn = async () => {
2365
- await refreshSeatEnvironment();
2366
- if (seatEnvironment?.sandbox?.trust !== 'workspace' && !codexUnconfined) {
2367
- return { environment: seatEnvironment, cwd: agentCwd, binding: sessionBinding };
2368
- }
2369
- let installations = null;
2370
- let readError = null;
2372
+ const readSeatPods = async () => {
2371
2373
  try {
2372
2374
  const identity = await client.get('/api/agents/runtime/installations', {}, {
2373
2375
  signal: AbortSignal.timeout(5000),
2374
2376
  });
2375
- installations = Array.isArray(identity?.installations) ? identity.installations : [];
2377
+ return { installations: Array.isArray(identity?.installations) ? identity.installations : [], readError: null };
2376
2378
  } catch (err) {
2377
- installations = null;
2378
- readError = err;
2379
+ return { installations: null, readError: err };
2380
+ }
2381
+ };
2382
+ const placeTurn = async () => {
2383
+ await refreshSeatEnvironment();
2384
+ if (seatEnvironment?.sandbox?.trust !== 'workspace' && !codexUnconfined) {
2385
+ const unchecked = { environment: seatEnvironment, cwd: agentCwd, binding: sessionBinding };
2386
+ if (!seatRunsUnconfined({ environment: seatEnvironment, adapterName: adapter.name })) return unchecked;
2387
+ // A seat with no sandbox runs as its owner, so each turn re-reads its
2388
+ // pods and runs only while all are confirmed private
2389
+ // (lib/unconfined-seat-guard.js). There is no confined fallback.
2390
+ const { installations, readError } = await readSeatPods();
2391
+ const reason = unconfinedPodRefusalReason(installations);
2392
+ if (reason !== lastPlacementReason) {
2393
+ log(reason
2394
+ ? `turns are refused, because ${reason}: ${UNCONFINED_TURN_REFUSAL}`
2395
+ : 'every pod is confirmed private again; turns run');
2396
+ lastPlacementReason = reason;
2397
+ }
2398
+ return reason ? { ...unchecked, reason, readError, unconfinedRefused: true } : unchecked;
2379
2399
  }
2400
+ const { installations, readError } = await readSeatPods();
2380
2401
  const placement = codexUnconfined
2381
2402
  ? unconfinedTurnPlacement({ environment: seatEnvironment, installations, cwd: agentCwd })
2382
2403
  : workspaceTurnPlacement({
@@ -2836,7 +2857,7 @@ export const performRun = ({
2836
2857
  // failed read is not: it throws, so the event stays unacked and comes back
2837
2858
  // through the spawn-retry backoff instead of being refused for good.
2838
2859
  if (placement.reason) {
2839
- const turnRefusal = hostSandboxRefusal({
2860
+ const turnRefusal = placement.unconfinedRefused ? UNCONFINED_TURN_REFUSAL : hostSandboxRefusal({
2840
2861
  environment: placement.environment,
2841
2862
  adapterName: adapter.name,
2842
2863
  hostUnconfined,
@@ -2859,7 +2880,7 @@ export const performRun = ({
2859
2880
  try {
2860
2881
  await client.post(
2861
2882
  `/api/agents/runtime/asks/${encodeURIComponent(event.payload.requestId)}/respond`,
2862
- { content: 'I can’t take this ask: this pod isn’t private, so I can’t run for it on my computer.' },
2883
+ { content: 'I can’t take this ask: a pod I’m in isn’t private and invite-only, so I can’t run on my owner’s computer right now.' },
2863
2884
  );
2864
2885
  } catch (err) {
2865
2886
  if (err?.status !== 409 || err?.body?.code !== 'already_responded') throw err;
@@ -2868,7 +2889,7 @@ export const performRun = ({
2868
2889
  return {
2869
2890
  outcome: 'no_action',
2870
2891
  refused: { reason: 'delivery-refused' },
2871
- reason: 'host-cannot-confine-turn',
2892
+ reason: placement.unconfinedRefused ? 'unconfined-pod-not-private' : 'host-cannot-confine-turn',
2872
2893
  };
2873
2894
  }
2874
2895
  }
@@ -114,19 +114,22 @@ const watchDaemonStatus = async () => {
114
114
  const seats = (loadDaemonState()?.seats || []).map((seat) => ({
115
115
  ...seat,
116
116
  // The supervisor stamps spawn time; the session store holds real turns.
117
- lastTurnAt: readSessionLastTurn(seat.agentName),
117
+ lastTurnAt: readSessionLastTurn(seat.recordKey || seat.agentName),
118
118
  }));
119
+ // Keyed by the local record, so two instances of one agent never read
120
+ // each other's log, last turn or pod (F427).
119
121
  const logTails = {};
120
122
  for (const seat of seats) {
121
- const tail = readLogTail(daemonSeatLogPath(seat.agentName), 3);
122
- logTails[seat.agentName] = tail ? tail.split('\n') : [];
123
+ const key = seat.recordKey || seat.agentName;
124
+ const tail = readLogTail(daemonSeatLogPath(key), 3);
125
+ logTails[key] = tail ? tail.split('\n') : [];
123
126
  }
124
127
  let states = null;
125
128
  let stateNote = '';
126
129
  if (!getToken(record.instanceUrl)) {
127
130
  stateNote = `Not logged in: showing local process state only. Run: commonly login --instance ${record.instanceUrl}`;
128
131
  } else {
129
- const podIds = [...new Set(seats.map((seat) => loadAgentToken(seat.agentName)?.podId).filter(Boolean))];
132
+ const podIds = [...new Set(seats.map((seat) => loadAgentToken(seat.recordKey || seat.agentName)?.podId).filter(Boolean))];
130
133
  try {
131
134
  states = await reachFor(podIds);
132
135
  } catch (error) {
@@ -746,12 +749,14 @@ Examples:
746
749
  // One child per agent, logging to its own file. The child is the
747
750
  // ordinary `commonly agent run <name>` — the daemon is its
748
751
  // supervisor, never its replacement (D6).
749
- spawnChild: (agentName) => {
750
- warnMissingSeatKey(agentName);
751
- const seatLog = daemonSeatLogPath(agentName);
752
+ // `recordKey` is the local record: `<name>`, or `<name>@<id>` for
753
+ // another instance, which `agent run` resolves the same way (F427).
754
+ spawnChild: (recordKey) => {
755
+ warnMissingSeatKey(recordKey);
756
+ const seatLog = daemonSeatLogPath(recordKey);
752
757
  const out = openSync(seatLog, 'a', 0o600);
753
758
  chmodSync(seatLog, 0o600);
754
- return spawn(process.execPath, [process.argv[1], 'agent', 'run', agentName], {
759
+ return spawn(process.execPath, [process.argv[1], 'agent', 'run', recordKey], {
755
760
  stdio: ['ignore', out, out],
756
761
  // Windows: never flash a console window per seat (no-op elsewhere).
757
762
  windowsHide: true,
@@ -776,7 +781,7 @@ Examples:
776
781
  updatedAt: new Date().toISOString(),
777
782
  seats: seats.map((seat) => ({
778
783
  ...seat,
779
- lastTurnAt: getLastTurn(seat.agentName) || seat.lastTurnAt,
784
+ lastTurnAt: getLastTurn(seat.recordKey || seat.agentName) || seat.lastTurnAt,
780
785
  })),
781
786
  }),
782
787
  });
@@ -26,6 +26,9 @@ const fixedLastError = (value) => {
26
26
  const seatState = (seat = {}) => ({
27
27
  agentName: seat.agentName,
28
28
  instanceId: seat.instanceId,
29
+ // The local record the seat runs from (`<name>` or `<name>@<id>`, F427):
30
+ // a file name, not a secret. Status reads its log and last turn by it.
31
+ recordKey: typeof seat.recordKey === 'string' ? seat.recordKey : null,
29
32
  state: seat.state,
30
33
  restarts: seat.restarts,
31
34
  adapter: seat.adapter || null,
@@ -59,6 +59,32 @@ export const backoffMs = (restarts) => Math.min(
59
59
 
60
60
  const identityKey = (agentName, instanceId) => `${agentName} ${instanceId || 'default'}`;
61
61
 
62
+ // An instance id becomes part of a local file name.
63
+ const INSTANCE_ID_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
64
+ const isDefaultInstance = (instanceId) => String(instanceId || 'default').toLowerCase() === 'default';
65
+ // Instance ids compare case-insensitively, as `agent run` and the server do.
66
+ const sameInstance = (a, b) => String(a || 'default').toLowerCase() === String(b || 'default').toLowerCase();
67
+
68
+ /**
69
+ * The local token record a seat lives in, as `agent run <key>` resolves it
70
+ * (F306, F427): the default instance is `<name>`, another is `<name>@<id>`,
71
+ * except a key an older CLI saved for that instance under the bare name, which
72
+ * is used where it is. So a second instance placed on a computer that already
73
+ * runs the default gets its own record, and neither overwrites the other.
74
+ * Null for an instance id that can't be a file name.
75
+ */
76
+ export const recordKeyFor = (row, loadToken) => {
77
+ const { agentName } = row;
78
+ const instanceId = row.instanceId || 'default';
79
+ if (isDefaultInstance(instanceId)) return agentName;
80
+ if (!INSTANCE_ID_PATTERN.test(instanceId)) return null;
81
+ const scoped = `${agentName}@${instanceId}`;
82
+ if (loadToken(scoped)) return scoped;
83
+ const legacy = loadToken(agentName);
84
+ if (legacy && sameInstance(legacy.instanceId, instanceId)) return agentName;
85
+ return scoped;
86
+ };
87
+
62
88
  export const createDaemonSupervisor = ({
63
89
  record,
64
90
  client,
@@ -104,7 +130,10 @@ export const createDaemonSupervisor = ({
104
130
 
105
131
  const persist = () => {
106
132
  try {
107
- persistState(agentStates());
133
+ // The local record key too, for this host's own readouts (the last turn
134
+ // is kept per record); the heartbeat reports agentStates() without it.
135
+ const keys = Array.from(seats.values()).map((s) => s.recordKey || s.agentName);
136
+ persistState(agentStates().map((state, i) => ({ ...state, recordKey: keys[i] })));
108
137
  } catch (error) {
109
138
  // A diagnostic state file must never take the daemon down. The log is
110
139
  // still useful, and the next state transition retries the write.
@@ -139,13 +168,13 @@ export const createDaemonSupervisor = ({
139
168
  return;
140
169
  }
141
170
  recentStarts.push(at);
142
- seat.child = spawnChild(seat.agentName);
171
+ seat.child = spawnChild(seat.recordKey || seat.agentName);
143
172
  seat.state = 'running';
144
173
  seat.pid = Number.isInteger(seat.child?.pid) ? seat.child.pid : null;
145
174
  seat.lastTurnAt = new Date().toISOString();
146
175
  seat.lastError = null;
147
176
  persist();
148
- log(`[${seat.agentName}] supervising (restarts so far: ${seat.restarts})`);
177
+ log(`[${seat.recordKey || seat.agentName}] supervising (restarts so far: ${seat.restarts})`);
149
178
  seat.child.on('exit', (code) => {
150
179
  seat.child = null;
151
180
  seat.pid = null;
@@ -158,7 +187,7 @@ export const createDaemonSupervisor = ({
158
187
  seat.lastError = code === 0 ? null : `child exited with code ${code}`;
159
188
  seat.restarts += 1;
160
189
  const delay = backoffMs(seat.restarts - 1);
161
- log(`[${seat.agentName}] exited (code ${code}) — respawn in ${Math.round(delay / 1000)}s`);
190
+ log(`[${seat.recordKey || seat.agentName}] exited (code ${code}) — respawn in ${Math.round(delay / 1000)}s`);
162
191
  seat.backoffTimer = setTimeoutFn(() => {
163
192
  seat.backoffTimer = null;
164
193
  startChild(seat);
@@ -178,7 +207,7 @@ export const createDaemonSupervisor = ({
178
207
  seat.backoffTimer = null;
179
208
  }
180
209
  if (seat.child) {
181
- log(`[${seat.agentName}] no longer assigned here — stopping`);
210
+ log(`[${seat.recordKey || seat.agentName}] no longer assigned here — stopping`);
182
211
  seat.child.kill('SIGTERM');
183
212
  } else {
184
213
  seat.state = 'stopped';
@@ -236,7 +265,7 @@ export const createDaemonSupervisor = ({
236
265
  // that refusal is answered with rotate:true — loudly.
237
266
  // Returns 'ready' | 'changed' (record updated — the seat must restart to
238
267
  // load it) | false.
239
- const ensureToken = async (row) => {
268
+ const ensureToken = async (row, recordKey) => {
240
269
  // One derive for this seat, so the broker refusal cannot be applied at three
241
270
  // of four sites: `seatBaseline` is where an environment becomes the one the
242
271
  // seat RUNS under, and `withholdGrantBroker` asks the same question the
@@ -253,18 +282,19 @@ export const createDaemonSupervisor = ({
253
282
  {
254
283
  instanceUrl: record.instanceUrl,
255
284
  onRefuse: (refusal, names) => log(
256
- `[${row.agentName}] ${refusal.code} (${refusal.reason}) — withholding ${names.join(', ')}: ${refusal.detail}`,
285
+ `[${recordKey}] ${refusal.code} (${refusal.reason}) — withholding ${names.join(', ')}: ${refusal.detail}`,
257
286
  ),
258
287
  },
259
288
  );
260
289
 
261
- const existing = loadToken(row.agentName);
290
+ const existing = loadToken(recordKey);
262
291
  if (existing) {
263
- // Local records are still keyed by agent name. Never rotate or launch
264
- // another instance through a same-name record: that would overwrite a
265
- // different seat's bearer until instance-scoped local records land.
266
- if ((existing.instanceId || 'default') !== (row.instanceId || 'default')) {
267
- log(`[${row.agentName}] local token belongs to instance '${existing.instanceId || 'default'}'; refusing '${row.instanceId || 'default'}'`);
292
+ // recordKeyFor gives each instance its own record; a record that still
293
+ // names another instance (written by hand, or the bare name holding a
294
+ // non-default instance when the default is placed) is never rotated or
295
+ // launched as this one, which would overwrite that seat's bearer.
296
+ if (!sameInstance(existing.instanceId, row.instanceId)) {
297
+ log(`[${recordKey}] local token belongs to instance '${existing.instanceId || 'default'}'; refusing '${row.instanceId || 'default'}'`);
268
298
  return false;
269
299
  }
270
300
  // A human owner can request a fresh key from Settings after revocation.
@@ -279,15 +309,15 @@ export const createDaemonSupervisor = ({
279
309
  agentName: row.agentName, instanceId: row.instanceId, rotate: true,
280
310
  });
281
311
  if (!minted?.token) throw new Error('mint returned no token');
282
- saveToken(row.agentName, {
312
+ saveToken(recordKey, {
283
313
  ...existing,
284
314
  runtimeToken: minted.token,
285
315
  reconnectRequestAppliedAt: row.reconnectRequestedAt,
286
316
  });
287
- log(`[${row.agentName}] owner-requested key rotation applied; restarting the seat`);
317
+ log(`[${recordKey}] owner-requested key rotation applied; restarting the seat`);
288
318
  return 'changed';
289
319
  } catch (error) {
290
- log(`[${row.agentName}] owner-requested key rotation failed: ${error.message}`);
320
+ log(`[${recordKey}] owner-requested key rotation failed: ${error.message}`);
291
321
  return false;
292
322
  }
293
323
  }
@@ -311,7 +341,7 @@ export const createDaemonSupervisor = ({
311
341
  // versa). Keep the existing child/token untouched until the exact
312
342
  // requested adapter is detected locally.
313
343
  if (detectedAdapter !== declaredAdapter) {
314
- log(`[${row.agentName}] requested adapter '${declaredAdapter}' is not available on this machine — keeping the current seat`);
344
+ log(`[${recordKey}] requested adapter '${declaredAdapter}' is not available on this machine — keeping the current seat`);
315
345
  return false;
316
346
  }
317
347
  nextAdapter = declaredAdapter;
@@ -324,7 +354,7 @@ export const createDaemonSupervisor = ({
324
354
  // adapter that needs a server binding (opencode) refuses to run under
325
355
  // the server's new one, so starting it would only crash-loop. The
326
356
  // owner sets the adapter back, or moves the provider to one it speaks.
327
- log(`[${row.agentName}] host-local provider: ${providerRefused} — keeping the current record and not starting it; `
357
+ log(`[${recordKey}] host-local provider: ${providerRefused} — keeping the current record and not starting it; `
328
358
  + `set the adapter back to ${existing.adapter || 'the previous one'} in Commonly, or change the provider`);
329
359
  return false;
330
360
  }
@@ -363,7 +393,7 @@ export const createDaemonSupervisor = ({
363
393
  if (adapterChanged
364
394
  || !isDeepStrictEqual(existing.environment || null, nextEnvironment)
365
395
  || (workspacePath && existing.workspacePath !== workspacePath)) {
366
- saveToken(row.agentName, nextRecord);
396
+ saveToken(recordKey, nextRecord);
367
397
  log('runtime config changed — restarting the seat to load it');
368
398
  return 'changed';
369
399
  }
@@ -374,7 +404,7 @@ export const createDaemonSupervisor = ({
374
404
  const nextEnvironment = derive(existing.environment, nextAdapter, {
375
405
  sandbox: !existing.environment,
376
406
  });
377
- saveToken(row.agentName, {
407
+ saveToken(recordKey, {
378
408
  ...existing,
379
409
  adapter: nextAdapter,
380
410
  ...(nextEnvironment ? { environment: nextEnvironment } : {}),
@@ -394,7 +424,7 @@ export const createDaemonSupervisor = ({
394
424
  sandbox: !existing.environment,
395
425
  });
396
426
  if (!isDeepStrictEqual(existing.environment || null, nextEnvironment || null)) {
397
- saveToken(row.agentName, { ...existing, environment: nextEnvironment });
427
+ saveToken(recordKey, { ...existing, environment: nextEnvironment });
398
428
  log('record predates the commonly MCP baseline — restarting the seat to load it');
399
429
  return 'changed';
400
430
  }
@@ -409,7 +439,7 @@ export const createDaemonSupervisor = ({
409
439
  if (requestedAdapter) {
410
440
  adapter = await resolveAdapter(row.runtime || null);
411
441
  if (adapter !== requestedAdapter) {
412
- log(`[${row.agentName}] requested adapter '${requestedAdapter}' is not available on this machine — skipping token mint`);
442
+ log(`[${recordKey}] requested adapter '${requestedAdapter}' is not available on this machine — skipping token mint`);
413
443
  return false;
414
444
  }
415
445
  }
@@ -421,25 +451,25 @@ export const createDaemonSupervisor = ({
421
451
  minted = await client.post('/api/agent-binding/runtime-token', body);
422
452
  } catch (error) {
423
453
  if (error?.status === 409 && error?.body?.code === 'token_exists') {
424
- log(`[${row.agentName}] a runtime token exists elsewhere — rotating it to this machine (the old token stops working)`);
454
+ log(`[${recordKey}] a runtime token exists elsewhere — rotating it to this machine (the old token stops working)`);
425
455
  try {
426
456
  minted = await client.post('/api/agent-binding/runtime-token', { ...body, rotate: true });
427
457
  } catch (rotateError) {
428
- log(`[${row.agentName}] token rotation failed: ${rotateError.message}`);
458
+ log(`[${recordKey}] token rotation failed: ${rotateError.message}`);
429
459
  return false;
430
460
  }
431
461
  } else {
432
- log(`[${row.agentName}] token mint failed: ${error.message}`);
462
+ log(`[${recordKey}] token mint failed: ${error.message}`);
433
463
  return false;
434
464
  }
435
465
  }
436
466
  if (!minted?.token) {
437
- log(`[${row.agentName}] mint returned no token — skipping`);
467
+ log(`[${recordKey}] mint returned no token — skipping`);
438
468
  return false;
439
469
  }
440
470
  if (!adapter) adapter = await resolveAdapter(row.runtime || null);
441
471
  if (!adapter) {
442
- log(`[${row.agentName}] no usable CLI adapter on this machine — install claude, codex, opencode, qwen, or dsh, or attach manually`);
472
+ log(`[${recordKey}] no usable CLI adapter on this machine — install claude, codex, opencode, qwen, or dsh, or attach manually`);
443
473
  return false;
444
474
  }
445
475
  const environment = environmentFor(row);
@@ -453,7 +483,7 @@ export const createDaemonSupervisor = ({
453
483
  adapter,
454
484
  { sandbox: true },
455
485
  );
456
- saveToken(row.agentName, {
486
+ saveToken(recordKey, {
457
487
  agentName: row.agentName,
458
488
  instanceId: row.instanceId,
459
489
  runtimeToken: minted.token,
@@ -467,7 +497,7 @@ export const createDaemonSupervisor = ({
467
497
  return workspacePath ? { workspacePath } : {};
468
498
  })() : {}),
469
499
  });
470
- log(`[${row.agentName}] provisioned runtime token (adapter: ${adapter}${environment?.value?.model ? `, model: ${environment.value.model}` : ''})`);
500
+ log(`[${recordKey}] provisioned runtime token (adapter: ${adapter}${environment?.value?.model ? `, model: ${environment.value.model}` : ''})`);
471
501
  return 'ready';
472
502
  };
473
503
 
@@ -527,8 +557,14 @@ export const createDaemonSupervisor = ({
527
557
  seats.set(key, seat);
528
558
  }
529
559
  seat.desired = true;
560
+ const recordKey = recordKeyFor(row, loadToken);
561
+ if (!recordKey) {
562
+ log(`[${row.agentName}] instance id '${row.instanceId}' is not a plain id (letters, digits, '.', '_' or '-'); not starting it`);
563
+ continue;
564
+ }
565
+ seat.recordKey = recordKey;
530
566
  // eslint-disable-next-line no-await-in-loop
531
- const ready = await ensureToken(row);
567
+ const ready = await ensureToken(row, recordKey);
532
568
  // Report what the seat actually RUNS, which is the record: `agent run`
533
569
  // reads it once at boot, and ensureToken above may have just rewritten it
534
570
  // (a mint, or a config change). Reading it AFTER ensureToken is the point
@@ -543,7 +579,7 @@ export const createDaemonSupervisor = ({
543
579
  // the TASK-065 measurement). ensureToken also REFUSES a change it cannot
544
580
  // apply — a requested adapter this machine does not have — so the record
545
581
  // is the honest answer there too: it names the adapter that kept running.
546
- const current = loadToken(row.agentName);
582
+ const current = loadToken(recordKey);
547
583
  seat.adapter = current ? (current.adapter || null) : (row.runtime?.adapter || null);
548
584
  seat.model = current ? (current.environment?.model || null) : (row.runtime?.model || null);
549
585
  seat.effort = current ? (current.environment?.effort || null) : (row.runtime?.effort || null);
@@ -82,7 +82,7 @@ const agentBlock = (seat, { now, width, color, logTail, states }) => {
82
82
  const dim = (text) => (color ? `${ANSI.dim}${text}${ANSI.reset}` : text);
83
83
  const bold = (text) => (color ? `${ANSI.bold}${text}${ANSI.reset}` : text);
84
84
  const lines = [
85
- `${bold(clip(seat.agentName || 'unknown', width))} ${agentStateLabel(seat, states)} last turn ${relative(seat.lastTurnAt, now)}`,
85
+ `${bold(clip(seat.recordKey || seat.agentName || 'unknown', width))} ${agentStateLabel(seat, states)} last turn ${relative(seat.lastTurnAt, now)}`,
86
86
  ];
87
87
  if (seat.lastError) lines.push(clip(` error: ${seat.lastError}`, width));
88
88
  for (const line of logTail || []) lines.push(dim(` ${safeLogLine(line, Math.max(10, width - 2))}`));
@@ -90,7 +90,7 @@ const agentBlock = (seat, { now, width, color, logTail, states }) => {
90
90
  };
91
91
 
92
92
  // Inputs: `machine` { name, status, lastSeenAt }, `seats` (from the daemon state
93
- // file), `logTails` { [agentName]: string[] }, `states` (Map from
93
+ // file), `logTails` { [recordKey || agentName]: string[] }, `states` (Map from
94
94
  // loadReachByAgent, or null), `stateNote` (why states is null), `now` (ms),
95
95
  // `width` (columns).
96
96
  export const renderDaemonWatch = ({
@@ -108,7 +108,7 @@ export const renderDaemonWatch = ({
108
108
  return out.join('\n');
109
109
  }
110
110
  for (const seat of seats) {
111
- out.push(...agentBlock(seat, { now, width, color, logTail: logTails[seat.agentName] || [], states }));
111
+ out.push(...agentBlock(seat, { now, width, color, logTail: logTails[seat.recordKey || seat.agentName] || [], states }));
112
112
  out.push('');
113
113
  }
114
114
  return out.join('\n').replace(/\n+$/, '');
@@ -166,27 +166,32 @@ export const withDefaultMcpServer = (environment, adapterName) => {
166
166
  * are the same thing to the adapter, and this is the path that decides what an
167
167
  * undeclared sandbox means.
168
168
  */
169
+ /**
170
+ * Whether an environment declares a sandbox the adapters ENFORCE: a public or
171
+ * workspace trust (whose mode they resolve, and refuse to spawn without, every
172
+ * adapter but claude refusing `workspace` outright, TASK-294) or an explicit
173
+ * non-'none' mode. `mode: 'none'`, an empty block and a missing one are all the
174
+ * same thing to a spawn: no confinement.
175
+ *
176
+ * Normalized first (Wren 71719): a legacy `internal` means `public` here as it
177
+ * does to the attach gate and the adapters.
178
+ */
179
+ export const declaresEnforcedSandbox = (environment) => {
180
+ const sandbox = normalizeSandboxTrust(environment?.sandbox);
181
+ return sandbox !== null && typeof sandbox === 'object'
182
+ && sandbox.mode !== 'none'
183
+ && (sandbox.trust === 'public' || sandbox.trust === 'workspace'
184
+ || typeof sandbox.mode === 'string');
185
+ };
186
+
169
187
  export const withDefaultSandbox = (environment) => {
170
188
  if (environment !== null && environment !== undefined
171
189
  && (typeof environment !== 'object' || Array.isArray(environment))) {
172
190
  return environment;
173
191
  }
174
- // Normalized first (Wren 71719): `assertSandboxDeclaredForPublicPod`'s own
175
- // comment says this predicate mirrors it, and a legacy `internal` record
176
- // means `public` to both. Read raw, this one replaced a record the attach
177
- // gate accepts — benign (same effective trust) but not a mirror, and the
178
- // comment would be false. The ORIGINAL block is what gets returned below.
179
- const sandbox = normalizeSandboxTrust(environment?.sandbox);
180
- // An ENFORCED declaration is one the adapters act on: a public or workspace
181
- // trust (whose mode they resolve, and refuse to spawn without — every adapter
182
- // but claude refuses `workspace` outright, TASK-294) or an explicit non-'none'
183
- // mode. `mode: 'none'`, an empty block and a missing one are all the same
184
- // thing to a spawn — no confinement — so all three are replaced here.
185
- const enforced = sandbox !== null && typeof sandbox === 'object'
186
- && sandbox.mode !== 'none'
187
- && (sandbox.trust === 'public' || sandbox.trust === 'workspace'
188
- || typeof sandbox.mode === 'string');
189
- if (enforced) return environment;
192
+ // `mode: 'none'`, an empty block and a missing one are replaced; the ORIGINAL
193
+ // block is what is returned when it is enforced.
194
+ if (declaresEnforcedSandbox(environment)) return environment;
190
195
  return { ...(environment || {}), sandbox: defaultSeatSandbox() };
191
196
  };
192
197
 
@@ -0,0 +1,94 @@
1
+ /**
2
+ * A seat with no sandbox answers only in pods confirmed private.
3
+ *
4
+ * An agent the adapters do not confine runs as its owner: their files, their
5
+ * git and GitHub login, their shell. Anyone who can post in its pod can direct
6
+ * it. Attach already refused a publicly readable pod, but not one anyone can
7
+ * join, and nothing looked again once it ran, so a pod made joinable later
8
+ * handed that access to whoever joined.
9
+ *
10
+ * So attach requires such a seat's pod to be confirmed private (publicRead and
11
+ * communityListed reported false, joinPolicy invite-only:
12
+ * workspace-trust.js `podIsConfirmedPrivate`), and before every turn the seat
13
+ * re-reads its pods (GET /installations) and refuses the turn unless all of
14
+ * them still are. There is no confined fallback: the seat's record was never
15
+ * written for one, so a pod that is not private is a refused turn, and a read
16
+ * that fails defers it. The Windows Codex opt-in keeps its own placement
17
+ * (`unconfinedTurnPlacement`); this covers every other unconfined seat.
18
+ *
19
+ * "Confined" is what the adapters enforce, not what the file declares: a public
20
+ * or workspace trust, or a shape one adapter enforces with no trust (claude's
21
+ * `bwrap` mode, dsh's `isConfinedDsh` shape). Any other `sandbox.mode` with no
22
+ * trust is spawned bare (claude, codex) or refused at spawn, so it is
23
+ * unconfined here, and `mode: 'none'` always is.
24
+ *
25
+ * A legacy pod with no joinPolicy is reported 'open', and that is not only a
26
+ * default: an agent may self-install into a pod an agent created unless it is
27
+ * invite-only, so a missing value is not confirmed private.
28
+ *
29
+ * The test-only `stub` adapter runs nothing and is not checked.
30
+ */
31
+ import { normalizeSandboxTrust } from './environment.js';
32
+ import { podIsConfirmedPrivate } from './workspace-trust.js';
33
+
34
+ export const UNCONFINED_UNCHECKED_ADAPTERS = new Set(['stub']);
35
+
36
+ // adapters/dsh.js isConfinedDsh's accepted shape, copied so this module stays
37
+ // free of adapter imports; a test holds the two equal.
38
+ const isConfinedDshShape = (sandbox) => {
39
+ if (!sandbox || typeof sandbox !== 'object' || sandbox.trust !== undefined) return false;
40
+ const { mode, network, ...rest } = sandbox;
41
+ return mode === 'workspace' && network?.policy === 'restricted'
42
+ && Object.keys(network).length === 1 && Object.keys(rest).length === 0;
43
+ };
44
+
45
+ // Confinement an adapter applies with no trust: claude wraps any `bwrap` mode
46
+ // (adapters/claude.js), and dsh enforces its one shape. codex, opencode and the
47
+ // rest apply a mode only under a public or workspace trust.
48
+ const ADAPTER_OWN_CONFINEMENT = {
49
+ claude: (sandbox) => sandbox?.mode === 'bwrap',
50
+ dsh: isConfinedDshShape,
51
+ };
52
+
53
+ export const seatRunsUnconfined = ({ environment, adapterName }) => {
54
+ if (UNCONFINED_UNCHECKED_ADAPTERS.has(adapterName)) return false;
55
+ const sandbox = normalizeSandboxTrust(environment?.sandbox);
56
+ // An explicit 'none' is no sandbox whatever the trust says.
57
+ if (sandbox?.mode === 'none') return true;
58
+ if (sandbox?.trust === 'public' || sandbox?.trust === 'workspace') return false;
59
+ return !ADAPTER_OWN_CONFINEMENT[adapterName]?.(sandbox);
60
+ };
61
+
62
+ export const UNCONFINED_TURN_REFUSAL = 'This agent runs without a sandbox, with your own access to files, '
63
+ + 'commands and logins, so it answers only while every pod it is in is private and invite-only. '
64
+ + 'To fix it, the pod\'s owner opens it in Commonly and sets "Who can join" to Invite-only in its side '
65
+ + 'panel (and makes it private if it is public or listed in Community), or you remove this agent from that pod.';
66
+
67
+ const MAX_PODS_NAMED = 3;
68
+
69
+ const describePod = (pod) => {
70
+ const label = pod?.podName ? `"${pod.podName}" (${pod.podId})` : `pod ${pod?.podId || '(no id)'}`;
71
+ if (typeof pod?.publicRead !== 'boolean' || typeof pod?.communityListed !== 'boolean') {
72
+ return `${label} did not report whether it is private`;
73
+ }
74
+ if (pod.publicRead || pod.communityListed) return `${label} is public or listed in Community`;
75
+ return `${label} is open to join`;
76
+ };
77
+
78
+ /** Null when every pod is confirmed private, otherwise why the turn is refused, naming the pods. */
79
+ export const unconfinedPodRefusalReason = (installations) => {
80
+ if (installations === null) return 'its pods could not be read';
81
+ if (!Array.isArray(installations) || installations.length === 0) return 'the server listed no pods for it';
82
+ const seen = new Set();
83
+ const notPrivate = installations.filter((pod) => {
84
+ if (podIsConfirmedPrivate(pod)) return false;
85
+ const key = String(pod?.podId || '');
86
+ if (seen.has(key)) return false;
87
+ seen.add(key);
88
+ return true;
89
+ });
90
+ if (!notPrivate.length) return null;
91
+ const named = notPrivate.slice(0, MAX_PODS_NAMED).map(describePod).join('; ');
92
+ const more = notPrivate.length - MAX_PODS_NAMED;
93
+ return more > 0 ? `${named}; and ${more} more` : named;
94
+ };