@commonlyai/cli 0.1.262 → 0.1.264

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -327,12 +327,46 @@ export const scrubAdapterFailure = (text, { credentials = [], limit = MAX_REFUSA
327
327
  * spawn-retry.js). The message still names the status so a human log says the
328
328
  * same thing as the classifier's decision.
329
329
  */
330
+ /**
331
+ * The provider's own error code (`error.code`, then a top-level `code`), read
332
+ * from the body a tail carries: the structured body after a status, else the
333
+ * one JSON object embedded in prose (`unexpected status 404 Not Found: {…}`).
334
+ * It is a keep-list of one more named field, and narrower than the message:
335
+ * only a short identifier is kept, and one that echoes a credential this spawn
336
+ * was handed is dropped. Null when there is none (F178: the keep-list reduced
337
+ * `{"code":"model_not_found"}` to its message, so the code was lost).
338
+ */
339
+ const PROVIDER_CODE_RE = /^[A-Za-z][\w.-]{0,63}$/;
340
+ export const providerCodeFrom = (text, { credentials = [] } = {}) => {
341
+ const raw = String(text ?? '');
342
+ const { body } = readStatusAndBody(raw.trim());
343
+ const candidates = [body];
344
+ const start = raw.indexOf('{');
345
+ const end = raw.lastIndexOf('}');
346
+ if (start >= 0 && end > start) candidates.push(raw.slice(start, end + 1));
347
+ for (const candidate of candidates) {
348
+ let parsed;
349
+ try {
350
+ parsed = JSON.parse(candidate);
351
+ } catch {
352
+ continue;
353
+ }
354
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) continue;
355
+ const code = parsed.error?.code ?? parsed.code;
356
+ if (typeof code !== 'string' || !PROVIDER_CODE_RE.test(code)) return null;
357
+ return redactKnownCredentials(code, credentials) === code ? code : null;
358
+ }
359
+ return null;
360
+ };
361
+
330
362
  export const adapterFailure = (label, text, { credentials = [], exitCode = null, limit } = {}) => {
331
363
  const { status, detail } = scrubAdapterFailure(text, { credentials, limit });
332
364
  const code = exitCode === null ? '' : ` exited with code ${exitCode}`;
333
365
  const named = status === null ? '' : ` (upstream ${status})`;
334
366
  const error = new Error(`${label}${code}${named}${detail ? `: ${detail}` : ''}`);
335
367
  if (status !== null) error.status = status;
368
+ const providerCode = providerCodeFrom(text, { credentials });
369
+ if (providerCode !== null) error.providerCode = providerCode;
336
370
  return error;
337
371
  };
338
372
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.262",
3
+ "version": "0.1.264",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -45,7 +45,14 @@ import {
45
45
  clearSessions,
46
46
  wasEventHandled,
47
47
  recordHandledEvent,
48
+ noticeDue,
49
+ recordNotice,
48
50
  } from '../lib/session-store.js';
