@commonlyai/cli 0.1.282 → 0.1.284

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.282",
3
+ "version": "0.1.284",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -105,7 +105,7 @@ import { detectBwrap } from '../lib/sandbox/bwrap.js';
105
105
  import { resolvePublicSandboxMode } from '../lib/sandbox/mode.js';
106
106
  import { UNSANDBOXED_FLAG, hostSandboxRefusal, windowsSandboxMessage } from '../lib/sandbox/host-check.js';
107
107
  import {
108
- CODEX_UNSANDBOXED_NOTICE, UNSANDBOXED_NOTICE, codexUnconfinedForRun, hostUnconfinedForRun, runOptedInUnsandboxed,
108
+ CODEX_UNSANDBOXED_NOTICE, UNSANDBOXED_NOTICE, codexUnconfinedForRun, hostReportFailureMessage, hostUnconfinedForRun, runOptedInUnsandboxed,
109
109
  unsandboxedFlagRefusal,
110
110
  } from '../lib/sandbox/windows-unsandboxed.js';
111
111
  import { prepareMcpBeforeFirstPoll } from '../lib/mcp-first-run.js';
@@ -1093,6 +1093,17 @@ export const setWakeOnMessage = async ({ client, record, enabled }) => {
1093
1093
  return { agentName: record.agentName, podId: record.podId, instanceId, enabled: Boolean(enabled) };
1094
1094
  };
1095
1095
 
1096
+ /** Lift the mark an unsandboxed run left on the seat. Only its owner's login can. */
1097
+ export const clearUnsandboxedMark = async ({ client, record }) => {
1098
+ if (!record?.podId || !record?.agentName) {
1099
+ throw new Error('token record is missing podId/agentName — re-attach the agent');
1100
+ }
1101
+ const instanceId = record.instanceId || 'default';
1102
+ const path = `/api/registry/pods/${encodeURIComponent(record.podId)}/agents/${encodeURIComponent(record.agentName)}/host-unconfined`;
1103
+ const result = await client.del(`${path}?instanceId=${encodeURIComponent(instanceId)}`);
1104
+ return { agentName: record.agentName, machineUnconfined: result?.machineUnconfined === true };
1105
+ };
1106
+
1096
1107
  /**
1097
1108
  * Update the server-side configuration for an existing local agent. The
1098
1109
  * registry PATCH route already fans this change out to accessible pod peers;
@@ -5252,7 +5263,7 @@ Docs:
5252
5263
  try {
5253
5264
  await seatClient.post('/api/agents/runtime/host-unconfined', {});
5254
5265
  } catch (err) {
5255
- console.error(`${stamp()} [${name}] could not tell the server this agent has no sandbox, so it did not start: ${err.message}`);
5266
+ console.error(`${stamp()} [${name}] ${hostReportFailureMessage(err)}`);
5256
5267
  process.exit(1);
5257
5268
  }
5258
5269
  }
@@ -5706,6 +5717,31 @@ Use --local to find the name you'd pass to 'agent run' or 'agent detach'.
5706
5717
  }
5707
5718
  });
5708
5719
 
5720
+ // ── clear-unsandboxed ─────────────────────────────────────────────────────
5721
+ agent
5722
+ .command('clear-unsandboxed <name>')
5723
+ .description('After moving an agent to a sandboxed host, let it use grants again (needs your login, not its token)')
5724
+ .option('--instance <url>', 'Target Commonly instance')
5725
+ .action(async (name, opts) => {
5726
+ const record = loadAgentToken(name);
5727
+ if (!record) {
5728
+ console.error(`No token file for '${name}' — is it attached on this machine? (commonly agent list --local)`);
5729
+ process.exit(1);
5730
+ }
5731
+ const instanceUrl = resolveInstanceUrl(opts.instance || record.instanceUrl);
5732
+ const token = getToken(opts.instance || record.instanceUrl);
5733
+ if (!token) { console.error('Not logged in. Run: commonly login'); process.exit(1); }
5734
+ const client = createClient({ instance: instanceUrl, token });
5735
+ try {
5736
+ const result = await clearUnsandboxedMark({ client, record });
5737
+ console.log(`✓ Cleared for ${result.agentName}. Running it with --unsandboxed marks it again.`);
5738
+ if (result.machineUnconfined) console.log(' Its machine reports no sandbox, so grants stay refused while it runs there.');
5739
+ } catch (err) {
5740
+ console.error(`Failed: ${err.message}`);
5741
+ process.exit(1);
5742
+ }
5743
+ });
5744
+
5709
5745
  // ── heartbeat ─────────────────────────────────────────────────────────────
5710
5746
  agent
5711
5747
  .command('heartbeat <name>')
@@ -895,20 +895,31 @@ const turnReply = (stdout, { credentials, publicMcp }) => {
895
895
  return redactKnownCredentials(claudeResultText(stdout, { credentials }), credentials);
896
896
  };
897
897
 
898
- // The failure tail for a non-zero exit. Stream events are mostly system init
899
- // and status lines, which would push the terminal error past the 2000-char cut,
900
- // so keep the result text, or the lines that are not system or stream events.
898
+ // A line of stdout the CLI wrote as a failure, not as part of the turn's stream:
899
+ // prose, or an API body printed whole. A keep-list, because a typed event holds
900
+ // the model's words or a tool's. Unparsed text opening like an event is the last
901
+ // one, torn by the crash.
902
+ const isCliFailureLine = (line, event) => (event
903
+ ? event.type === undefined || event.type === 'error'
904
+ : !line.trimStart().startsWith('{"'));
905
+
906
+ // The failure tail for a non-zero exit. The status scan, the failure class and
907
+ // the pod's notice all read this text, so it holds only the CLI's own words: a
908
+ // tool result quoting `| 429: ` once named the turn's status and cut the body
909
+ // past the JSON it sat in (F235). So the result text counts only when flagged
910
+ // is_error. At is_error false it's the model's answer, and a crash after it says
911
+ // nothing about the provider. A failed result with no text keeps its subtype.
912
+ // The cost: a crash with no result event loses a synthetic API-error assistant
913
+ // event, so it classes runtime, and the seat log loses the turn's last lines.
901
914
  export const claudeFailureTail = (stdout) => {
902
- const text = String(stdout || '');
903
- const lines = text.split('\n');
915
+ const lines = String(stdout || '').split('\n');
904
916
  const events = lines.map(parseEvent);
905
- if (!events.some(Boolean)) return text.trim();
906
917
  const result = [...events].reverse().find((event) => event?.type === 'result');
907
- if (String(result?.result ?? '').trim()) return String(result.result).trim();
908
- return lines
909
- .filter((_, i) => !['system', 'stream_event'].includes(events[i]?.type))
910
- .join('\n')
911
- .trim();
918
+ const failed = result?.is_error === true;
919
+ if (failed && String(result.result ?? '').trim()) return String(result.result).trim();
920
+ const subtype = failed && /^\w{1,40}$/.test(result.subtype) ? result.subtype : '';
921
+ const prose = lines.filter((line, i) => isCliFailureLine(line, events[i])).join('\n').trim();
922
+ return [prose, subtype].filter(Boolean).join('\n');
912
923
  };
913
924
 
914
925
  const runClaude = ({
@@ -142,6 +142,14 @@ export const UNSANDBOXED_NOTICE = 'unsandboxed (opted in): Windows has no sandbo
142
142
  /** Codex has no restricted tool settings to keep, so its line says what it costs instead. */
