@phantomcodes/cli 1.4.1 → 1.4.3

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.
Files changed (69) hide show
  1. package/README.md +99 -133
  2. package/dist/agents/command.d.mts +36 -0
  3. package/dist/agents/command.mjs +22 -10
  4. package/dist/agents/proxy.d.mts +44 -0
  5. package/dist/agents/proxy.mjs +4 -2
  6. package/dist/cli/app.d.mts +25 -0
  7. package/dist/cli/app.mjs +2 -2
  8. package/dist/cli/commands.d.mts +23 -0
  9. package/dist/cli/commands.mjs +106 -54
  10. package/dist/cli/help.d.mts +26 -0
  11. package/dist/cli/help.mjs +10 -6
  12. package/dist/cli/run.d.mts +2 -0
  13. package/dist/cli/screens.d.mts +171 -0
  14. package/dist/cli/screens.mjs +3 -3
  15. package/dist/cli/start.d.mts +34 -0
  16. package/dist/core/brand.d.mts +12 -0
  17. package/dist/core/errors.d.mts +27 -0
  18. package/dist/core/free.d.mts +13 -0
  19. package/dist/core/helpers.d.mts +75 -0
  20. package/dist/core/helpers.mjs +27 -2
  21. package/dist/core/motion.d.mts +47 -0
  22. package/dist/core/node-trust.d.mts +12 -0
  23. package/dist/core/pick.d.mts +86 -0
  24. package/dist/core/request.d.mts +64 -0
  25. package/dist/core/request.mjs +78 -29
  26. package/dist/core/secrets.d.mts +33 -0
  27. package/dist/core/shapes.d.mts +13 -0
  28. package/dist/core/state.d.mts +3 -0
  29. package/dist/core/style.d.mts +49 -0
  30. package/dist/core/version.d.mts +2 -0
  31. package/dist/core/version.mjs +1 -1
  32. package/dist/keys/command.d.mts +16 -0
  33. package/dist/keys/saved.d.mts +90 -0
  34. package/dist/keys/saved.mjs +6 -2
  35. package/dist/models/choice.d.mts +7 -0
  36. package/dist/models/choice.mjs +1 -1
  37. package/dist/models/command.d.mts +8 -0
  38. package/dist/models/list.d.mts +39 -0
  39. package/dist/phantom.d.mts +45 -0
  40. package/dist/receipts/command.d.mts +7 -0
  41. package/dist/receipts/receipts.d.mts +67 -0
  42. package/dist/receipts/receipts.mjs +15 -11
  43. package/dist/setup/agents.d.mts +149 -0
  44. package/dist/setup/agents.mjs +50 -37
  45. package/dist/setup/apply.d.mts +71 -0
  46. package/dist/setup/apply.mjs +7 -2
  47. package/dist/setup/command.d.mts +12 -0
  48. package/dist/setup/command.mjs +32 -5
  49. package/dist/setup/editors.d.mts +101 -0
  50. package/dist/setup/editors.mjs +6 -4
  51. package/dist/setup/legacy.d.mts +13 -0
  52. package/dist/setup/plan.d.mts +104 -0
  53. package/dist/setup/plan.mjs +5 -3
  54. package/dist/setup/screen.d.mts +30 -0
  55. package/dist/setup/screen.mjs +2 -2
  56. package/dist/setup/shared.d.mts +141 -0
  57. package/dist/setup/shared.mjs +8 -2
  58. package/dist/setup/was.d.mts +42 -0
  59. package/dist/setup/was.mjs +91 -0
  60. package/dist/spend/command.d.mts +5 -0
  61. package/dist/spend/lineup.d.mts +54 -0
  62. package/dist/spend/lineup.mjs +3 -2
  63. package/dist/spend/report.d.mts +105 -0
  64. package/dist/spend/report.mjs +2 -2
  65. package/dist/spend/routing.d.mts +72 -0
  66. package/dist/workspace/command.d.mts +59 -0
  67. package/dist/workspace/command.mjs +106 -52
  68. package/package.json +7 -7
  69. package/skills/phantom-ai/SKILL.md +40 -66