51
+ import {
52
+ MODEL_UNAVAILABLE_HINT_WINDOW_MS,
53
+ modelUnavailableFailure,
54
+ modelUnavailableHint,
55
+ } from '../lib/model-unavailable.js';
49
56
  import {
50
57
  buildRecycleBriefing,
51
58
  idleMinutesSince,
@@ -736,6 +743,16 @@ const PROMPT_EVENT_TYPES = new Set([
736
743
  // is the only one worth holding back.
737
744
  const DEFERRABLE_SOLO_EVENT_TYPES = new Set(['first_contact']);
738
745
 
746
+ // How long a fresh seat's greeting waits for a person before it runs alone.
747
+ // One poll lost the race on the 0.1.257 walk (2026-11-05): the mention landed
748
+ // just after the hold, the greeting took the next turn alone, and the answer
749
+ // came 50.5 s after the mention instead of 25.7 s. A person who has just
750
+ // connected an agent usually mentions it within its first minute, and the
751
+ // kernel posts the seat's own join line at once, so a quiet connect loses
752
+ // nothing by greeting a minute later. Counted in polls (at least one), so a
753
+ // shorter --interval holds for more polls, not for less time.
754
+ const GREETING_HOLD_MS = 60_000;
755
+
739
756
  // Inside one batch the person's item leads the prompt; the greeting follows it.
740
757
  const PERSON_WAITING_EVENT_TYPES = new Set(['chat.mention', 'message.posted', 'dm.message']);
741
758
 
@@ -1507,8 +1524,16 @@ const FINAL_TEXT_IS_POSTED = 'Your final text is posted to the pod unless it is
1507
1524
  // with no message at all. Only a message with no thread, outside a DM, gets it.
1508
1525
  // The line still allows the overflow rule (post the point, continue under your
1509
1526
  // own root): only threading under the person's message is ruled out.
1527
+ //
1528
+ // The same walk on 0.1.258, with the mention sharing a turn with the greeting:
1529
+ // the seat obeyed that line about threadRootId and passed replyToMessageId
1530
+ // instead. The kernel files a reply in its parent's thread
1531
+ // (COALESCE(parent.thread_root_id, parent.id) in models/pg/Message.ts), so
1532
+ // that threads it too. The line names both fields.
1510
1533
  const ANSWER_IN_CHANNEL = '[This message is top-level in the channel, not in a thread: post your answer top-level. '
1511
- + 'Never set threadRootId to this message\'s id; a long answer may continue under your own top-level post.]';
1534
+ + 'Do not pass this message\'s id as threadRootId or as replyToMessageId: a reply is filed in the thread of '
1535
+ + 'the message it replies to, so either one hides your answer under it. '
1536
+ + 'A long answer may continue under your own top-level post.]';
1512
1537
 
1513
1538
  export const answersInChannel = (entry) => {
1514
1539
  const payload = entry?.event?.payload || {};
@@ -2250,6 +2275,35 @@ export const performRun = ({
2250
2275
  }
2251
2276
  };
2252
2277
 
2278
+ // F178: a provider that will not run this seat's model fails every turn the
2279
+ // same way, and until now only the seat log said so. Post one plain line in
2280
+ // the pod naming the model and where to change it, at most once per model
2281
+ // per seat per hour (persisted, so a restart does not re-post). The failure
2282
+ // itself is rethrown by the caller unchanged, so retry and ack behave as
2283
+ // before. A notice that fails to post is logged and tried on a later turn.
2284
+ const postModelUnavailableHint = async (error, hintPodId, configuredModel) => {
2285
+ const failure = modelUnavailableFailure(error, { fallbackModel: configuredModel });
2286
+ if (!failure || !hintPodId) return;
2287
+ const key = `model-unavailable:${failure.model || 'unknown'}`;
2288
+ try {
2289
+ if (!noticeDue(agentName, key, MODEL_UNAVAILABLE_HINT_WINDOW_MS)) return;
2290
+ const delivery = await deliverChatReply({
2291
+ client,
2292
+ podId: hintPodId,
2293
+ text: modelUnavailableHint(failure.model),
2294
+ limit: chatCharLimit,
2295
+ maxChunks: maxChatChunks,
2296
+ log,
2297
+ });
2298
+ if (!delivery.skipped && !delivery.refused) {
2299
+ recordNotice(agentName, key);
2300
+ log(`model unavailable hint posted (${failure.model || 'model not named'})`);
2301
+ }
2302
+ } catch (noticeError) {
2303
+ log(`model unavailable hint could not be posted: ${noticeError.message}`);
2304
+ }
2305
+ };
2306
+
2253
2307
  const runTurnBody = async ({
2254
2308
  event, eventPodId, prompt, preSpawnIds, snapshotMessages, claimKeeper, trigger, turn,
2255
2309
  }) => {
@@ -2526,7 +2580,12 @@ export const performRun = ({
2526
2580
  // Supervised or plain, a failure is thrown exactly as the adapter's own
2527
2581
  // would be, so the run loop's classification and retry apply unchanged.
2528
2582
  const spawnStartedAt = Date.now();
2529
- result = await turn.run(adapter, spawnPrompt, spawnCtx);
2583
+ try {
2584
+ result = await turn.run(adapter, spawnPrompt, spawnCtx);
2585
+ } catch (spawnError) {
2586
+ await postModelUnavailableHint(spawnError, eventPodId, seatEnvironment?.model);
2587
+ throw spawnError;
2588
+ }
2530
2589
  spawnDurationMs = Date.now() - spawnStartedAt;
2531
2590
  spawnCompleted = true;
2532
2591
  } finally {
@@ -2988,6 +3047,10 @@ export const performRun = ({
2988
3047
  // Spent at most once per run. (CTO review 5623358693.)
2989
3048
  let heldGreeting = [];
2990
3049
  let greetingHoldSpent = false;
3050
+ // Polls the connect-time greeting has been carried, against the window.
3051
+ let greetingHeldPolls = 0;
3052
+ let greetingHoldStartedAt = null;
3053
+ const greetingHoldPolls = Math.max(1, Math.ceil(GREETING_HOLD_MS / Math.max(1, Number(intervalMs) || 1)));
2991
3054
 
2992
3055
  // The same is true of a batch whose turn FAILED: its events are claimed, so
2993
3056
  // scheduling a later poll retries nothing — the next poll cannot return
@@ -3463,8 +3526,16 @@ export const performRun = ({
3463
3526
  // The liveness clock runs from here until the next scheduled wait, paused
3464
3527
  // only while a model turn runs (lib/poll-liveness.js).
3465
3528
  pollLiveness.arm();
3529
+ // Leave room for what this loop carries (a held greeting, a failed
3530
+ // batch), so a carried event never pushes a full page past the prompt's
3531
+ // body cap and a busy pod can't keep the greeting out (CodeRabbit on
3532
+ // #3511). The overflow pass below stays as the backstop.
3533
+ // Only wake events count: the server's page cap is on wakes, and a
3534
+ // carried digest row takes no body (CodeRabbit on #3511).
3535
+ const carriedCount = [...heldRetry, ...heldGreeting]
3536
+ .filter((event) => event.deliveryMode !== 'digest').length;
3466
3537
  const page = await client.get('/api/agents/runtime/events', {
3467
- agentName, instanceId, limit: batchLimit,
3538
+ agentName, instanceId, limit: Math.max(1, batchLimit - carriedCount),
3468
3539
  ...(adapter?.name ? { reportedCli: adapter.name } : {}),
3469
3540
  });
3470
3541
  pollLiveness.arm();
@@ -3512,7 +3583,22 @@ export const performRun = ({
3512
3583
  group.push(event);
3513
3584
  eventGroups.set(key, group);
3514
3585
  }
3515
- const groups = [...eventGroups.values()];
3586
+ // A carried greeting must not push a full page past the prompt's body
3587
+ // cap: an event past the cap gets no body yet is acked with the batch
3588
+ // (CodeRabbit on #3511). Carry the greeting again instead.
3589
+ for (const [key, group] of eventGroups) {
3590
+ const wakeCount = group.filter((event) => event.deliveryMode !== 'digest').length;
3591
+ if (wakeCount <= batchLimit) continue;
3592
+ const overflow = group.filter((event) => carriedIds.has(String(event._id))
3593
+ && DEFERRABLE_SOLO_EVENT_TYPES.has(event.type));
3594
+ if (!overflow.length) continue;
3595
+ heldGreeting = [...heldGreeting, ...overflow];
3596
+ eventGroups.set(key, group.filter((event) => !overflow.includes(event)));
3597
+ }
3598
+ const groups = [...eventGroups.values()].filter((group) => group.length > 0);
3599
+ // The greeting window is counted once per poll, however many pods'
3600
+ // greetings this page carries (gate review of #3511).
3601
+ let greetingCarriedThisPoll = false;
3516
3602
  // The claimed events a failure at `groupIndex` stops before they run.
3517
3603
  // A digest-only group was never claimed, so it is not carried.
3518
3604
  const untriedAfter = (groupIndex) => groups.slice(groupIndex + 1)
@@ -3529,15 +3615,35 @@ export const performRun = ({
3529
3615
  }
3530
3616
  if ((group[0].podId || podId) && !PRIVATE_RESPONSE_EVENT_TYPES.has(group[0].type)) {
3531
3617
  // Nothing in this batch but the seat introducing itself: leave it
3532
- // unacked for one interval so a person who mentions the agent in that
3533
- // window is answered in the same turn instead of behind a greeting.
3534
- // Spent once per run, so a quiet connect still greets on the next tick.
3535
- if (!greetingHoldSpent && group.every((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))) {
3536
- greetingHoldSpent = true;
3537
- heldGreeting = group;
3538
- log(`[inbox.batch] carrying ${group.length} greeting event(s) to the next poll in case someone is mid-sentence`);
3618
+ // unacked for up to GREETING_HOLD_MS, so a person who mentions the
3619
+ // agent in that window is answered first, in the same turn, instead
3620
+ // of behind a greeting. Only the connect-time greeting is held: once
3621
+ // a turn has carried one, later greetings run as they arrive.
3622
+ // Digest rows ride along with a greeting without counting as a
3623
+ // person waiting (CodeRabbit on #3511). The window is bounded by the
3624
+ // clock too, so turns run for other pods between polls can't stretch
3625
+ // the carry past its delivery lease (CodeRabbit on #3511).
3626
+ if (!greetingHoldSpent
3627
+ && (greetingCarriedThisPoll || (greetingHeldPolls < greetingHoldPolls
3628
+ && (greetingHoldStartedAt === null || Date.now() - greetingHoldStartedAt < GREETING_HOLD_MS)))
3629
+ && group.some((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))
3630
+ && group.every((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type) || event.deliveryMode === 'digest')) {
3631
+ if (greetingHeldPolls === 0 && !greetingCarriedThisPoll) {
3632
+ log(`[inbox.batch] carrying ${group.length} greeting event(s) for up to `
3633
+ + `${Math.round(GREETING_HOLD_MS / 1000)} s, so a person who mentions this agent is answered first`);
3634
+ }
3635
+ if (!greetingCarriedThisPoll) {
3636
+ greetingCarriedThisPoll = true;
3637
+ greetingHeldPolls += 1;
3638
+ if (greetingHoldStartedAt === null) greetingHoldStartedAt = Date.now();
3639
+ }
3640
+ // Appended, never assigned: two pods' greetings can be carried in
3641
+ // the same window, and an overwrite left the first unacked until
3642
+ // the server's requeue, 10 to 20 minutes later.
3643
+ heldGreeting = [...heldGreeting, ...group];
3539
3644
  continue;
3540
3645
  }
3646
+ if (group.some((event) => DEFERRABLE_SOLO_EVENT_TYPES.has(event.type))) greetingHoldSpent = true;
3541
3647
  // One failure report for a batch whose items stay unacked, whether
3542
3648
  // the composite turn threw or an isolated item did after a refusal.
3543
3649
  // The unacked items are carried to the retry, not left to the
@@ -85,6 +85,7 @@ import {
85
85
  normalizeSandboxTrust,
86
86
  } from '../environment.js';
87
87
  import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
88
+ import { holdWorkspaceRealpath, workspacePinDir } from '../sandbox/workspace-pin.js';
88
89
  import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from '../sandbox/mode.js';
89
90
  import { UNSANDBOXED_FLAG } from '../sandbox/host-check.js';
90
91
  import {
@@ -1458,6 +1459,10 @@ const prepareArgv = async (innerArgv, ctx) => {
1458
1459
  // link refuses the turn (fail-closed). A workspace seat's folder is the
1459
1460
  // operator's own choice, which may be a link, and keeps following it.
1460
1461
  pinWorkspace: sandboxTrust === 'public',
1462
+ // F200: a workspace seat's folder is held to the realpath recorded on
1463
+ // its first turn, and that record is never writable from the jail.
1464
+ expectedWorkspaceRealpath: ctx.workspaceRealpath || null,
1465
+ denyWritePaths: ctx.workspacePinDirs || [],
1461
1466
  executablePath: claudeBin,
1462
1467
  statePath: ctx.publicClaudeState.statePath,
1463
1468
  mcpConfigDir: ctx.mcpConfigDir,
@@ -1524,6 +1529,10 @@ const prepareArgv = async (innerArgv, ctx) => {
1524
1529
  const { statePath } = ctx.publicClaudeState;
1525
1530
  const wrapped = wrapArgvWithBwrap([claudeBin, ...innerArgv], env, {
1526
1531
  workspacePath: ctx.cwd,
1532
+ // F200: bwrap resolves a bind source when the jail starts, after the
1533
+ // check, so the checked realpath is the source, mounted at the path the
1534
+ // seat was given.
1535
+ workspaceSource: ctx.workspaceRealpath || ctx.cwd,
1527
1536
  workspaceReadOnly: !grants.includes('write'),
1528
1537
  readOnlyWorkspaceEntries: ['.git'],
1529
1538
  homePath: statePath,
@@ -1720,6 +1729,14 @@ export default {
1720
1729
  && resolvePublicSandboxMode(ctx.environment?.sandbox) === 'bwrap';
1721
1730
  const workspaceBwrapSandbox = jailed && ctx.environment?.sandbox?.trust === 'workspace'
1722
1731
  && resolvePublicSandboxMode(ctx.environment?.sandbox) === 'bwrap';
1732
+ // F200: a jailed workspace seat's folder must still resolve where it did
1733
+ // on the seat's first turn, or a link the seat left in its place would
1734
+ // carry this turn's grant elsewhere. The record sits beside the seat's
1735
+ // state folder, the one bwrapClaudeStatePath names for both jails.
1736
+ const heldWorkspace = ctx.environment?.sandbox?.trust === 'workspace' && Boolean(ctx.cwd)
1737
+ && (publicNativeSandbox || workspaceBwrapSandbox);
1738
+ const workspacePinDirs = heldWorkspace ? [workspacePinDir(bwrapClaudeStatePath(ctx))] : [];
1739
+ let workspaceRealpath = null;
1723
1740
  // The proxy's address and per-turn token, never the host's key.
1724
1741
  const withProvider = (env) => {
1725
1742
  if (providerProxy) {
@@ -1733,6 +1750,11 @@ export default {
1733
1750
  ...spawnCredentials(spawnContext), providerProxy?.token,
1734
1751
  ].filter(Boolean);
1735
1752
  try {
1753
+ // Checked (and recorded, the first time) before the state is prepared
1754
+ // or anything is spawned.
1755
+ if (heldWorkspace) {
1756
+ workspaceRealpath = await holdWorkspaceRealpath({ cwd: ctx.cwd, statePath: bwrapClaudeStatePath(ctx) });
1757
+ }
1736
1758
  // Trust is normalized at entry (legacy `internal` reads as public). The
1737
1759
  // MCP policy follows trust alone, whatever confines the seat: a public
1738
1760
  // bwrap seat needs a host-prepared build exactly as a Seatbelt one does
@@ -1854,6 +1876,8 @@ export default {
1854
1876
  publicClaudeState,
1855
1877
  publicSkillArgs,
1856
1878
  providerProxyPort: proxyPort(providerProxy),
1879
+ workspaceRealpath,
1880
+ workspacePinDirs,
1857
1881
  claudeEnv,
1858
1882
  };
1859
1883
  const { cmd, args, env, childHome } = await prepareArgv(baseArgs, spawnCtx);