143
143
  export const CODEX_UNSANDBOXED_NOTICE = 'unsandboxed (opted in): Windows has no sandbox Codex can use here, so nothing confines this agent. It runs with your own access to files and commands, and anyone in its pods, people invited later included, can direct it. It gets no connector grants, and a turn is refused if a pod stops being invite-only.';
144
144
 
145
+ // A 404 here is a server from before this route, which reads like a missing agent.
146
+ export const hostReportFailureMessage = (err) => {
147
+ const hint = err?.status === 404
148
+ ? '. This server is older than this CLI: update the server, or run the agent in a sandbox.'
149
+ : '';
150
+ return `could not tell the server this agent has no sandbox, so it did not start: ${err?.message}${hint}`;
151
+ };
152
+
145
153
  export default {
146
154
  CODEX_UNSANDBOXED_NOTICE,
147
155
  UNSANDBOXED_FLAG,
@@ -110,7 +110,14 @@ const CONTENT_REFUSED_RE = /(?:flagged for possible cybersecurity risk|this cont
110
110
  // "thinking budget has been exceeded" stays out. Unmatched, the 422 is RUNTIME
111
111
  // and the seat respawns every few seconds against a key that stays refused.
112
112
  export const GATEWAY_BUDGET_RE = /Budget has been exceeded!|crossed budget/;
113
- const QUOTA_RE = /(?:quota|usage limit|session limit|weekly limit|credit balance|out of credits|billing|insufficient[_ -]?quota|resource exhausted|spending limit)/i;
113
+ // `credit_balance_exhausted` is OpenAI's code for a prepaid balance at zero, sent
114
+ // as a 429. `credit balance` has a space, so it needs its own entry. OpenAI:
115
+ // "Retrying billing, spend, or quota errors won't restore API access."
116
+ // This reaches the code only while it's in the text, as a bare code or a body
117
+ // kept whole. A body the keep-list reduces keeps its message and moves the code
118
+ // to `error.providerCode`, which isn't read here because it can come from a
119
+ // tool's JSON. That refusal stays RATE_LIMIT and probes in 60 seconds.
120
+ const QUOTA_RE = /(?:quota|usage limit|session limit|weekly limit|credit balance|credit_balance_exhausted|out of credits|billing|insufficient[_ -]?quota|resource exhausted|spending limit)/i;
114
121
  const QUOTA_POSSESSIVE_RE = /you'?ve (?:hit|reached) your (?!rate[ -]?limit)(?:[^.\n]|\.(?=\d)){0,40}?limit/i;
115
122
  // The status code is not a throttle wording: "429: You've reached your Fable 5
116
123
  // limit" is an exhausted allowance that a provider reports as HTTP 429.
@@ -11,9 +11,9 @@
11
11
  * The failure classes in spawn-retry.js are too loose for this. They only pick a
12
12
  * backoff, so a stray "401" or "billing" in a stack trace costs a slower retry.
13
13
  * Here the match becomes a statement to a person, so each line below fires only
14
- * on a wording a seat has logged, a walk has produced, or the wrapper or our own
15
- * gateway config writes. A failure that matches none of them posts nothing,
16
- * which is what it did before.
14
+ * on a wording a seat has logged, a walk has produced, a vendor publishes, or
15
+ * the wrapper or our own gateway config writes. A failure that matches none of
16
+ * them posts nothing, which is what it did before.
17
17
  */
18
18
  import { PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from './public-tool-error.js';
19
19
  import { PUBLIC_CODEX_VERSION_CODE } from './adapters/tested-version.js';
@@ -39,11 +39,34 @@ const WONT_START_WORDINGS = [
39
39
  /^spawn \S+ ENOENT/,
40
40
  /^\w+ adapter: \S+ (?:is not set|is missing)/, // the seat has no provider key
41
41
  ];
42
+ // The vendors' credit wordings open at the adapter's own label or the claude
43
+ // adapter's stderr | stdout join, because any `: ` or status number can open a
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.
46
+ 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}): | \| )`;
48
+ const TRANSPORT = String.raw`(?:unexpected status \d{3}[^:\n]*: |API Error: \d{3} |Error code: \d{3} - |Error running remote compact task: )*`;
49
+ const OPENAI_CODE = '(?:insufficient_quota|credit_balance_exhausted)';
50
+ const ownWording = (wording) => new RegExp(`${OWN_LEAD}${TRANSPORT}${wording}`);
51
+
42
52
  // Not the whole of QUOTA_RE, which also holds "billing" and "quota" for backoff.
43
53
  const OUT_OF_ALLOWANCE_WORDINGS = [
44
54
  /(?:^|: | \| )you['’]?ve (?:hit|reached) your [^\n]{0,40}?limit/i,
45
55
  /\bout of credits\b/i,
46
56
  GATEWAY_BUDGET_RE,
57
+ // An API key with no credit left, in the vendors' published text, case-sensitive.
58
+ // OpenAI's API (openai-cookbook error-codes, codex tests/suite/quota_exceeded.rs).
59
+ ownWording('You exceeded your current quota, please check your plan and billing details'),
60
+ // codex-rs source maps insufficient_quota, credit_balance_exhausted and the
61
+ // spend-limit codes to this text (CodexErr::QuotaExceeded). Not run on a binary.
62
+ ownWording(String.raw`Quota exceeded\. Check your plan and billing details`),
63
+ // OpenAI's error.type and error.code (guides/error-codes): bare, or in a body kept whole.
64
+ ownWording(String.raw`(?:\d{3} )?${OPENAI_CODE}\b`),
65
+ ownWording(String.raw`\{['"]error['"]: ?\{[^{}\n]{0,400}?['"](?:code|type)['"]: ?['"]${OPENAI_CODE}['"]`),
66
+ // Anthropic's API (about-claude/api-credits-for-subscribers): reduced, or in its body.
67
+ ownWording(String.raw`(?:\{"type":"error","error":\{"type":"invalid_request_error","message":")?Your credit balance is too low to access the Anthropic API`),
68
+ // Claude Code: the same page, and its errors page.
69
+ ownWording(String.raw`Credit balance (?:is )?too low(?: ·| \||\n|$)`),
47
70
  ];
48
71
 
49
72
  const AGAIN = 'After that, send your message again if I still haven’t answered.';
@@ -75,8 +98,8 @@ export const cantAnswerNotice = (error) => {
75
98
  if (error?.code === PUBLIC_CODEX_VERSION_CODE) {
76
99
  return { cause: 'codex-version', text: codexVersionNotice(error.requiredVersion) };
77
100
  }
78
- // A crashed claude turn keeps assistant and tool JSON lines in its tail, and
79
- // those are the model's words, or a tool's.
101
+ // claudeFailureTail drops tool and assistant JSON. This cut is for what can
102
+ // still arrive: a torn stream line, or an error event after stderr.
80
103
  const text = String(error?.message ?? '').split(/(?:^|: | \| |\n)\{"type":/)[0];
81
104
  // Before the allowance check: a 401 is settled, whatever else its body says.
82
105
  if (matches(LOGIN_FAILED_WORDINGS, text)) return { cause: 'login', text: LOGIN_NOTICE };