@commonlyai/cli 0.1.317 → 0.1.319

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.317",
3
+ "version": "0.1.319",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -197,6 +197,51 @@ export const loadAgentToken = (name) => {
197
197
  }
198
198
  };
199
199
 
200
+ // ── Instances (F306) ─────────────────────────────────────────────────────────
201
+ // One agent can have more than one instance (same name, another instanceId),
202
+ // each with its own key. The default instance keeps `<name>.json`; another
203
+ // is `<name>@<instanceId>.json`, so its key never overwrites the default's.
204
+ const INSTANCE_ID_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
205
+ const isDefaultInstanceId = (instanceId) => String(instanceId || 'default').toLowerCase() === 'default';
206
+
207
+ export const seatKey = (agentName, instanceId) => (
208
+ isDefaultInstanceId(instanceId) ? agentName : `${agentName}@${instanceId}`
209
+ );
210
+
211
+ const runCommandFor = (agentName, instanceId) => (
212
+ `commonly agent run ${agentName}${isDefaultInstanceId(instanceId) ? '' : ` --instance-id ${instanceId}`}`
213
+ );
214
+
215
+ /**
216
+ * The instance `run <name>` was asked to start: --instance-id, or the one a
217
+ * seat key (`nova@priya-nova`, the token file's name) carries. Null when
218
+ * neither names one: that run behaves as it always has, keyed by the bare name
219
+ * whatever instance its key is for (a persona's BYO install is a non-default
220
+ * instance, and its page command names none).
221
+ * Throws on an id that is not a plain id, since it becomes part of a file name.
222
+ */
223
+ export const parseRunInstanceId = (flag, name) => {
224
+ const at = String(name).indexOf('@');
225
+ const fromName = at >= 0 ? String(name).slice(at + 1) : null;
226
+ if (flag !== undefined && fromName !== null && flag !== fromName) {
227
+ throw new Error(`'${name}' already names instance ${fromName}, so --instance-id ${flag} does not apply`);
228
+ }
229
+ const instanceId = flag !== undefined ? flag : fromName;
230
+ if (instanceId === null) return null;
231
+ if (!INSTANCE_ID_PATTERN.test(instanceId)) {
232
+ throw new Error(`--instance-id takes the instance's id (letters, digits, '.', '_' or '-'), not '${instanceId}'`);
233
+ }
234
+ return instanceId;
235
+ };
236
+
237
+ /** A key for one instance never runs as another: say which command runs it. */
238
+ export const runInstanceRefusal = ({ record, instanceId }) => {
239
+ const keyInstance = record?.instanceId || 'default';
240
+ if (String(keyInstance).toLowerCase() === String(instanceId || 'default').toLowerCase()) return null;
241
+ return `this key is for instance ${keyInstance} of '${record.agentName}', not instance ${instanceId || 'default'}. `
242
+ + `To run it: ${runCommandFor(record.agentName, keyInstance)}`;
243
+ };
244
+
200
245
  export const deleteAgentToken = (name) => {
201
246
  const file = tokenFile(name);
202
247
  if (existsSync(file)) rmSync(file);
@@ -1983,6 +2028,10 @@ export const performRun = ({
1983
2028
  agentName,
1984
2029
  displayName = null,
1985
2030
  instanceId = 'default',
2031
+ // F306: the token file's key, which names this seat's local state (sessions,
2032
+ // handled events, notices, scratch folder). A second instance's is
2033
+ // `<name>@<instanceId>`; every other seat's is its bare name, as before.
2034
+ localKey = null,
1986
2035
  podId = null,
1987
2036
  environment = null,
1988
2037
  // D245: the user's own Windows opt-in for this run; reaches the adapter's
@@ -2058,6 +2107,7 @@ export const performRun = ({
2058
2107
  pollLivenessCheckMs,
2059
2108
  onPollStalled,
2060
2109
  }) => {
2110
+ const stateKey = localKey || agentName;
2061
2111
  const supervising = superviseRuns ?? superviseRunsByDefault(adapter?.name);
2062
2112
  reportRuntime = reportRuntime && WALKED_HARNESSES.includes(adapter?.name);
2063
2113
  {
@@ -2250,7 +2300,7 @@ export const performRun = ({
2250
2300
  // as binary-not-found — so we ensure it up front to avoid the confusing
2251
2301
  // diagnostic. ADR-008: when an environment spec was attached, the resolved
2252
2302
  // workspace path replaces the /tmp default.
2253
- const scratchCwd = join(tmpdir(), 'commonly-agents', agentName);
2303
+ const scratchCwd = join(tmpdir(), 'commonly-agents', stateKey);
2254
2304
  const agentCwd = workspacePath || scratchCwd;
2255
2305
  if (!existsSync(agentCwd)) mkdirSync(agentCwd, { recursive: true });
2256
2306
  // TASK-294: a pod can turn public after attach, so a workspace seat re-reads
@@ -2604,7 +2654,7 @@ export const performRun = ({
2604
2654
  // again on every resume (measured 2026-11-05 on codex 0.162.1 and claude
2605
2655
  // 2.1.318), so one refusal would refuse every later turn in this pod. The
2606
2656
  // next turn starts fresh; memory reaches it through the adapter's preamble.
2607
- if (isContentRefusal(error) && turn.resumedSession) clearSession(agentName, args.eventPodId);
2657
+ if (isContentRefusal(error) && turn.resumedSession) clearSession(stateKey, args.eventPodId);
2608
2658
  throw error;
2609
2659
  }
2610
2660
  };
@@ -2626,7 +2676,7 @@ export const performRun = ({
2626
2676
  const cliAgentName = (readSavedControls && !environment) || standaloneMachineRun ? agentName : null;
2627
2677
  const key = `model-unavailable:${failure.model || 'unknown'}${cliAgentName ? ':agent-config' : ''}`;
2628
2678
  try {
2629
- if (!noticeDue(agentName, key, MODEL_UNAVAILABLE_HINT_WINDOW_MS)) return;
2679
+ if (!noticeDue(stateKey, key, MODEL_UNAVAILABLE_HINT_WINDOW_MS)) return;
2630
2680
  const delivery = await deliverTurnNotice({
2631
2681
  client,
2632
2682
  podId: hintPodId,
@@ -2636,7 +2686,7 @@ export const performRun = ({
2636
2686
  log,
2637
2687
  });
2638
2688
  if (!delivery.skipped && !delivery.refused) {
2639
- recordNotice(agentName, key);
2689
+ recordNotice(stateKey, key);
2640
2690
  log(`model unavailable hint posted (${failure.model || 'model not named'})`);
2641
2691
  }
2642
2692
  } catch (noticeError) {
@@ -2662,7 +2712,7 @@ export const performRun = ({
2662
2712
  const key = `cant-answer:${notice.cause}:${waitingPod}`;
2663
2713
  try {
2664
2714
  // eslint-disable-next-line no-continue
2665
- if (!noticeDue(agentName, key, CANT_ANSWER_NOTICE_WINDOW_MS)) continue;
2715
+ if (!noticeDue(stateKey, key, CANT_ANSWER_NOTICE_WINDOW_MS)) continue;
2666
2716
  // eslint-disable-next-line no-await-in-loop
2667
2717
  const delivery = await deliverChatReply({
2668
2718
  client,
@@ -2677,7 +2727,7 @@ export const performRun = ({
2677
2727
  log(`[inbox.batch] pod ${waitingPod} was not told why this agent can't answer: `
2678
2728
  + `${delivery.reason || 'the notice was not posted'}`);
2679
2729
  } else {
2680
- recordNotice(agentName, key);
2730
+ recordNotice(stateKey, key);
2681
2731
  log(`[inbox.batch] told pod ${waitingPod} why this agent can't answer (${notice.cause})`);
2682
2732
  }
2683
2733
  } catch (noticeError) {
@@ -2814,8 +2864,8 @@ export const performRun = ({
2814
2864
  // TASK-440: a cold, large session starts fresh at wake instead of being
2815
2865
  // resumed. The restart note leads the prompt; memory still reaches the
2816
2866
  // fresh session through the adapter's preamble.
2817
- const sessionEntry = getSessionEntry(agentName, eventPodId, { binding: placement.binding });
2818
- let sessionId = getSession(agentName, eventPodId, { binding: placement.binding });
2867
+ const sessionEntry = getSessionEntry(stateKey, eventPodId, { binding: placement.binding });
2868
+ let sessionId = getSession(stateKey, eventPodId, { binding: placement.binding });
2819
2869
  let recycleBriefing = null;
2820
2870
  if (sessionId && shouldStartFreshSession({
2821
2871
  lastTurn: sessionEntry?.lastTurn,
@@ -3097,7 +3147,7 @@ export const performRun = ({
3097
3147
  // TASK-440: record the context size this turn left behind, so the next
3098
3148
  // wake can decide whether to recycle. Adapters that report nothing keep
3099
3149
  // resuming.
3100
- setSession(agentName, eventPodId, result.newSessionId, {
3150
+ setSession(stateKey, eventPodId, result.newSessionId, {
3101
3151
  binding: placement.binding,
3102
3152
  contextTokens: result.contextTokens ?? null,
3103
3153
  });
@@ -3859,7 +3909,7 @@ export const performRun = ({
3859
3909
  const seenEventIds = new Set();
3860
3910
  for (const entry of entries) {
3861
3911
  const eventId = String(entry.event._id);
3862
- if (seenEventIds.has(eventId) || wasEventHandled(agentName, entry.event._id)) {
3912
+ if (seenEventIds.has(eventId) || wasEventHandled(stateKey, entry.event._id)) {
3863
3913
  entry.result = { outcome: 'no_action', reason: 'duplicate-delivery' };
3864
3914
  log(`[${entry.event.type}] duplicate delivery ${entry.event._id} — re-acking without batch spawn`);
3865
3915
  } else {
@@ -4518,7 +4568,7 @@ export const performRun = ({
4518
4568
  // reached. Unacked, the kernel redelivers it.
4519
4569
  if (!entry.result) continue;
4520
4570
  if (entry.result?.reason !== 'duplicate-delivery') {
4521
- recordHandledEvent(agentName, event._id);
4571
+ recordHandledEvent(stateKey, event._id);
4522
4572
  }
4523
4573
  try {
4524
4574
  const deliveryId = event.payload?.deliveryId;
@@ -4554,7 +4604,7 @@ export const performRun = ({
4554
4604
  }
4555
4605
  const [event] = group;
4556
4606
  let result;
4557
- if (wasEventHandled(agentName, event._id)) {
4607
+ if (wasEventHandled(stateKey, event._id)) {
4558
4608
  result = { outcome: 'no_action', reason: 'duplicate-delivery' };
4559
4609
  log(`[${event.type}] duplicate delivery ${event._id} — skipping spawn and re-acking`);
4560
4610
  } else {
@@ -4650,7 +4700,7 @@ export const performRun = ({
4650
4700
  // Record after successful processing but before ack. If the ack
4651
4701
  // fails, the next delivery is skipped and re-acked instead of
4652
4702
  // burning a second model turn for work that already completed.
4653
- recordHandledEvent(agentName, event._id);
4703
+ recordHandledEvent(stateKey, event._id);
4654
4704
  }
4655
4705
  try {
4656
4706
  const deliveryId = event.payload?.deliveryId;
@@ -4889,6 +4939,8 @@ export const performDetach = async ({
4889
4939
  agentName,
4890
4940
  podId,
4891
4941
  instanceId = 'default',
4942
+ // F306: the token file to remove; a second instance's is `<name>@<instanceId>`.
4943
+ localKey = null,
4892
4944
  skipBackend = false,
4893
4945
  log = () => {},
4894
4946
  }) => {
@@ -4919,9 +4971,10 @@ export const performDetach = async ({
4919
4971
  }
4920
4972
  }
4921
4973
 
4922
- deleteAgentToken(agentName);
4923
- clearSessions(agentName);
4924
- log(`local: removed token file + session store for '${agentName}'`);
4974
+ const stateKey = localKey || agentName;
4975
+ deleteAgentToken(stateKey);
4976
+ clearSessions(stateKey);
4977
+ log(`local: removed token file + session store for '${stateKey}'`);
4925
4978
 
4926
4979
  return { backend: backendResult, localCleaned: true };
4927
4980
  };
@@ -5322,6 +5375,7 @@ Docs:
5322
5375
  .command('run <name>')
5323
5376
  .description('Run the local-CLI wrapper loop for an attached agent')
5324
5377
  .option('--interval <ms>', 'Poll interval in ms', '5000')
5378
+ .option('--instance-id <id>', 'Run this instance of the agent, when it has more than one (default: default)')
5325
5379
  .option('--adapter <name>', `CLI to wrap on first-run bootstrap (${listPublicAdapterNames().join('|')}); an existing token file bound to a different adapter stops the run`)
5326
5380
  .option('--cascade-cap <n>', `Consecutive agent-triggered turns allowed per pod (env ${CASCADE_ENV_VARS.cap}, default ${CASCADE_DEFAULTS.cap})`)
5327
5381
  .option('--cascade-grace <n>', `Extra turns allowed when this seat was directly addressed; 0 disables the grace (env ${CASCADE_ENV_VARS.addressedGrace}, default ${CASCADE_DEFAULTS.addressedGrace})`)
@@ -5329,7 +5383,19 @@ Docs:
5329
5383
  .option('--refusal-handoff <agent>', 'Agent to @mention when the model provider refuses a request\'s content; the request is acked as refused, never retried')
5330
5384
  .option('--allow <grants>', 'On first run of an agent that works in its folder, also let it edit files and run commands (write) and/or fetch web pages (web), comma-separated. Commands reach the network.')
5331
5385
  .option('--unsandboxed', 'Native Windows only: run this agent without a sandbox, with your own access to files and commands. It gets no connector grants. Codex can run commands in invite-only pods, where anyone in the pod, including people invited later, can direct it.')
5332
- .action(async (name, opts) => {
5386
+ .action(async (typedName, opts) => {
5387
+ // F306: the seat this run is. `name` is the local key (the token file,
5388
+ // the log label, the daemon's plist); the server identity is the record's.
5389
+ let instanceId;
5390
+ try {
5391
+ instanceId = parseRunInstanceId(opts.instanceId, typedName);
5392
+ } catch (err) {
5393
+ console.error(`${stamp()} [${typedName}] ${err.message}`);
5394
+ process.exit(1);
5395
+ }
5396
+ const agentArg = String(typedName).split('@')[0];
5397
+ const named = instanceId !== null;
5398
+ let name = named ? seatKey(agentArg, instanceId) : agentArg;
5333
5399
  if (opts.unsandboxed) {
5334
5400
  const flagRefusal = unsandboxedFlagRefusal();
5335
5401
  if (flagRefusal) {
@@ -5345,8 +5411,22 @@ Docs:
5345
5411
  process.exit(1);
5346
5412
  }
5347
5413
  let record = loadAgentToken(name);
5414
+ // An instance's key saved by an older run, under the bare name: use it
5415
+ // where it is, when it is that instance's (F306).
5416
+ if (!record && named && name !== agentArg) {
5417
+ const legacy = loadAgentToken(agentArg);
5418
+ if (legacy && !runInstanceRefusal({ record: legacy, instanceId })) {
5419
+ record = legacy;
5420
+ name = agentArg;
5421
+ }
5422
+ }
5348
5423
  let bootstrapped = false;
5349
5424
  const saved = record;
5425
+ const savedRefusal = record && named ? runInstanceRefusal({ record, instanceId }) : null;
5426
+ if (savedRefusal) {
5427
+ console.error(`${stamp()} [${name}] ${savedRefusal}`);
5428
+ process.exit(1);
5429
+ }
5350
5430
  if (record) {
5351
5431
  record = await adoptEnvToken({
5352
5432
  record,
@@ -5358,7 +5438,7 @@ Docs:
5358
5438
  // not a token file — bootstrap the record from them (#913).
5359
5439
  try {
5360
5440
  record = await bootstrapAgentRecordFromEnv({
5361
- name,
5441
+ name: agentArg,
5362
5442
  adapterOverride: opts.adapter || null,
5363
5443
  log: (line) => console.log(`${stamp()} [${name}] ${line}`),
5364
5444
  allow,
@@ -5376,10 +5456,15 @@ Docs:
5376
5456
  console.error(
5377
5457
  `No token for '${name}'. Either export COMMONLY_API_URL + COMMONLY_AGENT_TOKEN`
5378
5458
  + ` (shown on the Connect your own agent page) and re-run, or:`
5379
- + ` commonly agent attach <adapter> --pod <podId> --name ${name}`,
5459
+ + ` commonly agent attach <adapter> --pod <podId> --name ${agentArg}`,
5380
5460
  );
5381
5461
  process.exit(1);
5382
5462
  }
5463
+ const instanceRefusal = named ? runInstanceRefusal({ record, instanceId }) : null;
5464
+ if (instanceRefusal) {
5465
+ console.error(`${stamp()} [${name}] ${instanceRefusal}`);
5466
+ process.exit(1);
5467
+ }
5383
5468
  bootstrapped = true;
5384
5469
  }
5385
5470
 
@@ -5447,8 +5532,15 @@ Docs:
5447
5532
  }
5448
5533
  if (saved && record !== saved) saveAgentToken(name, record);
5449
5534
  if (bootstrapped) {
5450
- saveAgentToken(record.agentName, record);
5451
- console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(record.agentName)} from COMMONLY_AGENT_TOKEN (adapter: ${record.adapter})`);
5535
+ // A named instance is saved under its seat key; an unnamed run keeps
5536
+ // the bare name, as before.
5537
+ const savedAs = named ? seatKey(record.agentName, record.instanceId) : record.agentName;
5538
+ // The record's own spelling names the file, so the state this run keeps
5539
+ // follows it there, and the next run finds both (case, or a token that
5540
+ // belongs to another name).
5541
+ if (named) name = savedAs;
5542
+ saveAgentToken(savedAs, record);
5543
+ console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(savedAs)} from COMMONLY_AGENT_TOKEN (adapter: ${record.adapter})`);
5452
5544
  } else if (savedSeatLacksDefaultSandbox(record)) {
5453
5545
  console.warn(
5454
5546
  `${stamp()} [${name}] this agent's saved settings declare no sandbox, so it runs without one. `
@@ -5528,6 +5620,7 @@ Docs:
5528
5620
  agentName: record.agentName,
5529
5621
  displayName: record.displayName || record.agentName,
5530
5622
  instanceId: record.instanceId,
5623
+ localKey: name,
5531
5624
  podId: record.podId,
5532
5625
  environment: runEnvironment || null,
5533
5626
  hostUnconfined,
@@ -5630,6 +5723,7 @@ Docs:
5630
5723
  agentName: record.agentName,
5631
5724
  podId: record.podId,
5632
5725
  instanceId: record.instanceId || 'default',
5726
+ localKey: name,
5633
5727
  skipBackend: !!opts.force,
5634
5728
  log: (line) => console.warn(`[detach] ${line}`),
5635
5729
  });
@@ -26,7 +26,8 @@ import { armSupervisedGroupDeadline, killSupervisedGroups } from '@commonlyai/se
26
26
 
27
27
  export const DEFAULT_EXIT_TIMEOUT_S = 20;
28
28
  const MAX_MARGIN_MS = 5000;
29
- const SEAT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
29
+ // `@` joins an agent and its instance in a second instance's key (F306).
30
+ const SEAT_NAME = /^[A-Za-z0-9][A-Za-z0-9._@-]*$/;
30
31
 
31
32
  /** The seat's launchd plist path, or null for a name that cannot be a file name. */
32
33
  export const seatPlistPath = (name, home = homedir()) => (typeof name === 'string' && SEAT_NAME.test(name)
@@ -21,7 +21,7 @@
21
21
  * restart can still suppress a re-delivered event whose ack previously failed.
22
22
  */
23
23
 
24
- import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, renameSync } from 'fs';
24
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, renameSync, chmodSync } from 'fs';
25
25
  import { join } from 'path';
26
26
  import { homedir } from 'os';
27
27
 
@@ -32,6 +32,23 @@ const noticesFile = (agentName) => join(sessionsDir(), `${agentName}.notices.jso
32
32
  const MAX_HANDLED_EVENTS = 500;
33
33
  const handledEventsCache = new Map();
34
34
 
35
+ // Everything under ~/.commonly is private (D275). These files hold per-(agent,
36
+ // pod) session IDs and event rings; keep the dir and its files owner-only, and
37
+ // tighten an existing dir or file that a pre-0.1.309 CLI left group/world-
38
+ // readable. A mode arg applies only when the path is created, so each write
39
+ // chmods after — the same belt-and-braces config.js uses for the token file.
40
+ const ensureSessionsDir = () => {
41
+ const dir = sessionsDir();
42
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
43
+ try { chmodSync(dir, 0o700); } catch { /* a dir we don't own: leave it */ }
44
+ return dir;
45
+ };
46
+
47
+ const writeSessionFile = (file, data) => {
48
+ writeFileSync(file, data, { encoding: 'utf8', mode: 0o600 });
49
+ try { chmodSync(file, 0o600); } catch { /* best effort to tighten an existing file */ }
50
+ };
51
+
35
52
  const readAgent = (agentName) => {
36
53
  const file = sessionsFile(agentName);
37
54
  if (!existsSync(file)) return {};
@@ -43,8 +60,8 @@ const readAgent = (agentName) => {
43
60
  };
44
61
 
45
62
  const writeAgent = (agentName, state) => {
46
- if (!existsSync(sessionsDir())) mkdirSync(sessionsDir(), { recursive: true });
47
- writeFileSync(sessionsFile(agentName), JSON.stringify(state, null, 2), 'utf8');
63
+ ensureSessionsDir();
64
+ writeSessionFile(sessionsFile(agentName), JSON.stringify(state, null, 2));
48
65
  };
49
66
 
50
67
  const readHandledEvents = (agentName) => {
@@ -79,8 +96,8 @@ const getHandledEvents = (agentName) => {
79
96
  };
80
97
 
81
98
  const writeHandledEvents = (agentName, ids) => {
82
- if (!existsSync(sessionsDir())) mkdirSync(sessionsDir(), { recursive: true });
83
- writeFileSync(handledEventsFile(agentName), JSON.stringify(ids, null, 2), 'utf8');
99
+ ensureSessionsDir();
100
+ writeSessionFile(handledEventsFile(agentName), JSON.stringify(ids, null, 2));
84
101
  };
85
102
 
86
103
  export const getSession = (agentName, podId, { binding = null } = {}) => {
@@ -173,7 +190,7 @@ export const recordNotice = (agentName, key, now = Date.now()) => {
173
190
  if (!agentName || !key) return;
174
191
  const state = readNotices(agentName);
175
192
  state[key] = new Date(now).toISOString();
176
- if (!existsSync(sessionsDir())) mkdirSync(sessionsDir(), { recursive: true });
193
+ ensureSessionsDir();
177
194
  // Temp file then rename, so a crash mid-write never leaves a torn file, and
178
195
  // 0600 because the record says which models this seat's key cannot use.
179
196
  const file = noticesFile(agentName);