@@ -0,0 +1,105 @@
1
+ import { type CommandInput } from '../core/helpers.mts';
2
+ /** One key or model's calls and cost. */
3
+ export type SpendLine = {
4
+ /** Calls, free ones included. */
5
+ calls: number;
6
+ /** What they cost, in US dollars. */
7
+ spent_usd: number;
8
+ };
9
+ /** Everything a spend report covers. */
10
+ export type SpendTotal = SpendLine & {
11
+ /** Prompt tokens, cached ones included. */
12
+ prompt_tokens: number;
13
+ /** Completion tokens. */
14
+ completion_tokens: number;
15
+ };
16
+ /** One model a key ran. */
17
+ export type SpendKeyModel = SpendLine & {
18
+ /** The model that ran. */
19
+ model: string;
20
+ };
21
+ /** One key's spend. */
22
+ export type SpendKey = SpendLine & {
23
+ /** The name the workspace gave the key, or `This key`. */
24
+ name: string;
25
+ /** The key's first characters, only in a workspace report; null otherwise. */
26
+ prefix: string | null;
27
+ /** False once the key was revoked or rotated away. */
28
+ active: boolean;
29
+ /** What phantom-1 saved on this key's calls, in US dollars; null when it can't be worked out. */
30
+ saved_usd: number | null;
31
+ /** The models the key ran, biggest spender first. */
32
+ models: SpendKeyModel[];
33
+ };
34
+ /** One model's spend across the keys in the report. */
35
+ export type SpendModel = SpendLine & {
36
+ /** The model that ran. */
37
+ model: string;
38
+ /** Prompt tokens. */
39
+ prompt_tokens: number;
40
+ /** Completion tokens. */
41
+ completion_tokens: number;
42
+ };
43
+ /** One UTC day's spend. */
44
+ export type SpendDay = SpendLine & {
45
+ /** The day, `YYYY-MM-DD`, UTC. */
46
+ date: string;
47
+ };
48
+ /** What phantom-1 routing saved: a figure, or the reason there is none. */
49
+ export type SpendRouting = {
50
+ /** True when the figures below are given. */
51
+ available: true;
52
+ /** Calls sent to a phantom-1 router. */
53
+ calls: number;
54
+ /** What those calls cost, in US dollars. */
55
+ spent_usd: number;
56
+ /** The model the same calls are priced on. */
57
+ baseline_model: string;
58
+ /** What the same calls would have cost on it, in US dollars. */
59
+ baseline_usd: number;
60
+ /** `baseline_usd` less `spent_usd`. */
61
+ saved_usd: number;
62
+ /** How `baseline_usd` is worked out, in words. */
63
+ basis: string;
64
+ } | {
65
+ /** False when the frontier model's price isn't listed. */
66
+ available: false;
67
+ /** Why there is no figure. */
68
+ reason: string;
69
+ };
70
+ /** The answer from `/key/spend` and `/workspaces/{id}/spend`. */
71
+ export type SpendResult = {
72
+ /** `key` for the calling key alone, `workspace` for every key in it. */
73
+ scope: 'key' | 'workspace';
74
+ /** First day, UTC, inclusive. */
75
+ from: string;
76
+ /** Last day, UTC, inclusive. */
77
+ to: string;
78
+ /** Everything in the range. */
79
+ total: SpendTotal;
80
+ /** Each key by name, biggest spender first. */
81
+ keys: SpendKey[];
82
+ /** Each model that ran, biggest spender first. */
83
+ models: SpendModel[];
84
+ /** Every day in the range, oldest first. */
85
+ days: SpendDay[];
86
+ /** What phantom-1 routing saved. */
87
+ routing: SpendRouting;
88
+ };
89
+ /** The `--from` and `--to` values, as parseFlags read them. */
90
+ export type SpendDates = {
91
+ /** The `--from` value. */
92
+ from?: string | true;
93
+ /** The `--to` value. */
94
+ to?: string | true;
95
+ };
96
+ /** What the key spent (GET /key/spend). */
97
+ export declare function getSpend(apiKey: string, dates?: SpendDates, baseUrl?: string): Promise<SpendResult>;
98
+ /** `--table` output for `spend`. */
99
+ export declare function tableSpend(d: unknown): string;
100
+ /**
101
+ * `phantom spend`: what the key spent, by model and day, and what phantom-1
102
+ * saved. `--workspace` shows every key in the workspace by name, with the
103
+ * workspace connection `phantom login` saved. Run by `run()`.
104
+ */
105
+ export declare function spendCommand(input: CommandInput): Promise<number>;
@@ -31,9 +31,9 @@ export function tableSpend(d) {
31
31
  `spent ${dollars(s.total.spent_usd)} (${calls(s.total.calls)})`,
32
32
  ];
33
33
  if (!s.routing.available)
34
- lines.push(`phantom-1 saved not available: ${s.routing.reason}`);
34
+ lines.push(`phantom-1 saved unknown: ${s.routing.reason}`);
35
35
  else if (s.routing.calls === 0)
36
- lines.push('phantom-1 saved no calls went to phantom-1');
36
+ lines.push('phantom-1 saved nothing yet: no calls went to phantom-1');
37
37
  else
38
38
  lines.push(`phantom-1 saved ${dollars(s.routing.saved_usd)} (${calls(s.routing.calls)} cost ${dollars(s.routing.spent_usd)}; on ${s.routing.baseline_model} they would cost ${dollars(s.routing.baseline_usd)})`);
39
39
  lines.push('', 'by key');
