@phantomcodes/cli 1.5.0 → 1.6.0

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/README.md CHANGED
@@ -28,7 +28,7 @@ It also installs the `phantom-ai` skill, a file that teaches the agent the phant
28
28
  - `phantom setup --dry-run` shows the changes and writes nothing.
29
29
  - `--no-shell`, or unticking "Your shell" in the checklist, leaves your shell startup file alone. Setup then prints the lines to add yourself.
30
30
  - `--limit 20` caps what the key can spend each month, and `--limit none` removes the cap. At a terminal, setup asks once when the key has no cap.
31
- - `phantom setup --restore` puts back each file setup changed, from the copies it kept. A file you edited after setup keeps your edits: restore takes out only Phantom's own lines and keys, and leaves the copy beside the file. It exits 1 only when a file could not be undone.
31
+ - `phantom setup --restore` puts back each file setup changed, from the copies it kept. A file you edited after setup keeps your edits: restore takes out only Phantom's own lines and keys, and leaves the copy beside the file. Restore also removes the `settings.json.bak` copy that setup makes for Claude Code and Gemini, unless a `.bak` was already there before setup or you changed it since. It exits 1 only when a file could not be undone.
32
32
  - `phantom setup --provider off` takes Phantom out of an agent and keeps the rest of its settings. In JSON settings files (Claude Code, Qwen Code, Gemini CLI and others), setup records each value it replaces and puts it back.
33
33
 
34
34
  Claude Code's background calls (titles, summaries and its Explore agent) run on the model you chose with `phantom models`, so picking `phantom-1:zdr` covers them too.
@@ -80,7 +80,7 @@ phantom fund --amount 10 --card
80
80
  phantom fund --amount 10 --coin usdc
81
81
  ```
82
82
 
83
- `--card` opens Stripe Checkout, where the total includes Stripe's card fee. `--coin usdc` pays in USDC on Solana, and `--coin usdc-base` pays in USDC on Base. The credit appears once Stripe confirms the payment. Check it with `phantom balance`.
83
+ `--card` opens Stripe Checkout, where the total includes Stripe's card fee. `--coin usdc` pays in USDC on Solana, and `--coin usdc-base` pays in USDC on Base. Pick one of `--card` and `--coin`. Card payments take $5 to $10,000, USDC on Solana $0.10 to $10,000 and USDC on Base $1 to $10,000. A wallet payment link is good for 30 minutes. The credit appears once Stripe confirms the payment. Check it with `phantom balance`.
84
84
 
85
85
  ## Give each agent its own key and cap
86
86
 
@@ -175,7 +175,7 @@ At a terminal, commands draw a screen, and choices are pickers (arrow keys, Ente
175
175
 
176
176
  `phantom claude`, `phantom codex` and `phantom pi` run in your terminal and print a spending summary on stderr when the agent exits.
177
177
 
178
- Exit codes: 0 for success (and for Esc), 1 for an error, 2 for a rejected key, 130 for Ctrl+C. `phantom setup` returns 1 when it could only install the skills because there was no key yet (`"complete": false`). An agent run returns the agent's exit code.
178
+ Exit codes: 0 for success (and for Esc), 1 for an error, 2 for a rejected key (including `phantom balance` on a key that was revoked or has expired), 130 for Ctrl+C. `phantom setup` returns 1 when it could only install the skills because there was no key yet (`"complete": false`). An agent run returns the agent's exit code.
179
179
 
180
180
  <details>
181
181
  <summary><strong>Advanced and older commands</strong></summary>
@@ -46,7 +46,9 @@ export const AGENTS = {
46
46
  const { ANTHROPIC_AUTH_TOKEN: _auth, ...rest } = withoutPhantomKeys(env);
47
47
  return {
48
48
  args: ['--settings', JSON.stringify({ apiKeyHelper: helper, env: vars }), ...args],
49
- env: { ...rest, ...model, ANTHROPIC_BASE_URL: proxy, ANTHROPIC_API_KEY: token, PHANTOM_AGENT_TOKEN: token },
49
+ // Claude Code does not know the model `claude-code/phantom-1`, so it warns and guesses a window. Phantom's
50
+ // models take about a million tokens, which is what it guesses; this says so and ends the warning. A window the user set stays theirs.
51
+ env: { ...rest, ...model, ...(env.CLAUDE_CODE_MAX_CONTEXT_TOKENS ? {} : { CLAUDE_CODE_MAX_CONTEXT_TOKENS: '1048576' }), ANTHROPIC_BASE_URL: proxy, ANTHROPIC_API_KEY: token, PHANTOM_AGENT_TOKEN: token },
50
52
  };
51
53
  },
52
54
  },
@@ -57,7 +57,8 @@ export const COMMANDS = [
57
57
  workspace import --file <path> sign in to a guest workspace from its recovery
58
58
  file, then make a key with phantom keys create
59
59
  workspace revoke-access --id <id> stop a browser, device or recovery file from
60
- managing the workspace
60
+ managing the workspace; the start of the id
61
+ (4 or more characters) is enough
61
62
  workspace delete [--yes] delete an empty workspace and forget it here
62
63
  (--yes: don't ask)`,
63
64
  },
