@commonlyai/cli 0.1.371 → 0.1.373

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.371",
3
+ "version": "0.1.373",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -143,6 +143,7 @@ import {
143
143
  spawnRetryJitter,
144
144
  spawnRetryPolicy,
145
145
  } from '../lib/spawn-retry.js';
146
+ import { explainNarrowing, narrowingConfirmBody } from '../lib/install-narrowing.js';
146
147
  import {
147
148
  CONTENT_REFUSED_REASON,
148
149
  composeRefusalHandoff,
@@ -181,6 +182,10 @@ import { buildReplyReceipt } from '../lib/reply-receipt.js';
181
182
  import { savedRuntimeControls, withSavedRuntimeControls, effortRefusedByDevice } from '../lib/seat-runtime-controls.js';
182
183
  import { CLI } from '../lib/cli-hint.js';
183
184
 
185
+ // F167: shared by attach, init and register.
186
+ const NARROWING_FLAG_HELP = 'Install even when joining this pod would limit where the agent can write in its other pods '
187
+ + '(the install says which pods first)';
188
+
184
189
  const isPodFocusDiagnostic = (error) => (
185
190
  typeof error?.code === 'string'
186
191
  && (error.code.startsWith('pod_focus') || error.code.startsWith('FOCUS_FRAME_'))
@@ -1502,6 +1507,8 @@ export const performAttach = async ({
1502
1507
  wakeOnMessage = false,
1503
1508
  memoryFrom = null,
1504
1509
  memoryInstance = 'default',
1510
+ // F167: confirm the install route's narrowing warning (F164).
1511
+ confirmNarrowing = false,
1505
1512
  log = () => {},
1506
1513
  adapterRegistry = { getAdapter, listAdapterNames, listPublicAdapterNames },
1507
1514
  seatbelt: probeSeatbelt = detectSeatbelt,
@@ -1693,6 +1700,7 @@ export const performAttach = async ({
1693
1700
  ...(memoryFrom ? {
1694
1701
  resumeExisting: true, memoryFrom: { agentName: memoryFrom, instanceId: memoryInstance },
1695
1702
  } : {}),
1703
+ ...narrowingConfirmBody(confirmNarrowing),
1696
1704
  agentName,
1697
1705
  podId,
1698
1706
  displayName: displayName || agentName,
@@ -1710,7 +1718,7 @@ export const performAttach = async ({
1710
1718
  ...(wakeOnMessage ? { wakeOnMessage: { enabled: true } } : {}),
1711
1719
  },
1712
1720
  scopes: ['context:read', 'messages:write', 'memory:read', 'memory:write'],
1713
- });
1721
+ }).catch((error) => { throw explainNarrowing(error); });
1714
1722
 
1715
1723
  const installation = installResult.installation || installResult;
1716
1724
  const instanceId = installation.instanceId || 'default';
@@ -4975,6 +4983,13 @@ export const performRun = ({
4975
4983
  });
4976
4984
  nextPollDelayMs = retry.delayMs;
4977
4985
  retryScheduled = true;
4986
+ // As in the batch path (F236): an open circuit's wait is walked in
4987
+ // one-minute checks that tell newly waiting pods, never slept
4988
+ // through whole. A stated quota reset can make it hours (F481,
4989
+ // CodeRabbit on #4108).
4990
+ circuitNotice = retry.circuitOpen && cantAnswerNotice(err) && !modelUnavailableFailure(err)
4991
+ ? { error: err, remainingMs: retry.delayMs }
4992
+ : null;
4978
4993
  // Carried to the retry like a failed batch: the event is claimed,
4979
4994
  // so the next poll would not return it.
4980
4995
  tickUnsettled.push(...claimedAfter(groupIndex));
@@ -5232,6 +5247,7 @@ export const performInit = async ({
5232
5247
  podId,
5233
5248
  displayName,
5234
5249
  targetDir,
5250
+ confirmNarrowing = false,
5235
5251
  }) => {
5236
5252
  const recipe = SDK_SOURCES[language];
5237
5253
  if (!recipe) {
@@ -5260,12 +5276,21 @@ export const performInit = async ({
5260
5276
  // Self-serve install (ADR-006). No publish step; the backend synthesizes
5261
5277
  // an ephemeral registry row when no manifest exists for this name.
5262
5278
  const installResult = await client.post('/api/registry/install', {
5279
+ ...narrowingConfirmBody(confirmNarrowing),
5263
5280
  agentName,
5264
5281
  podId,
5265
5282
  displayName: displayName || agentName,
5266
5283
  version: '1.0.0',
5267
5284
  config: { runtime: { runtimeType: 'webhook', host: 'byo' } },
5268
5285
  scopes: ['context:read', 'messages:write', 'memory:read', 'memory:write'],
5286
+ }).catch((error) => {
5287
+ // The guard above proved neither file existed, so these two are this
5288
+ // attempt's own. Remove them, or the re-run a refusal advises (F167:
5289
+ // --confirm-narrowing) stops at that same guard before it installs.
5290
+ for (const written of [sdkOutPath, botOutPath]) {
5291
+ try { rmSync(written, { force: true }); } catch { /* the install error is the one to report */ }
5292
+ }
5293
+ throw explainNarrowing(error);
5269
5294
  });
5270
5295
  const installation = installResult.installation || installResult;
5271
5296
  const instanceId = installation.instanceId || 'default';
@@ -5443,6 +5468,7 @@ Docs:
5443
5468
  .requiredOption('--webhook <url>', 'Webhook URL (e.g. https://my-agent.example.com/cap)')
5444
5469
  .option('--secret <secret>', 'Webhook signing secret (HMAC-SHA256)')
5445
5470
  .option('--display <name>', 'Display name shown in the pod')
5471
+ .option('--confirm-narrowing', NARROWING_FLAG_HELP)
5446
5472
  .option('--instance <url>', 'Target Commonly instance')
5447
5473
  .action(async (opts) => {
5448
5474
  const instanceUrl = resolveInstanceUrl(opts.instance);
@@ -5466,6 +5492,7 @@ Docs:
5466
5492
  });
5467
5493
 
5468
5494
  const result = await client.post('/api/registry/install', {
5495
+ ...narrowingConfirmBody(opts.confirmNarrowing === true),
5469
5496
  agentName: opts.name,
5470
5497
  podId: opts.pod,
5471
5498
  displayName: opts.display || opts.name,
@@ -5479,7 +5506,7 @@ Docs:
5479
5506
  },
5480
5507
  },
5481
5508
  scopes: ['context:read', 'messages:write', 'memory:read'],
5482
- });
5509
+ }).catch((error) => { throw explainNarrowing(error); });
5483
5510
 
5484
5511
  const installation = result.installation || result;
5485
5512
  const instId = installation.instanceId || 'default';
@@ -5593,6 +5620,7 @@ Docs:
5593
5620
  .option('--import-memory [path]', 'Import local memory (CLAUDE.md / MEMORY.md / ~/.claude project memory, or a given file/dir) into the agent after attach')
5594
5621
  .option('--yes', 'Skip the import confirmation prompt')
5595
5622
  .option('--wake-on-message', `Wake this agent on every message in the pod, not only @mentions (ADR-018 ambient wake; default off). Change later with: ${CLI} agent wake <name> on|off`)
5623
+ .option('--confirm-narrowing', NARROWING_FLAG_HELP)
5596
5624
  .option('--instance <url>', 'Target Commonly instance')
5597
5625
  .action(async (adapterName, opts) => {
5598
5626
  const instanceUrl = resolveInstanceUrl(opts.instance);
@@ -5616,6 +5644,7 @@ Docs:
5616
5644
  wakeOnMessage: Boolean(opts.wakeOnMessage),
5617
5645
  memoryFrom: opts.memoryFrom,
5618
5646
  memoryInstance: opts.memoryInstance,
5647
+ confirmNarrowing: opts.confirmNarrowing === true,
5619
5648
  log: (line) => console.warn(`[attach] ${line}`),
5620
5649
  });
5621
5650
 
@@ -6167,6 +6196,7 @@ Docs:
6167
6196
  .requiredOption('--pod <podId>', 'Pod ID to install into')
6168
6197
  .option('--display <name>', 'Display name shown in the pod')
6169
6198
  .option('--dir <path>', 'Target directory (default: current dir)')
6199
+ .option('--confirm-narrowing', NARROWING_FLAG_HELP)
6170
6200
  .option('--instance <url>', 'Target Commonly instance')
6171
6201
  .action(async (opts) => {
6172
6202
  const instanceUrl = resolveInstanceUrl(opts.instance);
@@ -6183,6 +6213,7 @@ Docs:
6183
6213
  podId: opts.pod,
6184
6214
  displayName: opts.display,
6185
6215
  targetDir: pathResolve(opts.dir || process.cwd()),
6216
+ confirmNarrowing: opts.confirmNarrowing === true,
6186
6217
  });
6187
6218
 
6188
6219
  console.log(`✓ Written: ${result.files.bot}`);
@@ -0,0 +1,33 @@
1
+ /**
2
+ * F167: the install route's narrowing confirmation (F164), from the CLI.
3
+ *
4
+ * Joining a pod can confine a seat's writes in its other pods (an
5
+ * outside-writable grant narrows it; backend agentRuntimeAuth). Before the
6
+ * install is written the route answers 409 with this code and a sentence naming
7
+ * what would change. The installer confirms by sending `confirmNarrowing: true`.
8
+ * The server's text ends with that API advice, so the CLI swaps it for its own
9
+ * flag.
10
+ */
11
+
12
+ // Mirrors backend services/outsiderGrantNarrowingPreview.ts NARROWING_CONFIRM_CODE.
13
+ export const NARROWING_CONFIRM_CODE = 'outsider_grant_narrowing_confirm_required';
14
+
15
+ const API_ADVICE = /\s*Send confirmNarrowing: true to install anyway\.\s*$/;
16
+ const CLI_ADVICE = 'Re-run with --confirm-narrowing to install anyway.';
17
+
18
+ /** The install body field for --confirm-narrowing: present only when set. */
19
+ export const narrowingConfirmBody = (confirm) => (confirm === true ? { confirmNarrowing: true } : {});
20
+
21
+ /**
22
+ * The same refusal, telling a CLI user the flag instead of the API field. Any
23
+ * other error is returned as it came.
24
+ */
25
+ export const explainNarrowing = (error) => {
26
+ if (error?.status !== 409 || error?.body?.code !== NARROWING_CONFIRM_CODE) return error;
27
+ const said = String(error.body.message || error.message || '').replace(API_ADVICE, '').trim();
28
+ const explained = new Error(said ? `${said} ${CLI_ADVICE}` : CLI_ADVICE);
29
+ explained.status = error.status;
30
+ explained.body = error.body;
31
+ explained.code = NARROWING_CONFIRM_CODE;
32
+ return explained;
33
+ };
@@ -64,7 +64,7 @@ export const HOST_DEFERRAL_MAX_MS = 2 * 60 * 60 * 1000;
64
64
  export const SPAWN_STALL_RETRY_BASE_MS = 2 * 60 * 1000;
65
65
 
66
66
  export const SPAWN_CIRCUIT_THRESHOLD = 3;
67
- // Base ceiling before the stable per-agent 0–20% anti-herd offset.
67
+ // Fallback ceiling when an error has no usable reset clock.
68
68
  export const SPAWN_RETRY_MAX_MS = 15 * 60 * 1000;
69
69
  export const SPAWN_RETRY_JITTER_MAX_RATIO = 0.2;
70
70
 
@@ -163,6 +163,16 @@ const QUOTA_POSSESSIVE_RE = /you'?ve (?:hit|reached) your (?!rate[ -]?limit)(?:[
163
163
  const THROTTLE_WORDING_RE = /(?:rate[ -]?limit|too many requests|overloaded|capacity)/i;
164
164
  const RATE_LIMIT_RE = /(?:rate[ -]?limit|too many requests|\b429\b|overloaded|capacity)/i;
165
165
  const CONFIGURATION_RE = /(?:ENOENT|command not found|not on PATH|login required|not logged in|invalid api key|authentication failed|unauthori[sz]ed|forbidden|\b40[13]\b)/i;
166
+ // The zone is an IANA name: Area/Location (America/Port-au-Prince, Etc/GMT+5)
167
+ // or a bare UTC/GMT, as a CI box or container seat reports. An unknown name
168
+ // fails Intl below and keeps the fallback.
169
+ const QUOTA_RESET_RE = /\bresets?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*\((UTC|GMT|[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)+)\)/i;
170
+ const QUOTA_RESET_MARGIN_MS = 2 * 60 * 1000;
171
+ // A stated reset is the old account's. A person who hits quota can switch to
172
+ // another account (`/login`), and the seat must notice that within the hour,
173
+ // not at the old account's reset hours later. So a far reset probes hourly,
174
+ // and a near one still waits for it (CTO on #4108).
175
+ export const QUOTA_RESET_MAX_WAIT_MS = 60 * 60 * 1000;
166
176
 
167
177
  const CONNECTION_FAULT_RE = /(?:ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|socket hang up|fetch failed)/;
168
178
 
@@ -249,6 +259,46 @@ const applyJitter = (delayMs, jitterRatio) => {
249
259
  return Math.round(delayMs * (1 + safeJitter));
250
260
  };
251
261
 
262
+ // Claude names the local reset clock in its quota error. Waiting for that
263
+ // clock avoids repeatedly launching a seat that cannot answer before then.
264
+ // If the hint is absent or malformed, keep the ordinary bounded retry path.
265
+ export const quotaResetDelay = (error, now = Date.now()) => {
266
+ const match = QUOTA_RESET_RE.exec(errorText(error));
267
+ if (!match) return null;
268
+ const hour = Number(match[1]);
269
+ const minute = Number(match[2] || 0);
270
+ if (hour < 1 || hour > 12 || minute > 59) return null;
271
+ const target = ((hour % 12) + (match[3].toLowerCase() === 'pm' ? 12 : 0)) * 60 + minute;
272
+ let formatter;
273
+ try {
274
+ formatter = new Intl.DateTimeFormat('en-US', {
275
+ timeZone: match[4], hour: '2-digit', minute: '2-digit', hourCycle: 'h23',
276
+ });
277
+ } catch {
278
+ return null;
279
+ }
280
+ const localMinute = (instant) => {
281
+ const parts = Object.fromEntries(formatter.formatToParts(instant).map(({ type, value }) => [type, value]));
282
+ return Number(parts.hour) * 60 + Number(parts.minute);
283
+ };
284
+ const nowMinute = localMinute(now);
285
+ const wallMinutes = (target - nowMinute + 1440) % 1440;
286
+ // At or just after the named minute, the message may be a stale failure
287
+ // from the old quota window. Probe on the ordinary cooldown instead of
288
+ // assuming the next reset is nearly 24 hours away.
289
+ if (wallMinutes === 0 || wallMinutes > 1430) return null;
290
+ let resetAt = now - (now % 60000) + wallMinutes * 60 * 1000;
291
+ // Crossing a daylight-saving boundary can shift the initial wall-clock
292
+ // estimate by an hour. Reconcile against the target in the named zone.
293
+ for (let attempt = 0; attempt < 2; attempt += 1) {
294
+ const difference = (target - localMinute(resetAt) + 1440) % 1440;
295
+ if (difference === 0) break;
296
+ resetAt += (difference > 720 ? difference - 1440 : difference) * 60 * 1000;
297
+ }
298
+ if (resetAt <= now || localMinute(resetAt) !== target) return null;
299
+ return resetAt - now + QUOTA_RESET_MARGIN_MS;
300
+ };
301
+
252
302
  /**
253
303
  * Return the next probe delay and whether the circuit is open.
254
304
  *
@@ -294,10 +344,18 @@ export const spawnRetryPolicy = ({
294
344
  failureClass === SPAWN_FAILURE_CLASS.QUOTA
295
345
  || failureClass === SPAWN_FAILURE_CLASS.CONFIGURATION
296
346
  ) {
347
+ const resetDelay = failureClass === SPAWN_FAILURE_CLASS.QUOTA
348
+ ? quotaResetDelay(error)
349
+ : null;
297
350
  return {
298
351
  failureClass,
299
352
  circuitOpen: true,
300
- delayMs: applyJitter(SPAWN_RETRY_MAX_MS, jitterRatio),
353
+ // Spread the reset probe by at most 24 seconds, not a percentage of
354
+ // the entire wait: a six-hour hint must not add an hour of lag.
355
+ delayMs: resetDelay === null
356
+ ? applyJitter(SPAWN_RETRY_MAX_MS, jitterRatio)
357
+ : Math.min(resetDelay, QUOTA_RESET_MAX_WAIT_MS)
358
+ + applyJitter(QUOTA_RESET_MARGIN_MS, jitterRatio) - QUOTA_RESET_MARGIN_MS,
301
359
  };
302
360
  }
303
361