@@ -0,0 +1,72 @@
1
+ /**
2
+ * A key's route policy decides which model `model: "auto"` runs. The server
3
+ * validates it and owns the list of conditions and actions
4
+ * (routers/phantom-1/runtime/src/route-policy.ts in the Phantom repo), so the
5
+ * CLI passes it through as JSON.
6
+ */
7
+ /** One routing rule: when the condition in `if` holds, run the model `use` names. */
8
+ export type RouteRule = {
9
+ /** Exactly one condition, such as `{ pace: 'ahead' }` or `{ input_tokens_over: 50000 }`. */
10
+ if: Record<string, string | number | boolean>;
11
+ /** A model from the policy's `models`, or `cheapest`, `first` or `next`. */
12
+ use: string;
13
+ };
14
+ /** A key's route policy, as the server stores and validates it. */
15
+ export type RoutePolicy = {
16
+ /** The models routing may pick from. The first is the default for `auto`. Empty: the policy holds preferences only (such as `sort`) and routes nothing. */
17
+ models: string[];
18
+ /** `auto` routes only requests for model `auto`; `all` routes every request. Default `auto`. */
19
+ applies_to?: 'auto' | 'all';
20
+ /** Rules checked in order. The first that matches picks the model. */
21
+ rules?: RouteRule[];
22
+ /** When the key's cap for the period is used up: `stop` refuses requests, `cheapest` keeps running on the cheapest model in `models`. Default `stop`. */
23
+ on_empty?: 'stop' | 'cheapest';
24
+ /** When true, the other models in `models` are tried if the picked one fails. Default false. */
25
+ fallback_on_error?: boolean;
26
+ /** Minutes a conversation stays on the model it started on after its last request, so its prompt cache stays warm. 0 turns it off. Default 5. */
27
+ stick_minutes?: number;
28
+ /** When true, a conversation without an x-phantom-session header is recognised by its opening messages. false: only the header counts. Default true. */
29
+ stick_by_prompt?: boolean;
30
+ /** Which providers serve this key's requests first: `cost` (cheapest, the default), `ttft` (quickest to start answering) or `tps` (most tokens a second). */
31
+ sort?: ProviderSort;
32
+ /** Only providers that delete prompts right away. */
33
+ zdr?: boolean;
34
+ /** Only providers that don't train on prompts. */
35
+ no_training?: boolean;
36
+ };
37
+ /** The provider orders the server takes for `sort`. */
38
+ export type ProviderSort = 'cost' | 'ttft' | 'tps';
39
+ /** The words `phantom route set --sort` takes, and the server's name for each. The server's own names work too. */
40
+ export declare const SORT_WORDS: Record<string, ProviderSort>;
41
+ /** The answer from the /key/route calls. */
42
+ export type RouteResult = {
43
+ /** The key's policy. null means none, and model `auto` is refused. */
44
+ route_policy: RoutePolicy | null;
45
+ };
46
+ /** The answer from POST /key/route/test. */
47
+ export type RouteTestResult = {
48
+ /** The model the request would run on. The server sends null when the key's cap is used up and the request would be refused. */
49
+ model: string | null;
50
+ /** What decided it: `<condition>:<value>` for a rule, or `default`, `requested`, `cache`, `on_empty` or `budget_exceeded`. The server sends null when the request is not routed and runs the model it named. */
51
+ reason: string | null;
52
+ /** True when the route policy picked the model, false when the request runs the model it named or is refused. */
53
+ routed: boolean;
54
+ /** Models tried next if this one fails, when `fallback_on_error` is on. */
55
+ fallbacks?: string[];
56
+ };
57
+ /** The key's route policy (GET /key/route). */
58
+ export declare function getRoute(apiKey: string, baseUrl?: string): Promise<RouteResult>;
59
+ /** Replaces the key's route policy (PUT /key/route). The server checks it before saving. */
60
+ export declare function putRoute(apiKey: string, policy: RoutePolicy, baseUrl?: string): Promise<RouteResult>;
61
+ /** Changes some top-level fields of the route policy and keeps the rest (PATCH /key/route). A list sent here replaces the whole list. */
62
+ export declare function patchRoute(apiKey: string, fields: Partial<RoutePolicy>, baseUrl?: string): Promise<RouteResult>;
63
+ /** Removes the key's route policy (DELETE /key/route). */
64
+ export declare function clearRoute(apiKey: string, baseUrl?: string): Promise<RouteResult>;
65
+ /** Which model a request would run on now, and why (POST /key/route/test). Nothing is charged. A route policy picks without calling a model; `phantom-1`, `phantom-1:zdr`, or `auto` on a key with no policy can call the model that picks the tier. `phantom-1:free` never does. */
66
+ export declare function testRoute(apiKey: string, opts: {
67
+ model: string;
68
+ messages?: unknown;
69
+ tools?: unknown;
70
+ }, baseUrl?: string): Promise<RouteTestResult>;
71
+ /** `pace=ahead` or `input_tokens_over=50000` into one rule condition. */
72
+ export declare function parseCondition(raw: string): Record<string, string | number | boolean>;
@@ -0,0 +1,59 @@
1
+ import { type Env } from '../core/state.mts';
2
+ import { type CommandInput } from '../core/helpers.mts';
3
+ export type Credentials = {
4
+ version: 1;
5
+ workspace_id: string;
6
+ management_credential: string;
7
+ base_url: string;
8
+ recovery?: {
9
+ version: 1;
10
+ workspace_id: string;
11
+ management_credential: string;
12
+ };
13
+ };
14
+ /**
15
+ * One call to the workspace API, with the limits every call shares ({@link fetchAnswer}): 30 seconds
16
+ * unless `timeoutMs` says less, and a plain message for a web page, an empty answer or no connection.
17
+ * @throws {@link PhantomApiError} when the API answers with an error status.
18
+ */
19
+ export declare function wire<T>(url: string, method: string, endpoint: string, body?: unknown, token?: string, timeoutMs?: number): Promise<T>;
20
+ /** The workspace `phantom login` saved for this API address, or null when it saved none or saved one for another address. */
21
+ export declare function savedWorkspace(input: CommandInput): Credentials | null;
22
+ /** The management credential `phantom login` saved for this API address, or null when it saved none. */
23
+ export declare function savedManagement(input: CommandInput): string | null;
24
+ /** A read from the saved workspace, such as `/spend`, with its management credential. */
25
+ export declare function workspaceGet(input: CommandInput, path: string): Promise<unknown>;
26
+ /**
27
+ * Device authorization for accounts or guests, saving keys locally without copying a secret through the browser.
28
+ * With `inSetup`, `phantom setup` carries on once it is signed in, so it says that instead of printing the
29
+ * saved key's details and the next commands.
30
+ */
31
+ export declare function workspaceLogin(input: CommandInput, opts?: {
32
+ inSetup?: boolean;
33
+ }): Promise<number>;
34
+ /** Manage a workspace from the terminal: balance, keys, funding, recovery and revocation. */
35
+ export declare function workspaceCommand(input: CommandInput): Promise<number>;
36
+ /** Forget local management credentials and revoke server management access, leaving server-side keys and recovery files valid. True when there was a workspace sign-in to forget. */
37
+ export declare function forgetWorkspace(env: Env, baseUrl?: string): Promise<boolean>;
38
+ /**
39
+ * `--amount` as dollars: `10`, `10.50` or `$10`. A bare `--amount` is
40
+ * usually `--amount $5` after the shell has replaced `$5` with nothing, so
41
+ * the message says to leave out the $.
42
+ */
43
+ export declare function dollarsFlag(flags: Record<string, string | true>): number | undefined;
44
+ /** A workspace key as the view lists it: the parts used to find it by what people type. */
45
+ type ListedKey = {
46
+ id: string;
47
+ name?: string;
48
+ prefix?: string;
49
+ spent_usd?: number;
50
+ limit_usd?: number | null;
51
+ /** False for a key turned off by a rotate or revoke. Missing counts as on. */
52
+ is_active?: boolean;
53
+ };
54
+ /**
55
+ * Finds one key by id, the start of its id, its name, or the start of the key itself. Refuses when none or more than one matches.
56
+ * Keys that are turned off never match: after a rotate, the old key and the new one share a name.
57
+ */
58
+ export declare function findKey(allKeys: ListedKey[], typed: string): string;
59
+ export {};
@@ -2,12 +2,12 @@ import { createHash } from 'node:crypto';
2
2
  import { hostname } from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { existsSync, readFileSync, writeFileSync } from 'node:fs';