@@ -67,7 +68,8 @@ export const COMMANDS = [
67
68
  help: ` fund --amount <USD> [--card | --coin usdc|usdc-base] [--no-browser]
68
69
  add credit to your workspace by card (plus
69
70
  Stripe's fee), or USDC on Solana (usdc) or Base
70
- (usdc-base); --no-browser prints the link`,
71
+ (usdc-base); pick one of --card and --coin;
72
+ --no-browser prints the link`,
71
73
  },
72
74
  {
73
75
  name: 'keys', handler: workspaceCommand, keyless: true,
@@ -225,7 +227,9 @@ export const COMMANDS = [
225
227
  setup --restore [--agent <name>] put back the files setup changed, from the
226
228
  .phantom.bak copies it kept. A file you
227
229
  edited since keeps your edits: only
228
- Phantom's own lines come out`,
230
+ Phantom's own lines come out. It also
231
+ removes the settings.json.bak copy setup
232
+ made for Claude Code and Gemini`,
229
233
  },
230
234
  {
231
235
  name: 'verify', advanced: true, handler: verifyCommand, keyless: ['--receipt'],
@@ -43,6 +43,13 @@ export type WorkspaceView = {
43
43
  held_usd?: number;
44
44
  account_linked?: boolean;
45
45
  keys: WorkspaceKey[];
46
+ /** The sign-ins that can manage the workspace: a browser, a device, a recovery file. */
47
+ access?: Array<{
48
+ id: string;
49
+ kind?: string;
50
+ created_at?: string;
51
+ expires_at?: string | null;
52
+ }>;
46
53
  charges?: Array<{
47
54
  model?: string;
48
55
  cost_usd?: number;
@@ -1,4 +1,5 @@
1
1
  import { paint } from "../core/style.mjs";
2
+ import { reasonInWords } from "../spend/reason.mjs";
2
3
  import { JOBS } from "../models/list.mjs";
3
4
  import { FREE_AGENT_REQUESTS_A_DAY, FREE_REQUESTS_A_DAY } from "../core/free.mjs";
4
5
  /** The window's width: given, or the terminal's, or 100 for a pipe. */
@@ -40,6 +41,16 @@ export function bar(p, share, width, fill) {
40
41
  const shown = share > 0 && cells === 0 ? 1 : cells;
41
42
  return fill('━'.repeat(shown)) + p.dim('─'.repeat(width - shown));
42
43
  }
44
+ /** A moment as `Nov 13, 2026, 4:29 PM EST`, in this computer's time zone, or the text as given when it isn't one. */
45
+ function dayAndTime(iso) {
46
+ const d = new Date(iso);
47
+ if (Number.isNaN(d.getTime()))
48
+ return iso;
49
+ const date = d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
50
+ // Newer ICU puts a narrow no-break space before AM and PM; a plain space copies and wraps better.
51
+ const time = d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', timeZoneName: 'short' }).replace(/\u202f/g, ' ');
52
+ return `${date}, ${time}`;
53
+ }
43
54
  /** A date as `Nov 1, 2026`, read as UTC, or the text as given when it isn't one. */
44
55
  function day(iso) {
45
56
  const d = new Date(iso.length === 10 ? `${iso}T00:00:00Z` : iso);
@@ -61,11 +72,11 @@ export function balanceScreen(b, style = {}) {
61
72
  lines.push(` ${p.dim('expires'.padEnd(10))}${day(b.expires_at)}`);
62
73
  if (!b.active)
63
74
  lines.push('', ` ${p.red('✗')} This key is switched off or past its expiry.`);
64
- if (b.credit_balance_usd <= 0) {
75
+ if (b.active && b.credit_balance_usd <= 0) {
65
76
  lines.push('', ` ${p.lime('✓')} phantom-1 still runs on free models while you have no credit.`);
66
77
  lines.push(...next(p, 'Add credit:', 'phantom fund --amount 10 --card'));
67
78
  }
68
- else {
79
+ else if (b.active) {
69
80
  lines.push(...next(p, 'See what it went on:', 'phantom spend'));
70
81
  }
71
82
  return lines.join('\n');
@@ -142,6 +153,17 @@ export function workspaceScreen(view, style = {}) {
142
153
  const lines = ['', ...caption(p, w, 'WORKSPACE', p.dim(`${view.name ?? ''}${view.account_linked ? ' · signed-in account' : ' · guest'}`))];
143
154
  lines.push(` ${p.bold(usd(view.balance_usd))} ${p.dim('shared balance')}${view.held_usd ? p.dim(` ${usd(view.held_usd)} held for requests running now`) : ''}`);
144
155
  lines.push('', ...caption(p, w, 'KEYS', p.dim(String(view.keys.length))), ...keyRows(p, view.keys));
156
+ const access = view.access ?? [];
157
+ if (access.length) {
158
+ // What each kind is, in words: a "session" is a browser sign-in, a "device" is phantom login on a computer.
159
+ const kinds = { session: 'browser', device: 'device', recovery: 'recovery file' };
160
+ lines.push('', ...caption(p, w, 'SIGN-INS', p.dim(String(access.length))));
161
+ for (const a of access) {
162
+ const ends = a.expires_at ? `expires ${day(a.expires_at)}` : 'never expires';
163
+ lines.push(` ${(kinds[a.kind ?? ''] ?? a.kind ?? 'sign-in').padEnd(14)}${p.dim(a.id.slice(0, 8).padEnd(10))}${p.dim(`${a.created_at ? `since ${day(a.created_at)} ` : ''}${ends}`)}`);
164
+ }
165
+ lines.push(` ${p.dim('Stop one with')} ${p.cyan('phantom workspace revoke-access --id <id>')}`);
166
+ }
145
167
  const charges = (view.charges ?? []).slice(0, 5);
146
168
  if (charges.length) {
147
169
  lines.push('', ...caption(p, w, 'LATEST CALLS'));
@@ -222,7 +244,7 @@ export function routeTestScreen(t, style = {}) {
222
244
  if (!t.model)
223
245
  lines.push(` ${p.red('✗')} A request now would be refused: this key's cap is used up.`);
224
246
  else
225
- lines.push(` ${p.lime('→')} A request now would run on ${p.bold(t.model)}`, ` ${p.dim(t.routed === false ? 'it names its own model, so the route policy is not used' : `because: ${t.reason ?? 'default'}`)}`);
247
+ lines.push(` ${p.lime('→')} A request now would run on ${p.bold(t.model)}`, ` ${p.dim(t.routed === false ? 'it names its own model, so the route policy is not used' : `because: ${reasonInWords(t.reason ?? 'default')}`)}`);
226
248
  if (t.fallbacks?.length)
227
249
  lines.push(` ${p.dim(`then, if it fails: ${t.fallbacks.join(', ')}`)}`);
228
250
  return lines.join('\n');
@@ -266,7 +288,7 @@ export function fundScreen(f, style = {}) {
266
288
  }
267
289
  const p = paint(style.env ?? {}, Boolean(style.color));
268
290
  const w = ruleWidth(style);
269
- return [linkScreen(`Pay ${f.amount ?? ''} ${(f.coin ?? '').toUpperCase()} from your wallet`.replace(/\s+/g, ' '), f.payment_url ?? f.solana_pay_url ?? '', null, style), ` ${p.dim('payment')} ${f.payment_id ?? ''}${f.expires_at ? p.dim(` · good until ${day(f.expires_at)}`) : ''}`, ...next(p, 'See whether it arrived:', `phantom workspace payment --id ${f.payment_id ?? '<id>'}`)].join('\n');
291
+ return [linkScreen(`Pay ${f.amount ?? ''} ${(f.coin ?? '').toUpperCase()} from your wallet`.replace(/\s+/g, ' '), f.payment_url ?? f.solana_pay_url ?? '', null, style), ` ${p.dim('payment')} ${f.payment_id ?? ''}${f.expires_at ? p.dim(` · good until ${dayAndTime(f.expires_at)}`) : ''}`, ...next(p, 'See whether it arrived:', `phantom workspace payment --id ${f.payment_id ?? '<id>'}`)].join('\n');
270
292
  }
271
293
  /** `phantom workspace payment`: whether a payment has come in. */
