@commonlyai/cli 0.1.295 → 0.1.297

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.
@@ -145,6 +145,11 @@ export const keptRefusalDetail = (raw, { credentials = [] } = {}) => {
145
145
  * the ladder has finished — so it wins over the per-attempt `message_end`
146
146
  * events that precede it. A run that refused on its first attempt and never
147
147
  * retried still reports through `message_end`.
148
+ *
149
+ * A retry that answered ends the refusal. pi prints `auto_retry_end` with
150
+ * `success: true` once a retried call answers (agent-session.js, pi 0.84.1), so
151
+ * a refusal before it is one pi recovered from. Kept, it would name the cause
152
+ * of a later failure that has none of its own, such as `fetch failed` (F320).
148
153
  */
149
154
  export const readUpstreamRefusal = (stdout, { credentials = [] } = {}) => {
150
155
  let status = null;
@@ -159,6 +164,16 @@ export const readUpstreamRefusal = (stdout, { credentials = [] } = {}) => {
159
164
  continue;
160
165
  }
161
166
 
167
+ // A compaction that continues the turn is pi recovering from an overflow,
168
+ // so a refusal before it is one pi recovered from too. The turn's own cause
169
+ // comes after (agent-session.js `compaction_end`, pi 0.84.1).
170
+ if ((event?.type === 'auto_retry_end' && event.success === true)
171
+ || (event?.type === 'compaction_end' && event.aborted === false && event.willRetry === true)) {
172
+ status = null;
173
+ raw = null;
174
+ continue;
175
+ }
176
+
162
177
  if (event?.type === 'auto_retry_end' && event.success === false) {
163
178
  const candidate = event.finalError ?? event.errorMessage;
164
179
  const attemptStatus = statusFromError(candidate);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.295",
3
+ "version": "0.1.297",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -104,7 +104,9 @@ import { createClaimedWorkGate } from '../lib/claimed-work-gate.js';
104
104
  import { prepareCommitAttribution } from '../lib/commit-attribution.js';
105
105
  import { detectBwrap } from '../lib/sandbox/bwrap.js';
106
106
  import { resolvePublicSandboxMode } from '../lib/sandbox/mode.js';
107
- import { UNSANDBOXED_FLAG, hostSandboxRefusal, windowsSandboxMessage } from '../lib/sandbox/host-check.js';
107
+ import {
108
+ UNSANDBOXED_FLAG, bwrapRefusedMessage, hostSandboxRefusal, windowsSandboxMessage,
109
+ } from '../lib/sandbox/host-check.js';
108
110
  import {
109
111
  CODEX_UNSANDBOXED_NOTICE, UNSANDBOXED_NOTICE, codexUnconfinedForRun, hostReportFailureMessage, hostUnconfinedForRun, runOptedInUnsandboxed,
110
112
  unsandboxedFlagRefusal,
@@ -1444,7 +1446,7 @@ export const performAttach = async ({
1444
1446
  // that don't offer the flag. A seat with no sandbox block still needs the
1445
1447
  // person's opt-in at `agent run`.
1446
1448
  const codexRefusal = hostSandboxRefusal({
1447
- environment, adapterName, platform, hostUnconfined: true, optedIn: true,
1449
+ environment, adapterName, platform, hostUnconfined: true, optedIn: true, detectBwrap: probeBwrap,
1448
1450
  });
1449
1451
  if (codexRefusal) throw new Error(codexRefusal);
1450
1452
  }
@@ -1478,6 +1480,7 @@ export const performAttach = async ({
1478
1480
  const bwrap = probeBwrap();
1479
1481
  if (!bwrap.available) {
1480
1482
  if (platform === 'win32') throw windowsRefusal();
1483
+ if (bwrap.namespaceRefused === true) throw new Error(bwrapRefusedMessage(adapterName, bwrap));
1481
1484
  throw new Error(`sandbox.mode=bwrap requested but unavailable: ${bwrap.error}`);
1482
1485
  }
1483
1486
  if (environment.sandbox?.network?.policy === 'restricted') {
@@ -533,12 +533,16 @@ export const buildArgs = ({
533
533
  * after an assistant message that stopped with `stop`. An overflow's `agent_end`
534
534
  * says `willRetry: false` and then pi compacts and continues, so `agent_end` after
535
535
  * an `error` or `length` stop doesn't count; the continuation's message decides.
536
+ * `lastError` is that last message's `errorMessage`, pi's cause for an `error`
537
+ * stop (`Provider finish_reason: content_filter`, `fetch failed`). It is raw
538
+ * provider text, so only adapterFailure's scrub may carry it anywhere.
536
539
  */
537
540
  export const extractReply = (stdout) => {
538
541
  let text = '';
539
542
  let sawAssistant = false;
540
543
  let finished = false;
541
544
  let lastStop = null;
545
+ let lastError;
542
546
  const errors = [];
543
547
  for (const line of String(stdout).split('\n')) {
544
548
  if (!line.trim()) continue;
@@ -548,12 +552,15 @@ export const extractReply = (stdout) => {
548
552
  const parts = (event.message.content || []).filter((c) => c?.type === 'text').map((c) => c.text || '');
549
553
  if (parts.length) { text = parts.join('\n').trim(); sawAssistant = true; }
550
554
  lastStop = event.message.stopReason;
555
+ lastError = typeof event.message.errorMessage === 'string' ? event.message.errorMessage : undefined;
551
556
  finished = false;
552
557
  }
553
558
  if (event?.type === 'agent_end') finished = event.willRetry !== true && lastStop === 'stop';
554
559
  if (event?.type === 'error') errors.push(String(event.message || event.error || 'error'));
555
560
  }
556
- return { text, sawAssistant, finished, lastStop, errors };
561
+ return {
562
+ text, sawAssistant, finished, lastStop, lastError, errors,
563
+ };
557
564
  };
558
565
 
559
566
  // A turn that printed an interim message and then ended without finishing. A
@@ -562,6 +569,10 @@ export const extractReply = (stdout) => {
562
569
  // holds pi's startup warnings, and a refusal on the stream may be one pi was
563
570
  // recovering from, like an overflow's 400. A clean exit that ended on an error
564
571
  // has only the stream: its stderr is those warnings too, and the refusal stands.
572
+ // A stop with no status still has the cause pi gave it, and without it a content
573
+ // filter's stop classes as a runtime fault and is retried in seconds (F320).
574
+ // The status is pi's on a clean exit, not one the kept detail mentions: that
575
+ // detail is the provider's prose, and "proxy said status 503" on a 429 is 429.
565
576
  const stoppedTurnFailure = (reply, {
566
577
  code, signal, stderr, credentials,
567
578
  }) => {
@@ -574,10 +585,12 @@ const stoppedTurnFailure = (reply, {
574
585
  || (cleanExit ? describeUpstreamRefusal(upstream) : '')
575
586
  || (killed || cleanExit ? '' : stderr.trim().slice(-600))
576
587
  || upstream?.detail
588
+ || (killed || reply.lastStop !== 'error' ? '' : reply.lastError)
577
589
  || 'the turn stopped before it finished',
578
590
  { credentials, exitCode: code, limit: 600 },
579
591
  );
580
- if (upstream) failure.status ??= upstream.status;
592
+ if (upstream && cleanExit) failure.status = upstream.status;
593
+ else if (upstream) failure.status ??= upstream.status;
581
594
  return failure;
582
595
  };
583
596
 
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { spawnSync } from 'child_process';
17
+ import { existsSync, readFileSync } from 'fs';
17
18
  import { isAbsolute, join } from 'path';
18
19
  import { homedir } from 'os';
19
20
 
@@ -60,7 +61,51 @@ const DEFAULT_RO_BINDS = [
60
61
  // ubuntu run 38982219348). Starting one empty namespace is the real check.
61
62
  const NAMESPACE_PROBE = ['--unshare-all', '--ro-bind', '/', '/', 'true'];
62
63
 
63
- export const detectBwrap = ({ spawn = spawnSync, platform = process.platform } = {}) => {
64
+ const APPARMOR_USERNS_SYSCTL = '/proc/sys/kernel/apparmor_restrict_unprivileged_userns';
65
+
66
+ // Inside a container the sysctl reports the host, and what blocks bwrap is the
67
+ // container's own policy, so the host's AppArmor is not the person's way out.
68
+ // Docker leaves /.dockerenv, Podman /run/.containerenv, and systemd writes
69
+ // /run/systemd/container inside a container (nspawn, LXC), never on a host.
70
+ // The filesystem is injectable for the tests.
71
+ const CONTAINER_MARKERS = ['/.dockerenv', '/run/.containerenv', '/run/systemd/container'];
72
+ export const readApparmorRestriction = ({ read = readFileSync, exists = existsSync } = {}) => {
73
+ if (CONTAINER_MARKERS.some((marker) => exists(marker))) return false;
74
+ try {
75
+ return read(APPARMOR_USERNS_SYSCTL, 'utf8').trim() === '1';
76
+ } catch {
77
+ return false;
78
+ }
79
+ };
80
+
81
+ // os-release values may be quoted, so `ID="ubuntu"` reads the same as `ID=ubuntu`.
82
+ // /etc/os-release wins; /usr/lib/os-release is the file it normally links to,
83
+ // read only when the first is missing.
84
+ const readOsRelease = (read) => {
85
+ try {
86
+ return read('/etc/os-release', 'utf8');
87
+ } catch {
88
+ return read('/usr/lib/os-release', 'utf8');
89
+ }
90
+ };
91
+ export const readUbuntuRelease = ({ read = readFileSync } = {}) => {
92
+ try {
93
+ const release = readOsRelease(read);
94
+ if (!/^ID=(["']?)ubuntu\1$/m.test(release)) return null;
95
+ // The last assignment wins, as it does when a shell sources the file.
96
+ const versions = [...release.matchAll(/^VERSION_ID=(["']?)([\d.]+)\1$/gm)];
97
+ return versions.at(-1)?.[2] ?? null;
98
+ } catch {
99
+ return null;
100
+ }
101
+ };
102
+
103
+ export const detectBwrap = ({
104
+ spawn = spawnSync,
105
+ platform = process.platform,
106
+ readRestriction = readApparmorRestriction,
107
+ readRelease = readUbuntuRelease,
108
+ } = {}) => {
64
109
  if (platform !== 'linux') {
65
110
  return { available: false, error: nonLinuxMessage(platform) };
66
111
  }
@@ -78,6 +123,12 @@ export const detectBwrap = ({ spawn = spawnSync, platform = process.platform } =
78
123
  const reason = (probe.stderr || probe.error?.message || `exit ${probe.status}`).trim().split('\n').pop();
79
124
  return {
80
125
  available: false,
126
+ // Only when bwrap ran and exited refusing: a probe that timed out or
127
+ // couldn't spawn says nothing about this host.
128
+ namespaceRefused: !probe.error && typeof probe.status === 'number',
129
+ reason,
130
+ apparmorRestricted: readRestriction(),
131
+ ubuntuRelease: readRelease(),
81
132
  error: `bubblewrap is installed but cannot start a sandbox on this machine (${reason}). `
82
133
  + 'On Ubuntu 24.04 and later, AppArmor restricts the unprivileged user namespaces it needs.',
83
134
  };
@@ -29,7 +29,7 @@ export const UNSANDBOXED_FLAG = '--unsandboxed';
29
29
  // added there is not silently missing here.
30
30
  const SEATBELT_MODES = PUBLIC_SANDBOX_MODES;
31
31
 
32
- const ADAPTER_LABELS = { claude: 'Claude Code', opencode: 'OpenCode', qwen: 'Qwen Code' };
32
+ const ADAPTER_LABELS = { claude: 'Claude Code', codex: 'Codex', opencode: 'OpenCode', qwen: 'Qwen Code' };
33
33
 
34
34
  const HOSTED_LINE = ' - A hosted agent: choose "Run it here" on the Connect page. Nothing runs on this machine.';
35
35
 
@@ -67,6 +67,59 @@ const CODEX_WINDOWS_PUBLIC_MESSAGE = [
67
67
  HOSTED_LINE,
68
68
  ].join('\n');
69
69
 
70
+ const CLAUDE_MCP_LINE = ' - Use Commonly from your own Claude Code sessions: the Connect page shows a `claude mcp add` command.';
71
+
72
+ // Claude Code and Codex each answered on prod under this profile, on a fresh
73
+ // Ubuntu 24.04 runner (byo-linux.yml runs 42398237284, 42398763392), so only
74
+ // they are offered it. Printed for the person to run; nothing here runs it. It
75
+ // stays the last and optional route, and the sysctl behind the restriction is
76
+ // never named as a way out. The lines take the one file out of the package:
77
+ // installing apparmor-profiles enforces 21 more profiles at once, among them
78
+ // ping, dnsmasq and smbd (run 42400201955), which nobody here agreed to.
79
+ // The subshell keeps the person in their project folder, which a first run on a
80
+ // private pod binds to, and stops at the first failure. byo-linux.yml runs these
81
+ // exact lines.
82
+ export const UBUNTU_BWRAP_PROFILE_COMMANDS = [
83
+ 'sudo apt-get update',
84
+ '(cd "$(mktemp -d)" && apt-get download apparmor-profiles && dpkg-deb -x apparmor-profiles_*.deb .'
85
+ + ' && sudo cp usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/)',
86
+ 'sudo apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict',
87
+ ];
88
+
89
+ export const UBUNTU_BWRAP_PROFILE_UNDO = [
90
+ 'sudo apparmor_parser -R /etc/apparmor.d/bwrap-userns-restrict',
91
+ 'sudo rm /etc/apparmor.d/bwrap-userns-restrict',
92
+ ];
93
+
94
+ const UBUNTU_BWRAP_PROFILE_LINES = [
95
+ " - Optional, if you'd rather run it on this machine: load Ubuntu's own AppArmor profile for bubblewrap.",
96
+ ' It lets any program here use bubblewrap to create user namespaces; what bubblewrap starts gets no special',
97
+ " capabilities. It's your call, it needs sudo, and Commonly never runs it for you. We tested it on a fresh",
98
+ " Ubuntu 24.04 server image, not on every machine. These lines load that one profile and nothing else from",
99
+ " Ubuntu's package:",
100
+ ...UBUNTU_BWRAP_PROFILE_COMMANDS.map((line) => ` ${line}`),
101
+ ' Then run the same command again. To undo it:',
102
+ ...UBUNTU_BWRAP_PROFILE_UNDO.map((line) => ` ${line}`),
103
+ ];
104
+
105
+ /** bubblewrap is installed and this host refused it a sandbox. */
106
+ export const bwrapRefusedMessage = (adapterName, { reason, apparmorRestricted, ubuntuRelease }) => {
107
+ const label = ADAPTER_LABELS[adapterName] || adapterName;
108
+ // 24.04 only: the file moves or is absent on other releases.
109
+ const offersProfile = apparmorRestricted === true && ubuntuRelease === '24.04'
110
+ && (adapterName === 'claude' || adapterName === 'codex');
111
+ return [
112
+ `A connected ${label} runs inside a bubblewrap sandbox, and this machine won't let bubblewrap start one (${reason}).`,
113
+ ...(apparmorRestricted === true
114
+ ? ['AppArmor on Ubuntu 24.04 and later restricts the user namespaces bubblewrap needs.']
115
+ : []),
116
+ 'So this agent cannot listen for @mentions here yet. You can:',
117
+ HOSTED_LINE,
118
+ ...(adapterName === 'claude' ? [CLAUDE_MCP_LINE] : []),
119
+ ...(offersProfile ? UBUNTU_BWRAP_PROFILE_LINES : []),
120
+ ].join('\n');
121
+ };
122
+
70
123
  /** What a person on native Windows can do instead. */
71
124
  export const windowsSandboxMessage = (adapterName) => {
72
125
  if (adapterName === 'codex') return CODEX_WINDOWS_MESSAGE;
@@ -106,12 +159,19 @@ export const hostSandboxRefusal = ({
106
159
  detectSeatbelt = defaultDetectSeatbelt,
107
160
  } = {}) => {
108
161
  if (adapterName === 'codex') {
109
- if (platform !== 'win32') return null;
110
162
  // Keyed on trust, not mode: Codex resolves no Seatbelt or bwrap mode of its
111
163
  // own, and a legacy `internal` normalizes to public. Workspace trust is
112
164
  // left to Codex's own refusal, at attach and at spawn on every platform,
113
165
  // so WSL advice would only send that seat to a second refusal.
114
166
  const trust = normalizeSandboxTrust(environment?.sandbox)?.trust;
167
+ if (platform === 'linux' && trust === 'public') {
168
+ // Codex's own sandbox uses bubblewrap here. Refused a namespace, every
169
+ // turn dies at session start and the pod hears nothing (run 42398478814).
170
+ // A missing bwrap stays Codex's own to report.
171
+ const bwrap = detectBwrap();
172
+ return bwrap.namespaceRefused === true ? bwrapRefusedMessage(adapterName, bwrap) : null;
173
+ }
174
+ if (platform !== 'win32') return null;
115
175
  if (trust === 'workspace') return null;
116
176
  if (trust === 'public') return optedIn === true ? CODEX_WINDOWS_PUBLIC_MESSAGE : CODEX_WINDOWS_MESSAGE;
117
177
  // No public trust: `agent run` removed the block for this run after
@@ -133,7 +193,10 @@ export const hostSandboxRefusal = ({
133
193
  }
134
194
  if (mode === 'bwrap') {
135
195
  const bwrap = detectBwrap();
136
- return bwrap.available ? null : `This seat runs in a bubblewrap sandbox, which is not available here. ${bwrap.error}`;
196
+ if (bwrap.available) return null;
197
+ return bwrap.namespaceRefused === true
198
+ ? bwrapRefusedMessage(adapterName, bwrap)
199
+ : `This seat runs in a bubblewrap sandbox, which is not available here. ${bwrap.error}`;
137
200
  }
138
201
  const seatbelt = detectSeatbelt();
139
202
  return seatbelt.available
@@ -75,6 +75,11 @@ export const SPAWN_RETRY_JITTER_MAX_RATIO = 0.2;
75
75
  // nothing else until the kernel retired the event. Only the refusal wordings
76
76
  // themselves are matched, so an ordinary failure that mentions a flag is not.
77
77
  const CONTENT_REFUSED_RE = /(?:flagged for possible cybersecurity risk|this content was flagged|content[_ ]policy[_ ]violation|cyber[_ ]policy)/i;
78
+ // pi writes its own line for a provider's content stop (pi-ai 0.84.1:
79
+ // openai-completions.js, anthropic-messages.js) as the whole errorMessage, so
80
+ // only the pi failure that IS that line matches. Anywhere else the wording is
81
+ // text someone wrote, such as a seat quoting this file, and a match is terminal.
82
+ const PI_CONTENT_STOP_RE = /^pi exited with code \d+(?: \(upstream \d+\))?: Provider (?:finish_reason: content_filter|stopped with: sensitive)$/;
78
83
  // The third miss is why there is now a PHRASE as well as a word list, and it is
79
84
  // a different failure from the first two. Measured across the fleet's logs on
80
85
  // 2026-08-25: 283 failures reading "You've hit your weekly limit", 55 reading
@@ -153,7 +158,9 @@ export const classifySpawnFailure = (error) => {
153
158
  if (error?.code === PUBLIC_CODEX_VERSION_CODE) return SPAWN_FAILURE_CLASS.CONFIGURATION;
154
159
  // First: the refusal text carries none of the words below today, but a
155
160
  // refusal must never be read as a transient condition and retried.
156
- if (CONTENT_REFUSED_RE.test(text)) return SPAWN_FAILURE_CLASS.CONTENT_REFUSED;
161
+ if (CONTENT_REFUSED_RE.test(text) || PI_CONTENT_STOP_RE.test(String(error?.message || '').trim())) {
162
+ return SPAWN_FAILURE_CLASS.CONTENT_REFUSED;
163
+ }
157
164
  if (error?.code === 'spawn_stalled') return SPAWN_FAILURE_CLASS.STALLED;
158
165
  // Provider APIs commonly report an exhausted account quota as HTTP 429.
159
166
  // Prefer the more specific body/message over the generic status code so a
@@ -42,9 +42,11 @@ const WONT_START_WORDINGS = [
42
42
  // The vendors' credit wordings open at the adapter's own label or the claude
43
43
  // adapter's stderr | stdout join, because any `: ` or status number can open a
44
44
  // log line. An unknown label stays silent. `upstream refused` is the line the run
45
- // loop builds for pi. The transports are how a CLI wraps a refusal it keeps whole.
45
+ // loop builds for pi, and the pi adapter puts its label before it when a refused
46
+ // turn exits 0 after an interim message (F320). The transports are how a CLI
47
+ // wraps a refusal it keeps whole.
46
48
  const ADAPTER_LABEL = String.raw`(?:claude|codex|pi|opencode|goose|qwen|dsh|Hermes)(?: turn failed)?(?: exited(?: with code)? \d+)?(?: \(upstream \d{3}\))?`;
47
- const OWN_LEAD = String.raw`(?:^(?:${ADAPTER_LABEL}|upstream refused \d{3}): | \| )`;
49
+ const OWN_LEAD = String.raw`(?:^(?:${ADAPTER_LABEL}(?:: upstream refused \d{3})?|upstream refused \d{3}): | \| )`;
48
50
  const TRANSPORT = String.raw`(?:unexpected status \d{3}[^:\n]*: |API Error: \d{3} |Error code: \d{3} - |Error running remote compact task: )*`;
49
51
  const OPENAI_CODE = '(?:insufficient_quota|credit_balance_exhausted)';
50
52
  const ownWording = (wording) => new RegExp(`${OWN_LEAD}${TRANSPORT}${wording}`);