5
- import { DEFAULT_BASE_URL, httpsOnly, apiError } from "../core/request.mjs";
5
+ import { DEFAULT_BASE_URL, REQUEST_TIMEOUT_MS, answerError, fetchAnswer, httpsOnly } from "../core/request.mjs";
6
6
  import { stateDir } from "../core/state.mjs";
7
7
  import { writeSecret, readSecret, removeSecret, keychainOn } from "../core/secrets.mjs";
8
8
  import { keyCommand, loginCommand } from "../keys/command.mjs";
9
9
  import { die } from "../core/errors.mjs";
10
- import { openUrl, flagNum, pickIo, showsScreen } from "../core/helpers.mjs";
10
+ import { limitFlag, openUrl, pickIo, showsScreen } from "../core/helpers.mjs";
11
11
  import { BackToMenu, Cancelled, askText, cancelKeys, choose, keyboard } from "../core/pick.mjs";
12
12
  import { spawnSync } from 'node:child_process';
13
13
  import { onPath } from "../setup/shared.mjs";
@@ -16,8 +16,13 @@ import { alreadySignedInScreen, fundScreen, keyChangeScreen, keysScreen, payment
16
16
  import { keyId, keyPath, listNamedKeys, namedKeyPath, readNamedKey, resolveApiKey, saveApiKey, saveNamedKey } from "../keys/saved.mjs";
17
17
  const credentialPath = (env) => path.join(stateDir(env), 'workspace');
18
18
  const base = (input) => httpsOnly(input.baseUrl || input.env.PHANTOM_BASE_URL || DEFAULT_BASE_URL).replace(/\/$/, '');
19
- async function wire(url, method, endpoint, body, token) {
20
- const response = await fetch(url + endpoint, {
19
+ /**
20
+ * One call to the workspace API, with the limits every call shares ({@link fetchAnswer}): 30 seconds
21
+ * unless `timeoutMs` says less, and a plain message for a web page, an empty answer or no connection.
22
+ * @throws {@link PhantomApiError} when the API answers with an error status.
23
+ */
24
+ export async function wire(url, method, endpoint, body, token, timeoutMs) {
25
+ const { res, answer } = await fetchAnswer(url + endpoint, {
21
26
  method,
22
27
  redirect: 'error',
23
28
  headers: {
@@ -25,11 +30,12 @@ async function wire(url, method, endpoint, body, token) {
25
30
  ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
26
31
  },
27
32
  body: body === undefined ? undefined : JSON.stringify(body),
28
- });
29
- const data = await response.json();
30
- if (!response.ok)
31
- throw apiError(response.status, data);
32
- return data;
33
+ }, `${method} ${endpoint}`, timeoutMs);
34
+ if (!res.ok)
35
+ throw answerError(res.status, answer);
36
+ if (answer.kind === 'text')
37
+ die('Phantom AI sent a web page instead of data. Check PHANTOM_BASE_URL, and try again in a minute.', 'bad_answer');
38
+ return answer.json;
33
39
  }
34
40
  function credentials(input) {
35
41
  const file = credentialPath(input.env);
@@ -40,6 +46,14 @@ function credentials(input) {
40
46
  die('This workspace belongs to a different API address. Run phantom login for this address.', 'workspace_origin');
41
47
  return saved;
42
48
  }
49
+ /** The workspace `phantom login` saved for this API address, or null when it saved none or saved one for another address. */
50
+ export function savedWorkspace(input) {
51
+ const file = credentialPath(input.env);
52
+ if (!existsSync(file))
53
+ return null;
54
+ const saved = JSON.parse(readSecret(input.env, file));
55
+ return saved.base_url === base(input) ? saved : null;
56
+ }
43
57
  /** The management credential `phantom login` saved for this API address, or null when it saved none. */
44
58
  export function savedManagement(input) {
45
59
  return existsSync(credentialPath(input.env)) ? credentials(input).management_credential : null;
@@ -77,7 +91,7 @@ export async function workspaceLogin(input, opts = {}) {
77
91
  value: 'browser',
78
92
  },
79
93
  {
80
- label: 'Just show the link',
94
+ label: 'Show the link',
81
95
  hint: 'to open it yourself, or on another device',
82
96
  value: 'link',
83
97
  },
@@ -115,7 +129,7 @@ export async function workspaceLogin(input, opts = {}) {
115
129
  ` ${p.dim('Open')} ${p.bold(start.verification_uri_complete)}\n` +
116
130
  ` ${p.dim('Code')} ${p.lime(p.bold(start.user_code))} ${p.dim('check that the page shows the same code, then approve')}\n\n` +
117
131
  // In color the spinner below draws this line, so it moves while sign-in waits.
118
- (lit ? '' : ` ${p.dim('Waiting for you to approve...')}\n`) +
132
+ (lit ? '' : ` ${p.dim('Waiting for you to approve…')}\n`) +
119
133
  (pick ? ` ${p.dim('esc or ctrl+c to cancel')}\n` : ''));
120
134
  if (!noBrowser)
121
135
  openUrl(start.verification_uri_complete);
@@ -154,8 +168,8 @@ function alreadySignedIn(input) {
154
168
  io.stdout(JSON.stringify(result) + '\n');
155
169
  return 0;
156
170
  }
157
- /** A spinner on one line: `⠋ Waiting for you to approve...` until stopped, then `✓ Approved.` or nothing. */
158
- function waiting(write, p, words = 'Waiting for you to approve...', doneWords = 'Approved.') {
171
+ /** A spinner on one line: `⠋ Waiting for you to approve…` until stopped, then `✓ Approved.` or nothing. */
172
+ function waiting(write, p, words = 'Waiting for you to approve…', doneWords = 'Approved.') {
159
173
  const frames = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';
160
174
  let k = 0;
161
175
  const draw = () => write(`\r ${p.lime(frames[k++ % frames.length])} ${p.dim(words)}`);
@@ -194,15 +208,18 @@ async function pollForApproval(input, opts, ctx) {
194
208
  io.stderr(' Sign-in cancelled. Nothing was saved.\n');
195
209
  return 0;
196
210
  }
211
+ // The sleep may have used up the time. One stuck request must not carry the wait past the deadline.
212
+ const left = deadline - Date.now();
213
+ if (left <= 0)
214
+ break;
197
215
  let token;
198
216
  try {
199
- token = await wire(url, 'POST', '/auth/device/token', {
200
- device_code: start.device_code,
201
- });
217
+ token = await wire(url, 'POST', '/auth/device/token', { device_code: start.device_code }, undefined, Math.min(REQUEST_TIMEOUT_MS, left));
202
218
  }
203
219
  catch (error) {
204
220
  const code = error.code;
205
- if (code === 'authorization_pending')
221
+ // One poll that got no answer is not the end: ask again until the deadline.
222
+ if (code === 'authorization_pending' || code === 'request_timeout')
206
223
  continue;
207
224
  if (code === 'slow_down') {
208
225
  interval += 5000;
@@ -226,7 +243,7 @@ async function pollForApproval(input, opts, ctx) {
226
243
  saveNamedKey(env, name, token.api_key);
227
244
  }
228
245
  catch (error) {
229
- io.stderr('phantom could not save the connection. Sign in or restore your workspace to revoke the device key and reconnect.\n');
246
+ io.stderr('phantom signed you in but could not save the sign-in on this computer. Fix the error below and run phantom login again. Then revoke the key this sign-in made with phantom keys revoke.\n');
230
247
  throw error;
231
248
  }
232
249
  if (opts.inSetup) {
@@ -244,10 +261,10 @@ async function pollForApproval(input, opts, ctx) {
244
261
  return 0;
245
262
  }
246
263
  io.stdout(JSON.stringify(result) + '\n');
247
- io.stderr('Ready. Run phantom claude, phantom codex or phantom pi. Guests can export recovery with phantom workspace export --file <path>.\n');
264
+ io.stderr('Signed in. Start an agent with phantom claude, phantom codex or phantom pi. A guest workspace can save its recovery file with phantom workspace export --file <path>.\n');
248
265
  return 0;
249
266
  }
250
- die('Device code expired. Run phantom login again.', 'login_expired');
267
+ die('The sign-in code expired before it was approved. Run phantom login again.', 'login_expired');
251
268
  }
252
269
  /** Manage a workspace from the terminal: balance, keys, funding, recovery and revocation. */
253
270
  export async function workspaceCommand(input) {
@@ -275,10 +292,10 @@ export async function workspaceCommand(input) {
275
292
  die('Use phantom workspace import --file <recovery-file>.');
276
293
  const recovery = JSON.parse(readFileSync(flags.file, 'utf8'));
277
294
  if (!recovery || recovery.version !== 1)
278
- die('Invalid recovery file.');
295
+ die(`${flags.file} is not a recovery file from phantom workspace export.`);
279
296
  await wire(base(input), 'GET', '/workspaces/' + encodeURIComponent(recovery.workspace_id), undefined, recovery.management_credential);
280
297
  writeSecret(env, credentialPath(env), JSON.stringify({ ...recovery, base_url: base(input), recovery }));
281
- 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. Use phantom keys create to save a new API key.\n');
298
+ 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');
282
299
  return 0;
283
300
  }
284
301
  const saved = credentials(input);
@@ -292,12 +309,14 @@ export async function workspaceCommand(input) {
292
309
  mode: 0o600,
293
310
  flag: 'wx',
294
311
  });
295
- 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 exported. Keep that file private; it grants workspace management.\n');
312
+ 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`);
296
313
  return 0;
297
314
  }
298
315
  if (command === 'create' || command === 'rotate') {
299
316
  if (flags.save === true)
300
317
  die('--save requires a key name.');
318
+ // Checked before anything is sent: a mistyped limit must not turn into "no limit".
319
+ const typedLimit = limitFlag(flags, 'limit', true);
301
320
  // keys create at a terminal with nothing given: a short form (name, then limit), and the key to hand over.
302
321
  if (command === 'create' && flags.save === undefined && flags.limit === undefined) {
303
322
  const pick = pickIo(input);
@@ -315,12 +334,9 @@ export async function workspaceCommand(input) {
315
334
  const replacing = existsSync(target);
316
335
  if (replacing && name !== mine)
317
336
  die(`A key is already saved here as "${name}". Pick another name with --save <name>.`, 'key_exists');
318
- const limit = flags.limit === undefined ? null : Number(flags.limit);
337
+ const limit = typedLimit ?? null;
319
338
  const result = await wire(saved.base_url, 'POST', command === 'create' ? endpoint + '/keys' : endpoint + '/keys/' + String(id), command === 'create' ? { name, limit_usd: limit } : { action: 'rotate' }, saved.management_credential);
320
- if (name === 'default')
321
- saveApiKey(env, result.api_key);
322
- else
323
- saveNamedKey(env, name, result.api_key, { replace: replacing });
339
+ saveIssuedKey(input, name, result.api_key, { replace: replacing, rotated: command === 'rotate' });
324
340
  io.stdout(showsScreen(input)
325
341
  ? keyChangeScreen(command === 'create' ? 'created' : 'rotated', name, {
326
342
  env,
@@ -361,6 +377,13 @@ export async function workspaceCommand(input) {
361
377
  return 0;
362
378
  }
363
379
  if (command === 'set') {
380
+ // Every value is checked before the server is asked anything, so a typo changes nothing.
381
+ const typed = {
382
+ limit_usd: limitFlag(flags, 'limit', true),
383
+ budget_usd: limitFlag(flags, 'budget', true),
384
+ period_days: limitFlag(flags, 'period'),
385
+ rate_usd_per_min: limitFlag(flags, 'rate', true),
386
+ };
364
387
  const which = await whichKey(input, saved, endpoint, 'change');
365
388
  if (which === null)
366
389
  return 0;
@@ -372,18 +395,12 @@ export async function workspaceCommand(input) {
372
395
  const limit = await chooseLimit(pick);
373
396
  if (limit === undefined)
374
397
  return 0;
375
- flags.limit = limit === null ? 'none' : String(limit);
398
+ typed.limit_usd = limit;
376
399
  }
377
400
  const body = {};
378
- const controls = {
379
- limit_usd: flags.limit,
380
- budget_usd: flags.budget,
381
- period_days: flags.period,
382
- rate_usd_per_min: flags.rate,
383
- };
384
- for (const [field, value] of Object.entries(controls))
401
+ for (const [field, value] of Object.entries(typed))
385
402
  if (value !== undefined)
386
- body[field] = value === 'none' ? null : Number(value);
403
+ body[field] = value;
387
404
  if (typeof flags.name === 'string')
388
405
  body.name = flags.name;
389
406
  if (typeof flags['policy-file'] === 'string')
@@ -467,7 +484,7 @@ export async function workspaceCommand(input) {
467
484
  return leaveFund(input);
468
485
  }
469
486
  if (amount === undefined || !method)
470
- die(`fund needs how much and how to pay. ${FUND_EXAMPLE}`, 'fund_usage');
487
+ die(`fund needs an amount and a way to pay. ${FUND_EXAMPLE}`, 'fund_usage');
471
488
  const result = await wire(saved.base_url, 'POST', endpoint + '/fund', {
472
489
  method: method === 'card' ? 'card' : 'crypto',
473
490
  amount_usd: amount,
@@ -542,6 +559,8 @@ function leaveFund(input) {
542
559
  input.io.stderr(' Nothing was charged.\n');
543
560
  return 0;
544
561
  }
562
+ /** Keys that still work. A rotate or revoke leaves the old key in the list, turned off. */
563
+ const stillOn = (keys) => keys.filter((k) => k.is_active !== false);
545
564
  /**
546
565
  * The key a key command acts on. --id may be the id, its first few
547
566
  * characters, the key's name, or the start of the key, the way people
@@ -560,7 +579,7 @@ async function whichKey(input, saved, endpoint, verb) {
560
579
  const pick = pickIo(input);
561
580
  if (!pick)
562
581
  die(`Say which key with --id: its id, name or start. For example: phantom keys ${verb === 'change' ? 'set' : verb} --id CI${verb === 'change' ? ' --limit 5' : ''}`, 'key_usage');
563
- const chosen = await choose(pick, `Which key do you want to ${verb}?`, view.keys.map((k) => ({
582
+ const chosen = await choose(pick, `Which key do you want to ${verb}?`, stillOn(view.keys).map((k) => ({
564
583
  label: k.name ?? 'Key',
565
584
  hint: `${k.prefix ?? ''} · id ${k.id.slice(0, 8)} · spent $${(k.spent_usd ?? 0).toFixed(2)}`,
566
585
  value: k.id,
@@ -571,17 +590,28 @@ async function whichKey(input, saved, endpoint, verb) {
571
590
  input.io.stderr(' Nothing was changed.\n');
572
591
  return chosen === null ? null : named(chosen);
573
592
  }
574
- /** Finds one key by id, the start of its id, its name, or the start of the key itself. Refuses when none or more than one matches. */
575
- export function findKey(keys, typed) {
593
+ /**
594
+ * Finds one key by id, the start of its id, its name, or the start of the key itself. Refuses when none or more than one matches.
595
+ * Keys that are turned off never match: after a rotate, the old key and the new one share a name.
596
+ */
597
+ export function findKey(allKeys, typed) {
598
+ const keys = stillOn(allKeys);
576
599
  const t = typed.trim().toLowerCase();
577
- const hits = keys.filter((k) => k.id.toLowerCase() === t);
578
- const loose = hits.length ? hits : keys.filter((k) => (t.length >= 4 && k.id.toLowerCase().startsWith(t)) || k.name?.toLowerCase() === t || (t.length >= 8 && k.prefix?.toLowerCase().startsWith(t)));
579
- const list = keys.map((k) => `${k.name ?? 'Key'} (${k.id.slice(0, 8)})`).join(', ');
600
+ const matching = (list) => {
601
+ const hits = list.filter((k) => k.id.toLowerCase() === t);
602
+ return hits.length ? hits : list.filter((k) => (t.length >= 4 && k.id.toLowerCase().startsWith(t)) || k.name?.toLowerCase() === t || (t.length >= 8 && k.prefix?.toLowerCase().startsWith(t)));
603
+ };
604
+ const loose = matching(keys);
605
+ const label = (k) => `${k.name ?? 'Key'} (${k.id.slice(0, 8)})`;
580
606
  if (loose.length === 1)
581
607
  return loose[0].id;
582
- if (!loose.length)
583
- die(`No key matches "${typed}". Your keys: ${list || 'none yet'}.`, 'key_not_found');
584
- die(`"${typed}" matches more than one key: ${loose.map((k) => `${k.name ?? 'Key'} (${k.id.slice(0, 8)})`).join(', ')}. Use more of the id.`, 'key_ambiguous');
608
+ if (!loose.length) {
609
+ const off = matching(allKeys.filter((k) => k.is_active === false));
610
+ if (off.length)
611
+ 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');
612
+ die(`No key matches "${typed}". Your keys: ${keys.map(label).join(', ') || 'none yet'}.`, 'key_not_found');
613
+ }
614
+ die(`"${typed}" matches more than one key: ${loose.map(label).join(', ')}. Use more of the id.`, 'key_ambiguous');
585
615
  }
586
616
  /** The name a key with this id is saved under on this computer, if any: `default` for the login key. */
587
617
  function savedNameFor(env, id) {
@@ -601,7 +631,7 @@ function savedNameFor(env, id) {
601
631
  }
602
632
  /** A limit picker: no limit, or a few round amounts. undefined means Esc. */
603
633
  async function chooseLimit(pick) {
604
- const limit = await choose({ ...pick, esc: 'back' }, 'Spending limit for this key?', [
634
+ const limit = await choose({ ...pick, esc: 'back' }, 'How much may this key spend in total?', [
605
635
  {
606
636
  label: 'No limit',
607
637
  hint: 'it can spend the whole workspace balance',
@@ -632,7 +662,7 @@ async function newKeyForm(input, pick, saved, endpoint) {
632
662
  if (limit === undefined)
633
663
  return leaveKeys(input);
634
664
  const result = await wire(saved.base_url, 'POST', endpoint + '/keys', { name, limit_usd: limit }, saved.management_credential);
635
- saveNamedKey(env, name, result.api_key);
665
+ saveIssuedKey(input, name, result.api_key, { rotated: false });
636
666
  const style = {
637
667
  env,
638
668
  color: colorOn(env, io.stdoutIsTTY),
@@ -656,6 +686,30 @@ async function newKeyForm(input, pick, saved, endpoint) {
656
686
  }
657
687
  return 0;
658
688
  }
689
+ /**
690
+ * Saves a key the server has just made. When the save fails (a read-only file, a locked Keychain over
691
+ * SSH), this computer is the only place the key ever exists, so it goes to stderr once with how to
692
+ * save it, and the command exits 1. After a rotate the old key is already off, and the message says so.
693
+ */
694
+ function saveIssuedKey(input, name, key, opts) {
695
+ const { env, io } = input;
696
+ try {
697
+ if (name === 'default')
698
+ saveApiKey(env, key);
699
+ else
700
+ saveNamedKey(env, name, key, { replace: opts.replace });
701
+ }
702
+ catch (error) {
703
+ const why = error instanceof Error ? error.message : String(error);
704
+ const how = name === 'default' ? 'phantom login --paste (paste the key when it asks)' : `phantom keys save ${name} (paste the key when it asks)`;
705
+ io.stderr(`\nphantom made your new key but could not save it on this computer: ${why}\n` +
706
+ (opts.rotated ? 'Your old key is turned off, so this new key is the only one that works.\n' : '') +
707
+ 'This is the only time it is shown. Copy it somewhere private now; it works like a password:\n\n' +
708
+ ` ${key}\n\n` +
709
+ `Save it once the problem is fixed with: ${how}\n`);
710
+ die('The new key was not saved here.', 'key_not_saved');
711
+ }
712
+ }
659
713
  /** Esc out of a key form: back to the menu if it started this, otherwise say nothing changed. */
660
714
  function leaveKeys(input) {
661
715
  if (input.io.fromMenu)
@@ -675,7 +729,7 @@ async function waitForPayment(input, pick, saved, endpoint, paymentId) {
675
729
  const { env, io } = input;
676
730
  const p = paint(env, colorOn(env, io.isTTY));
677
731
  io.stderr(` ${p.dim('esc to stop waiting')}\n`);
678
- const spinner = colorOn(env, io.isTTY) ? waiting(io.stderr, p, 'Waiting for your payment...', 'Payment received.') : null;
732
+ const spinner = colorOn(env, io.isTTY) ? waiting(io.stderr, p, 'Waiting for your payment…', 'Payment received.') : null;
679
733
  const cancel = cancelKeys((pick.keys ?? keyboard)());
680
734
  const deadline = Date.now() + PAYMENT_WAIT_MS;
681
735
  try {
@@ -695,12 +749,12 @@ async function waitForPayment(input, pick, saved, endpoint, paymentId) {
695
749
  throw new Cancelled();
696
750
  if (key) {
697
751
  spinner?.stop();
698
- io.stderr(` ${p.dim('Stopped waiting. If you finish paying, the credit still lands: check Balance.')}\n`);
752
+ io.stderr(` ${p.dim('Stopped waiting. If you finish paying, the credit still arrives: check Balance.')}\n`);
699
753
  return;
700
754
  }
701
755
  }
702
756
  spinner?.stop();
703
- io.stderr(` ${p.dim('No payment yet. If you finish paying, the credit still lands: check Balance.')}\n`);
757
+ io.stderr(` ${p.dim('No payment yet. If you finish paying, the credit still arrives: check Balance.')}\n`);
704
758
  }
705
759
  finally {
706
760
  spinner?.stop();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@phantomcodes/cli",
3
- "version": "1.4.1",
4
- "description": "AI inference for your coding agents. Route models, control spending, and fund your workspace.",
3
+ "version": "1.4.3",
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",
7
7
  "api-key",
@@ -9,23 +9,23 @@
9
9
  "llm",
10
10
  "inference",
11
11
  "cli",
12
- "mcp",
12
+ "openai-compatible",
13
13
  "pi-package",
14
14
  "agent-skill",
15
15
  "claude-code",
16
16
  "codex",
17
17
  "cursor",
18
- "model-context-protocol",
18
+ "opencode",
19
19
  "ai-agents",
20
20
  "solana",
21
- "wallet",
22
- "subagents"
21
+ "usdc",
22
+ "wallet"
23
23
  ],
24
24
  "homepage": "https://phantom.codes/",
25
25
  "repository": {
26
26
  "type": "git",
27
27
  "url": "git+https://github.com/connortessaro/phantom.git",
28
- "directory": "packages/cli"
28
+ "directory": "cli"
29
29
  },
30
30
  "type": "module",
31
31
  "bin": {