272
294
  export function paymentScreen(pay, style = {}) {
@@ -33,11 +33,11 @@ export declare function parseFlags(args: string[]): Record<string, string | true
33
33
  */
34
34
  export declare function flagNum(flags: Record<string, string | true>, name: string): number | undefined;
35
35
  /**
36
- * A spending control's value for a key: a number of zero or more, `none` for no limit (null), or
36
+ * A spending control's value for a key: a number above zero, `none` for no limit (null), or
37
37
  * undefined when the flag is absent. A mistyped value stops the command, because a number that
38
38
  * silently became "no limit" would remove the key's cap.
39
39
  * @param dollars True for money flags, which may start with `$`.
40
- * @throws {@link CliError} `key_usage` when the flag has no value, or the value is not a finite number of zero or more.
40
+ * @throws {@link CliError} `key_usage` when the flag has no value, or the value is not a finite number above zero. The server refuses 0 for every one of these, and `setup --limit` does too.
41
41
  */
42
42
  export declare function limitFlag(flags: Record<string, string | true>, name: string, dollars?: boolean): number | null | undefined;
43
43
  /** Opens a URL in the user's default browser. */
@@ -47,8 +47,9 @@ export function handleError(err, stderr = (s) => process.stderr.write(s), opts =
47
47
  // A person at a terminal reads a sentence; the code stays for support, dimmed.
48
48
  const p = paint(opts.env ?? {}, colorOn(opts.env ?? {}, true));
49
49
  const lit = message.replace(COMMAND_IN_TEXT, (cmd) => p.cyan(cmd));
50
- // The code only when it says more than "an error": HTTP 401, invalid_key helps support; cli_error doesn't.
51
- const detail = api ? `HTTP ${api.status}, ${code}` : code === 'cli_error' || code === 'unknown' ? '' : code;
50
+ // The server's answer keeps its status and code for support (HTTP 401, invalid_key). The CLI's own
51
+ // errors already say what happened in the sentence, and their code is for scripts, which get it as JSON.
52
+ const detail = api ? `HTTP ${api.status}, ${code}` : '';
52
53
  stderr(`\n ${p.red('✗')} ${lit}\n${detail ? p.dim(` ${detail}`) + '\n' : ''}\n`);
53
54
  }
54
55
  else {
@@ -99,11 +100,11 @@ export function flagNum(flags, name) {
99
100
  return n;
100
101
  }
101
102
  /**
102
- * A spending control's value for a key: a number of zero or more, `none` for no limit (null), or
103
+ * A spending control's value for a key: a number above zero, `none` for no limit (null), or
103
104
  * undefined when the flag is absent. A mistyped value stops the command, because a number that
104
105
  * silently became "no limit" would remove the key's cap.
105
106
  * @param dollars True for money flags, which may start with `$`.
106
- * @throws {@link CliError} `key_usage` when the flag has no value, or the value is not a finite number of zero or more.
107
+ * @throws {@link CliError} `key_usage` when the flag has no value, or the value is not a finite number above zero. The server refuses 0 for every one of these, and `setup --limit` does too.
107
108
  */
108
109
  export function limitFlag(flags, name, dollars = false) {
109
110
  const raw = flags[name];
@@ -116,8 +117,8 @@ export function limitFlag(flags, name, dollars = false) {
116
117
  if (text === 'none')
117
118
  return null;
118
119
  const n = text === '' ? NaN : Number(dollars ? text.replace(/^\$/, '') : text);
119
- if (!Number.isFinite(n) || n < 0)
120
- die(`--${name} must be ${dollars ? 'a number of dollars' : 'a number'} (0 or more) or none, such as ${example}. You gave "${raw}".`, 'key_usage');
120
+ if (!Number.isFinite(n) || n <= 0)
121
+ die(`--${name} must be ${dollars ? 'a number of dollars' : 'a number'} above 0, or none, such as ${example}. You gave "${raw}".`, 'key_usage');
121
122
  return n;
122
123
  }
123
124
  /** Opens a URL in the user's default browser. */
@@ -119,6 +119,16 @@ export function httpsOnly(baseUrl) {
119
119
  }
120
120
  return baseUrl;
121
121
  }
122
+ /**
123
+ * Sentences for the bare code words some routes answer with (`{ "error": "invalid_key" }`), which say
124
+ * nothing about what to do. The code stays on the error for scripts.
125
+ */
126
+ const CODE_SENTENCES = {
127
+ invalid_key: 'Phantom AI does not accept this key. It may be mistyped, revoked or expired. Check the key, or run phantom login to sign in again.',
128
+ access_denied: 'The sign-in was declined in the browser. Run phantom login to try again.',
129
+ expired_token: 'The sign-in code expired. Run phantom login again.',
130
+ invalid_grant: 'The sign-in code was not accepted. Run phantom login again.',
131
+ };
122
132
  export function apiError(status, json) {
123
133
  json = json && typeof json === 'object' ? json : {};
124
134
  const err = json.error;
@@ -132,7 +142,7 @@ export function apiError(status, json) {
132
142
  else if (typeof err === 'string') {
133
143
  // Some routes answer { error: <words> }; a detail, when one is sent, reads better.
134
144
  const detail = json.detail;
135
- msg = typeof detail === 'string' && detail ? detail : err;
145
+ msg = typeof detail === 'string' && detail ? detail : (CODE_SENTENCES[err] ?? err);
136
146
  // A code word such as `invalid_key` is the code. A sentence is the message only: its code is made from
137
147
  // the status, so the dim detail line under the message doesn't repeat it.
138
148
  code = /^[a-z][a-z0-9_]*$/.test(err) ? err : `http_${status}`;
@@ -1,2 +1,2 @@
1
1
  /** This release of phantom. `npm version` keeps it equal to the version in package.json. */
2
- export declare const VERSION = "1.5.0";
2
+ export declare const VERSION = "1.6.0";
@@ -1,2 +1,2 @@
1
1
  /** This release of phantom. `npm version` keeps it equal to the version in package.json. */
2
- export const VERSION = '1.5.0';
2
+ export const VERSION = '1.6.0';
@@ -34,6 +34,9 @@ export function tableKeys(d) {
34
34
  export async function balanceCommand(input) {
35
35
  const { io, apiKey, baseUrl, env } = input;
36
36
  const result = await getBalance(apiKey, baseUrl);
37
+ // The API answers 200 with active: false for a key that was revoked, rotated away or has expired. Its credit is not spendable.
38
+ if (!result.active)
39
+ die('This key is revoked or has expired. Make a new key with phantom keys create --save <name>, or run phantom logout and phantom login to start again.', 'key_revoked', 2);
37
40
  out(result, showsScreen(input), (d) => balanceScreen(d, { env, color: colorOn(env, io.stdoutIsTTY) }), io.stdout);
38
41
  return 0;
39
42
  }
@@ -106,11 +106,13 @@ export function applySetup(env, plan) {
106
106
  }
107
107
  else
108
108
  from = null;
109
+ let standardCopy = Boolean(prior?.standard_copy);
109
110
  if (f.before !== null && (f.agent === 'claude' || f.file.endsWith('settings.json'))) {
110
111
  const standardBak = `${f.file}.bak`;
111
112
  if (!existsSync(standardBak)) {
112
113
  const content = from && existsSync(from) ? readFileSync(from, 'utf-8') : f.before;
113
114
  writeFileSync(standardBak, content, { mode: 0o600 });
115
+ standardCopy = true;
114
116
  }
115
117
  }
116
118
  if (from && existsSync(from))
@@ -118,7 +120,7 @@ export function applySetup(env, plan) {
118
120
  if (f.after === null && from === null)
119
121
  delete backups[f.file];
120
122
  else
121
- backups[f.file] = { agent: f.agent, backup: from, sha: sha256(f.after ?? ''), ...(edited ? { edited } : {}) };
123
+ backups[f.file] = { agent: f.agent, backup: from, sha: sha256(f.after ?? ''), ...(edited ? { edited } : {}), ...(standardCopy ? { standard_copy: true } : {}) };
122
124
  }
123
125
  if (f.after === null)
124
126
  rmSync(f.file, { force: true });
@@ -170,6 +172,18 @@ export function previewSetup(plan) {
170
172
  export function setupAgents(env, opts = {}) {
171
173
  return applySetup(env, planSetup(env, opts));
172
174
  }
175
+ /**
176
+ * Removes the `<file>.bak` setup made, when it is still the copy setup wrote. One the user changed since, or one that
177
+ * was there before setup, stays. `original` is the copy from before setup, when it is still there.
178
+ */
179
+ function dropStandardCopy(file, entry, original) {
180
+ const copy = `${file}.bak`;
181
+ if (!entry.standard_copy || !existsSync(copy))
182
+ return;
183
+ if (original !== null && readText(copy) !== original)
184
+ return;
185
+ rmSync(copy, { force: true });
186
+ }
173
187
  /**
174
188
  * What a file holds once phantom's own lines and keys are taken out, for a file that changed since setup
175
189
  * (or whose copy is gone): the agent's own `--provider off` step, which uses the values setup recorded
@@ -231,6 +245,7 @@ export function restoreSetup(env, opts = {}) {
231
245
  if (entry.backup === null)
232
246
  rmSync(file, { force: true });
233
247
  else {
248
+ dropStandardCopy(file, entry, readText(entry.backup));
234
249
  writeFileSync(file, readFileSync(entry.backup));
235
250
  rmSync(entry.backup);
236
251
  }
@@ -247,6 +262,7 @@ export function restoreSetup(env, opts = {}) {
247
262
  continue;
248
263
  }
249
264
  if (!opts.dryRun) {
265
+ dropStandardCopy(file, entry, copyThere ? readText(entry.backup) : null);
250
266
  const empty = cleaned.after === null || cleaned.after.trim() === '';
251
267
  if (empty && copyThere)
252
268
  writeFileSync(file, readFileSync(entry.backup));
@@ -31,8 +31,10 @@ export function planSetup(env, opts = {}) {
31
31
  let picked;
32
32
  if (!opts.agent || opts.agent === 'all') {
33
33
  picked = names.filter((a) => SETUP_AGENTS[a].detect?.(env, home) ?? existsSync(path.join(home, SETUP_AGENTS[a].home)));
34
- if (picked.length === 0)
35
- die(`Found no agent to set up. Pass --agent ${names.join('|')}`);
34
+ if (picked.length === 0) {
35
+ const looked = names.map((a) => `${SETUP_AGENTS[a].label} (~/${SETUP_AGENTS[a].home})`).join(', ');
36
+ die(`No supported coding agents were found on this computer. phantom looks for these folders: ${looked}. Install one, or set up a specific one with --agent <name> (${names.join(', ')}).`, 'no_agents_found');
37
+ }
36
38
  if (opts.only)
37
39
  picked = picked.filter((a) => opts.only.includes(a));
38
40
  }
@@ -71,16 +71,21 @@ export async function routeCommand(input) {
71
71
  }
72
72
  else if (subcommand === 'rule') {
73
73
  const action = argv[2];
74
- const current = (await getRoute(apiKey, baseUrl)).route_policy;
75
- if (!current)
76
- die('This key has no route policy. Start with: phantom route set --models a,b');
77
- const rules = [...(current.rules ?? [])];
74
+ // The new rule is checked before the server is asked anything, so a typo in a condition costs no request.
75
+ let newRule = null;
78
76
  if (action === 'add') {
79
77
  const cond = flags['if'];
80
78
  const use = flags['use'];
81
79
  if (typeof cond !== 'string' || typeof use !== 'string')
82
80
  die('route rule add requires --if name=value and --use <model|cheapest|first|next>');
83
- const rule = { if: parseCondition(cond), use };
81
+ newRule = { if: parseCondition(cond), use };
82
+ }
83
+ const current = (await getRoute(apiKey, baseUrl)).route_policy;
84
+ if (!current)
85
+ die('This key has no route policy. Start with: phantom route set --models a,b');
86
+ const rules = [...(current.rules ?? [])];
87
+ if (newRule) {
88
+ const rule = newRule;
84
89
  const at = flagNum(flags, 'at');
85
90
  if (at !== undefined)
86
91
  rules.splice(Math.max(0, at - 1), 0, rule);
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Why a model ran, in plain words. A reason the CLI does not know reads "picked for the task",
3
+ * so a code never shows raw.
4
+ */
5
+ export declare function reasonInWords(reason: string): string;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * What each reason a route test gives means to a person, in the words the website uses for
3
+ * the same codes. This copies `reasonInWords` from `web/lib/route-reason.ts`, which the CLI
4
+ * can't import because that file only runs on the server. When the website's words change, change these.
5
+ */
6
+ const PHANTOM_1_WORDS = {
7
+ session: 'continuing with the same model',
8
+ escalated: 'you asked for a stronger model',
9
+ 'free-pool': 'free model',
10
+ 'rules:only_option': 'the only model that fits',
11
+ 'rules:contest_programming': 'contest programming problem',
12
+ 'rules:contest_math': 'competition math problem',
13
+ 'rules:concurrency_debugging': 'concurrency bug',
14
+ 'rules:complex_reasoning': 'needs careful reasoning',
15
+ 'rules:large_prompt': 'long prompt',
16
+ 'rules:routine_formatting': 'routine text work',
17
+ 'rules:default': 'typical coding step',
18
+ images: 'the request includes an image',
19
+ 'too-large': 'the conversation is long, so moving up would cost a lot',
20
+ 'said-failed': "you said the last try didn't work",
21
+ 'agent-failed': "the agent said its last try didn't work",
22
+ helper: "a helper agent's side job",
23
+ 'switchyard:fall_open': 'no sign it needs Frontier',
24
+ 'switchyard:ambiguous': 'no clear sign it needs Frontier',
25
+ 'switchyard:dimensions': 'based on the last few steps',
26
+ 'switchyard:override': 'recovering from an error',
27
+ 'switchyard:capable_hold': 'still recovering from an error',
28
+ 'switchyard:efficient_hold': 'the work is going smoothly',
29
+ 'switchyard:only-fit': 'the only model that fits',
30
+ 'switchyard:unavailable': 'the strongest model, to be safe',
31
+ };
32
+ /** The reasons a key's own route policy gives, in words. */
33
+ const POLICY_WORDS = {
34
+ default: "the key's first model",
35
+ requested: 'you named this model',
36
+ cache: 'continuing the conversation on its model',
37
+ on_empty: 'the cap is used up, so the cheapest model',
38
+ budget_exceeded: 'the cap is used up',
39
+ };
40
+ /** A key's own rule as the server writes it: `has_tools:true`. */
41
+ const RULE_REASON = /^(pace|budget_left_pct_below|days_left_below|has_tools|input_tokens_over|reasoning_requested):(.*)$/;
42
+ /**
43
+ * Why a model ran, in plain words. A reason the CLI does not know reads "picked for the task",
44
+ * so a code never shows raw.
45
+ */
46
+ export function reasonInWords(reason) {
47
+ const known = PHANTOM_1_WORDS[reason] ?? POLICY_WORDS[reason];
48
+ if (known)
49
+ return known;
50
+ const rule = RULE_REASON.exec(reason);
51
+ if (rule)
52
+ return `your rule ${rule[1]} = ${rule[2]}`;
53
+ if (reason.endsWith(':frontier'))
54
+ return 'hard task';
55
+ if (reason.endsWith(':free'))
56
+ return 'easy step';
57
+ if (reason.endsWith(':cheap') || reason.endsWith(':standard'))
58
+ return 'typical coding step';
59
+ return reason.startsWith('rules:') ? 'picked by phantom-1' : 'picked for the task';
60
+ }
@@ -68,5 +68,7 @@ export declare function testRoute(apiKey: string, opts: {
68
68
  messages?: unknown;
69
69
  tools?: unknown;
70
70
  }, baseUrl?: string): Promise<RouteTestResult>;
71
+ /** The conditions a rule can test. The server owns this list; it is here so a typo is caught before a request is sent. */
72
+ export declare const RULE_CONDITIONS: string[];
71
73
  /** `pace=ahead` or `input_tokens_over=50000` into one rule condition. */
72
74
  export declare function parseCondition(raw: string): Record<string, string | number | boolean>;
@@ -1,4 +1,5 @@
1
1
  import { die } from "../core/errors.mjs";
2
+ import { PhantomApiError } from "../core/errors.mjs";
2
3
  import { request } from "../core/request.mjs";
3
4
  /** The words `phantom route set --sort` takes, and the server's name for each. The server's own names work too. */
4
5
  export const SORT_WORDS = { cheap: 'cost', fast: 'ttft', throughput: 'tps', cost: 'cost', ttft: 'ttft', tps: 'tps' };
@@ -6,13 +7,31 @@ export const SORT_WORDS = { cheap: 'cost', fast: 'ttft', throughput: 'tps', cost
6
7
  export function getRoute(apiKey, baseUrl) {
7
8
  return request('GET', '/key/route', apiKey, undefined, baseUrl);
8
9
  }
10
+ /**
11
+ * The server's refusal of a policy reads `Invalid route policy: rules.2.if: Unrecognized key: "x"; ...`, with the
12
+ * path of each field it checked. The paths mean nothing to a person typing flags, so they come off.
13
+ */
14
+ function plainPolicyError(err) {
15
+ if (!(err instanceof PhantomApiError) || err.status !== 400 || !err.message.startsWith('Invalid route policy:'))
16
+ return err;
17
+ const problems = err.message
18
+ .slice('Invalid route policy:'.length)
19
+ .split(/;\s+/)
20
+ .map((p) => p.trim().replace(/^[a-z_]+(?:\.[a-z0-9_]+)*:\s+(?=[A-Z])/, ''))
21
+ .filter((p, k, all) => p && all.indexOf(p) === k);
22
+ return new PhantomApiError(err.status, err.code, `Phantom AI did not accept that route policy. ${problems.join('; ')}`);
23
+ }
9
24
  /** Replaces the key's route policy (PUT /key/route). The server checks it before saving. */
10
- export function putRoute(apiKey, policy, baseUrl) {
11
- return request('PUT', '/key/route', apiKey, policy, baseUrl);
25
+ export async function putRoute(apiKey, policy, baseUrl) {
26
+ return request('PUT', '/key/route', apiKey, policy, baseUrl).catch((err) => {
27
+ throw plainPolicyError(err);
28
+ });
12
29
  }
13
30
  /** Changes some top-level fields of the route policy and keeps the rest (PATCH /key/route). A list sent here replaces the whole list. */
14
- export function patchRoute(apiKey, fields, baseUrl) {
15
- return request('PATCH', '/key/route', apiKey, fields, baseUrl);
31
+ export async function patchRoute(apiKey, fields, baseUrl) {
32
+ return request('PATCH', '/key/route', apiKey, fields, baseUrl).catch((err) => {
33
+ throw plainPolicyError(err);
34
+ });
16
35
  }
17
36
  /** Removes the key's route policy (DELETE /key/route). */
18
37
  export function clearRoute(apiKey, baseUrl) {
@@ -22,12 +41,16 @@ export function clearRoute(apiKey, baseUrl) {
22
41
  export function testRoute(apiKey, opts, baseUrl) {
23
42
  return request('POST', '/key/route/test', apiKey, opts, baseUrl);
24
43
  }
44
+ /** The conditions a rule can test. The server owns this list; it is here so a typo is caught before a request is sent. */
45
+ export const RULE_CONDITIONS = ['pace', 'budget_left_pct_below', 'days_left_below', 'has_tools', 'input_tokens_over', 'reasoning_requested'];
25
46
  /** `pace=ahead` or `input_tokens_over=50000` into one rule condition. */
26
47
  export function parseCondition(raw) {
27
48
  const eq = raw.indexOf('=');
28
49
  if (eq < 1)
29
50
  die(`Write a condition as name=value, for example pace=ahead`);
30
51
  const name = raw.slice(0, eq);
52
+ if (!RULE_CONDITIONS.includes(name))
53
+ die(`"${name}" is not a condition. Use one of: ${RULE_CONDITIONS.join(', ')}. For example --if pace=ahead.`, 'route_usage');
31
54
  const text = raw.slice(eq + 1);
32
55
  const value = text === 'true' ? true : text === 'false' ? false : text !== '' && Number.isFinite(Number(text)) ? Number(text) : text;
33
56
  return { [name]: value };
@@ -12,6 +12,7 @@ import { BackToMenu, Cancelled, askText, cancelKeys, choose, keyboard } from "..
12
12
  import { spawnSync } from 'node:child_process';
13
13
  import { onPath } from "../setup/shared.mjs";
14
14
  import { colorOn, paint } from "../core/style.mjs";
15
+ import { closestCommand } from "../cli/start.mjs";
15
16
  import { alreadySignedInScreen, fundScreen, keyChangeScreen, keysScreen, paymentScreen, signedInScreen, workspaceScreen } from "../cli/screens.mjs";
16
17
  import { keyId, keyPath, listNamedKeys, namedKeyPath, readNamedKey, resolveApiKey, saveApiKey, saveNamedKey } from "../keys/saved.mjs";
17
18
  const credentialPath = (env) => path.join(stateDir(env), 'workspace');
@@ -273,9 +274,85 @@ async function pollForApproval(input, opts, ctx) {
273
274
  }
274
275
  die('The sign-in code expired before it was approved. Run phantom login again.', 'login_expired');
275
276
  }
277
+ /** The words `phantom workspace` takes. `fund` is here because `phantom fund` runs it. */
278
+ const WORKSPACE_WORDS = ['status', 'payment', 'export', 'import', 'revoke-access', 'delete', 'fund'];
279
+ /**
280
+ * A file phantom could not write, in a sentence that says what to do, instead of node's `EEXIST: file already
281
+ * exists, open '…'`.
282
+ */
283
+ function writeFailure(err, file) {
284
+ const code = err.code;
285
+ if (code === 'EEXIST')
286
+ die(`There is already a file at ${file}. phantom won't overwrite it. Pick a path that doesn't exist yet.`, 'file_exists');
287
+ if (code === 'ENOENT')
288
+ die(`Could not save to ${file}: the folder doesn't exist. Make the folder first, or pick another path.`, 'file_unwritable');
289
+ if (code === 'EACCES' || code === 'EPERM')
290
+ die(`Could not save to ${file}: phantom has no permission to write there. Pick another path.`, 'file_unwritable');
291
+ if (code === 'EISDIR')
292
+ die(`Could not save to ${file}: that is a folder. Give a file path, such as ${path.join(file, 'recovery.json')}.`, 'file_unwritable');
293
+ die(`Could not save to ${file}. Pick another path.`, 'file_unwritable');
294
+ }
295
+ /**
296
+ * Reads a JSON file for a flag. A file that is missing or can't be read says so, and a file that is not
297
+ * JSON says `notJson`, instead of node's `ENOENT` or `Unexpected token`.
298
+ */
299
+ function readJsonFile(file, notJson) {
300
+ let text;
301
+ try {
302
+ text = readFileSync(file, 'utf8');
303
+ }
304
+ catch (err) {
305
+ const code = err.code;
306
+ const why = code === 'ENOENT' ? 'there is no file at that path' : code === 'EISDIR' ? 'that is a folder' : code === 'EACCES' ? 'phantom has no permission to read it' : 'it could not be opened';
307
+ die(`Could not read ${file}: ${why}. Check the path.`, 'file_unreadable');
308
+ }
309
+ try {
310
+ return JSON.parse(text);
311
+ }
312
+ catch {
313
+ die(notJson, 'file_not_json');
314
+ }
315
+ }
316
+ /** One sign-in by its id or the start of it, at least 4 characters, as `phantom workspace` lists them. */
317
+ function findAccess(access, typed) {
318
+ const t = typed.trim().toLowerCase();
319
+ const exact = access.find((a) => a.id.toLowerCase() === t);
320
+ if (exact)
321
+ return exact.id;
322
+ if (t.length < 4)
323
+ die(`"${typed}" is too short. Type at least 4 characters of the id from phantom workspace.`, 'access_not_found');
324
+ const hits = access.filter((a) => a.id.toLowerCase().startsWith(t));
325
+ const label = (a) => `${a.kind ?? 'sign-in'} ${a.id.slice(0, 8)}`;
326
+ if (hits.length === 1)
327
+ return hits[0].id;
328
+ if (!hits.length)
329
+ die(`No sign-in matches "${typed}". Run phantom workspace to see them: ${access.map(label).join(', ') || 'none'}.`, 'access_not_found');
330
+ die(`"${typed}" matches more than one sign-in: ${hits.map(label).join(', ')}. Type more of the id.`, 'access_ambiguous');
331
+ }
332
+ /** What each way to pay takes: its name in a sentence, and the least it takes. Every way takes up to $10,000 (web/lib/pricing.ts). */
333
+ const FUND_WAYS = {
334
+ card: { label: 'Card payments take', min: 5 },
335
+ usdc: { label: 'USDC on Solana takes', min: 0.1 },
336
+ 'usdc-base': { label: 'USDC on Base takes', min: 1 },
337
+ };
338
+ const FUND_MAX = 10_000;
339
+ /** Dollars as a person would write them: `$5`, `$0.10`, `$10,000`. */
340
+ const dollars = (n) => `$${Number.isInteger(n) ? n.toLocaleString('en-US') : n.toFixed(2)}`;
341
+ /** Refuses an amount the way to pay can't take, naming the range for that way, before anything is sent. The server checks it again. */
342
+ function checkFundAmount(method, amount) {
343
+ const way = FUND_WAYS[method];
344
+ if (!way || (amount >= way.min && amount <= FUND_MAX))
345
+ return;
346
+ const hint = amount < way.min ? (method === 'card' ? ` For less than ${dollars(way.min)}, pay with --coin usdc.` : '') : ' Add it in smaller payments.';
347
+ die(`${way.label} ${dollars(way.min)} to ${dollars(FUND_MAX)} at a time. You asked for ${dollars(amount)}.${hint}`, 'fund_usage');
348
+ }
276
349
  /** Manage a workspace from the terminal: balance, keys, funding, recovery and revocation. */
277
350
  export async function workspaceCommand(input) {
278
351
  const { subcommand, flags, io, env, argv } = input;
352
+ if (argv[0] === 'workspace' && subcommand !== undefined && !WORKSPACE_WORDS.includes(subcommand)) {
353
+ const guess = closestCommand(subcommand, WORKSPACE_WORDS);
354
+ die(`Unknown phantom workspace subcommand "${subcommand}".${guess ? ` Did you mean phantom workspace ${guess}?` : ''} It takes: ${WORKSPACE_WORDS.join(', ')}.`, 'workspace_usage');
355
+ }
279
356
  if (argv[0] === 'keys') {
280
357
  if (subcommand === 'saved' || subcommand === 'save' || subcommand === 'show' || subcommand === 'rm') {
281
358
  // Only the flags the key command reads pass through; --copy must, or `keys show --copy` would print the key.
@@ -297,12 +374,13 @@ export async function workspaceCommand(input) {
297
374
  if (command === 'import' && argv[0] === 'workspace') {
298
375
  if (typeof flags.file !== 'string')
299
376
  die('Use phantom workspace import --file <recovery-file>.');
300
- const recovery = JSON.parse(readFileSync(flags.file, 'utf8'));
377
+ const notRecovery = `${flags.file} is not a recovery file from phantom workspace export.`;
378
+ const recovery = readJsonFile(flags.file, notRecovery);
301
379
  if (!recovery || recovery.version !== 1)
302
- die(`${flags.file} is not a recovery file from phantom workspace export.`);
380
+ die(notRecovery, 'file_not_json');
303
381
  await wire(base(input), 'GET', '/workspaces/' + encodeURIComponent(recovery.workspace_id), undefined, recovery.management_credential);
304
382
  writeSecret(env, credentialPath(env), JSON.stringify({ ...recovery, base_url: base(input), recovery }));
305
- io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} Workspace restored. Make a new key with phantom keys create.\n` : 'Workspace restored. Make a new key with phantom keys create.\n');
383
+ io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} Workspace restored. Make a new key with phantom keys create.\n` : JSON.stringify({ imported: true, workspace_id: recovery.workspace_id }) + '\n');
306
384
  return 0;
307
385
  }
308
386
  const saved = credentials(input);
@@ -312,11 +390,17 @@ export async function workspaceCommand(input) {
312
390
  die('This is an account workspace. Sign in to recover it on another computer.');
313
391
  if (typeof flags.file !== 'string')
314
392
  die('Use phantom workspace export --file <path>.');
315
- writeFileSync(flags.file, JSON.stringify(saved.recovery, null, 2), {
316
- mode: 0o600,
317
- flag: 'wx',
318
- });
319
- io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} Recovery saved to ${flags.file}. Keep that file private: it can manage this workspace.\n` : `Recovery saved to ${flags.file}. Keep that file private: it can manage this workspace.\n`);
393
+ try {
394
+ writeFileSync(flags.file, JSON.stringify(saved.recovery, null, 2), {
395
+ mode: 0o600,
396
+ flag: 'wx',
397
+ });
398
+ }
399
+ catch (err) {
400
+ writeFailure(err, flags.file);
401
+ }
402
+ const keepPrivate = 'Keep that file private: it can manage this workspace.';
403
+ io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} Recovery saved to ${flags.file}. ${keepPrivate}\n` : JSON.stringify({ exported: true, file: flags.file, note: keepPrivate }) + '\n');
320
404
  return 0;
321
405
  }
322
406
  if (command === 'create' || command === 'rotate') {
@@ -380,7 +464,7 @@ export async function workspaceCommand(input) {
380
464
  env,
381
465
  color: colorOn(env, io.stdoutIsTTY),
382
466
  }) + '\n'
383
- : 'Key revoked.\n');
467
+ : JSON.stringify({ revoked: true, id: which.id }) + '\n');
384
468
  return 0;
385
469
  }
386
470
  if (command === 'set') {
@@ -391,13 +475,18 @@ export async function workspaceCommand(input) {
391
475
  period_days: limitFlag(flags, 'period'),
392
476
  rate_usd_per_min: limitFlag(flags, 'rate', true),
393
477
  };
478
+ for (const k of ['name', 'policy-file'])
479
+ if (flags[k] === true)
480
+ die(`--${k} needs a value.`, 'key_usage');
481
+ // No change given, at a terminal: the usual change, a spending limit, as a picker. In a pipe there is no one to ask.
482
+ const anyChange = ['limit', 'budget', 'period', 'rate', 'name', 'policy-file', 'clear-policy'].some((k) => flags[k] !== undefined);
483
+ const pick = anyChange ? null : pickIo(input);
484
+ if (!anyChange && !pick)
485
+ die('Nothing was changed. Say what to change: --limit <USD|none>, --budget <USD|none> with --period <days>, --rate <USD|none>, --name <name>, --policy-file <path> or --clear-policy.', 'key_usage');
394
486
  const which = await whichKey(input, saved, endpoint, 'change');
395
487
  if (which === null)
396
488
  return 0;
397
489
  const id = which.id;
398
- // No change given, at a terminal: the usual change, a spending limit, as a picker.
399
- const anyChange = ['limit', 'budget', 'period', 'rate', 'name', 'policy-file', 'clear-policy'].some((k) => flags[k] !== undefined);
400
- const pick = anyChange ? null : pickIo(input);
401
490
  if (pick) {
402
491
  const limit = await chooseLimit(pick);
403
492
  if (limit === undefined)
@@ -411,7 +500,7 @@ export async function workspaceCommand(input) {
411
500
  if (typeof flags.name === 'string')
412
501
  body.name = flags.name;
413
502
  if (typeof flags['policy-file'] === 'string')
414
- body.route_policy = JSON.parse(readFileSync(flags['policy-file'], 'utf8'));
503
+ body.route_policy = readJsonFile(flags['policy-file'], `${flags['policy-file']} is not valid JSON. It should hold a route policy, as phantom route set --file does.`);
415
504
  if (flags['clear-policy'])
416
505
  body.route_policy = null;
417
506
  const result = await wire(saved.base_url, 'PATCH', endpoint + '/keys/' + id, body, saved.management_credential);
@@ -451,8 +540,10 @@ export async function workspaceCommand(input) {
451
540
  if (command === 'revoke-access') {
452
541
  if (typeof flags.id !== 'string')
453
542
  die('Use --id <management-id> from phantom workspace status.');
454
- await wire(saved.base_url, 'DELETE', endpoint + '/access/' + flags.id, undefined, saved.management_credential);
455
- io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} That sign-in can no longer manage this workspace.\n` : 'Management access revoked.\n');
543
+ // A full id is used as it is. The start of one is looked up in the workspace's sign-ins.
544
+ const accessId = /^[0-9a-f]{64}$/i.test(flags.id) ? flags.id : findAccess((await wire(saved.base_url, 'GET', endpoint, undefined, saved.management_credential)).access ?? [], flags.id);
545
+ await wire(saved.base_url, 'DELETE', endpoint + '/access/' + accessId, undefined, saved.management_credential);
546
+ io.stdout(showsScreen(input) ? `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} That sign-in can no longer manage this workspace.\n` : JSON.stringify({ revoked: true, id: accessId }) + '\n');
456
547
  return 0;
457
548
  }
458
549
  if (command === 'payment') {
@@ -467,6 +558,8 @@ export async function workspaceCommand(input) {
467
558
  die('--pay has been removed. Use --card or --coin.');
468
559
  if (flags.coin === true)
469
560
  die(`--coin needs usdc or usdc-base. ${FUND_EXAMPLE}`);
561
+ if (flags.card && flags.coin !== undefined)
562
+ die(`Pick one: --card or --coin, not both. ${FUND_EXAMPLE}`, 'fund_usage');
470
563
  let amount = dollarsFlag(flags);
471
564
  let method = flags.card ? 'card' : flags.coin;
472
565
  // At a terminal, whatever is missing is asked for: first how much, then how to pay.
@@ -492,11 +585,14 @@ export async function workspaceCommand(input) {
492
585
  }
493
586
  if (amount === undefined || !method)
494
587
  die(`fund needs an amount and a way to pay. ${FUND_EXAMPLE}`, 'fund_usage');
495
- const result = await wire(saved.base_url, 'POST', endpoint + '/fund', {
588
+ checkFundAmount(method, amount);
589
+ const answer = await wire(saved.base_url, 'POST', endpoint + '/fund', {
496
590
  method: method === 'card' ? 'card' : 'crypto',
497
591
  amount_usd: amount,
498
592
  coin: method === 'card' ? 'usdc' : method,
499
593
  }, saved.management_credential);
594
+ // The server fills a field a way to pay doesn't use with an empty string (a Base payment has no Solana reference). Leave those out.
595
+ const result = Object.fromEntries(Object.entries(answer).filter(([, value]) => value !== ''));
500
596
  io.stdout((showsScreen(input)
501
597
  ? fundScreen(result, {
502
598
  env,
@@ -529,7 +625,10 @@ export async function forgetWorkspace(env, baseUrl) {
529
625
  {
530
626
  try {
531
627
  const saved = JSON.parse(readSecret(env, file));
532
- if (saved?.workspace_id && saved?.management_credential) {
628
+ // `workspace import` saves the recovery file's own credential as the sign-in. Revoking that on the
629
+ // server would kill the recovery file, so a sign-in that is the recovery credential is only forgotten here.
630
+ const isRecoveryFile = saved?.recovery?.management_credential === saved?.management_credential;
631
+ if (saved?.workspace_id && saved?.management_credential && !isRecoveryFile) {
533
632
  const url = httpsOnly(baseUrl || env.PHANTOM_BASE_URL || saved.base_url || DEFAULT_BASE_URL).replace(/\/$/, '');
534
633
  await wire(url, 'POST', '/workspaces/' + encodeURIComponent(saved.workspace_id) + '/logout', {}, saved.management_credential).catch(() => { });
535
634
  }
@@ -616,7 +715,9 @@ export function findKey(allKeys, typed) {
616
715
  const off = matching(allKeys.filter((k) => k.is_active === false));
617
716
  if (off.length)
618
717
  die(`"${typed}" is a key that is turned off (${off.map(label).join(', ')}). Your keys that work: ${keys.map(label).join(', ') || 'none'}.`, 'key_not_found');
619
- die(`No key matches "${typed}". Your keys: ${keys.map(label).join(', ') || 'none yet'}.`, 'key_not_found');
718
+ // A few characters that do start a key's id are a start that is too short, not a wrong name.
719
+ const tooShort = t.length < 4 && keys.some((k) => k.id.toLowerCase().startsWith(t));
720
+ die(`No key matches "${typed}".${tooShort ? ' Type at least 4 characters of an id, or the key\'s name.' : ''} Your keys: ${keys.map(label).join(', ') || 'none yet'}.`, 'key_not_found');
620
721
  }
621
722
  die(`"${typed}" matches more than one key: ${loose.map(label).join(', ')}. Use more of the id.`, 'key_ambiguous');
622
723
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phantomcodes/cli",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Connects Claude Code, Codex, pi and other coding agents to Phantom AI, an OpenAI-compatible API, and manages your keys, credit and spending caps from the terminal.",
5
5
  "keywords": [
6
6
  "phantom",
@@ -58,7 +58,7 @@ phantom fund --amount 10 --coin usdc
58
58
  phantom workspace payment --id <payment-id>
59
59
  ```
60
60
 
61
- `--card` opens Stripe Checkout in the browser. `--coin usdc` pays in USDC on Solana and `--coin usdc-base` in USDC on Base; both return a payment link and a payment id. The credit appears once Stripe confirms the payment. `phantom workspace payment --id <payment-id>` says whether it has arrived, and `phantom balance` shows the key's credit.
61
+ `--card` opens Stripe Checkout in the browser. `--coin usdc` pays in USDC on Solana and `--coin usdc-base` in USDC on Base; both return a payment link and a payment id, and the link is good for 30 minutes. Use one of `--card` and `--coin`, never both. Card payments take $5 to $10,000, USDC on Solana $0.10 to $10,000 and USDC on Base $1 to $10,000. The credit appears once Stripe confirms the payment. `phantom workspace payment --id <payment-id>` says whether it has arrived, and `phantom balance` shows the key's credit.
62
62
 
63
63
  ## Cap what keys spend
64
64
 
@@ -117,7 +117,7 @@ phantom spend --workspace --from 2026-09-01 --to 2026-09-30
117
117
 
118
118
  `phantom --help --all` lists every command, including `phantom verify` for receipts, and the environment variables.
119
119
 
120
- A guest workspace has no account; whoever holds its recovery file controls it. Save that file with `phantom workspace export --file <path>`, only to a private place.
120
+ A guest workspace has no account; whoever holds its recovery file controls it. Save that file with `phantom workspace export --file <path>`, only to a private place. `phantom workspace revoke-access --id <id>` stops a browser, device or recovery file from managing the workspace; `--id` takes the first 4 or more characters of the id that `phantom workspace` lists. In a pipe, `keys revoke`, `workspace export`, `workspace import` and `workspace revoke-access` print JSON.
121
121
 
122
122
  `phantom workspace delete` deletes an empty workspace, with its keys and saved sign-ins. It asks first (`--yes` skips the question). The server refuses while the workspace holds credit, has a request running or has a payment in progress.
123
123