@phantomcodes/cli 1.4.2 → 1.4.4

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.
@@ -7,7 +7,7 @@ import { verifyCommand } from "../receipts/command.mjs";
7
7
  import { setupCommand } from "../setup/command.mjs";
8
8
  import { SETUP_MODEL } from "../setup/shared.mjs";
9
9
  import { modelsCommand } from "../models/command.mjs";
10
- import { SETUP_NAMES, orList } from "../setup/agents.mjs";
10
+ import { SETUP_NAMES } from "../setup/agents.mjs";
11
11
  /** The short `--help`'s headings, in the order they print. */
12
12
  export const HELP_GROUPS = ['Start', 'Run', 'Money', 'Keys', 'Routing', 'More'];
13
13
  async function loginDispatch(input) {
@@ -29,73 +29,111 @@ async function fundDispatch(input) {
29
29
  void flags['no-browser'];
30
30
  return workspaceCommand({ ...input, subcommand: 'fund' });
31
31
  }
32
- /** The definitions used by CLI dispatch, help, and generated documentation. */
32
+ /**
33
+ * The definitions used by CLI dispatch, help, and generated documentation.
34
+ * `run()` reads each command's flags from its `help`, so every flag a command
35
+ * takes must appear there as `--name`.
36
+ */
33
37
  export const COMMANDS = [
34
38
  {
35
39
  name: 'login', handler: loginDispatch, keyless: true,
36
40
  group: 'Start', summary: 'sign in only, or save a Phantom key you already have',
37
- help: ` login [--save <name>] [--no-browser] sign in by device code: an account or a guest workspace
38
- login --paste save a Phantom key you already have (it asks for it)`,
41
+ help: ` login [--save <name>] [--no-browser]
42
+ sign in by approving a short code in the
43
+ browser, with an account or as a guest;
44
+ --save names the key
45
+ login --paste save a Phantom key you already have; it asks for
46
+ the key, so it stays out of your shell history`,
39
47
  },
40
48
  {
41
49
  name: 'workspace', handler: workspaceCommand, keyless: true,
42
- group: 'More', summary: 'the whole workspace: balance, recovery and access',
43
- help: ` workspace [status] shared balance, keys, recent usage and management access
44
- workspace payment --id <payment-id> check verified funding status
45
- workspace export --file <path> export private guest recovery; refuses overwrites
46
- workspace import --file <path> restore a guest, then issue replacement keys
47
- workspace revoke-access --id <id> revoke a browser, device or recovery credential
48
- workspace delete [--yes] delete an empty workspace and forget it here (--yes: don't ask)`,
50
+ group: 'More', summary: 'the shared balance, keys, recovery and sign-ins',
51
+ help: ` workspace [status] the shared balance, each key, the latest calls
52
+ and the sign-ins that can manage the workspace
53
+ workspace payment --id <payment-id>
54
+ whether a payment has arrived
55
+ workspace export --file <path> save a guest workspace's recovery file; it won't
56
+ overwrite a file that exists
57
+ workspace import --file <path> sign in to a guest workspace from its recovery
58
+ file, then make a key with phantom keys create
59
+ workspace revoke-access --id <id> stop a browser, device or recovery file from
60
+ managing the workspace
61
+ workspace delete [--yes] delete an empty workspace and forget it here
62
+ (--yes: don't ask)`,
49
63
  },
50
64
  {
51
65
  name: 'fund', handler: fundDispatch, keyless: true,
52
66
  group: 'Money', summary: 'add credit by card or crypto',
53
67
  help: ` fund --amount <USD> [--card | --coin usdc|usdc-base] [--no-browser]
54
- fund your workspace balance with card (plus Stripe's fee) or crypto`,
68
+ add credit to your workspace by card (plus
69
+ Stripe's fee), or USDC on Solana (usdc) or Base
70
+ (usdc-base); --no-browser prints the link`,
55
71
  },
56
72
  {
57
73
  name: 'keys', handler: workspaceCommand, keyless: true,
58
74
  group: 'Keys', summary: "your workspace's keys: list, create, set limits, revoke",
59
- help: ` keys [list] remote workspace key metadata, never secrets
75
+ help: ` keys [list] the workspace's keys: name, id, spend and limit;
76
+ never the keys themselves
60
77
  keys create [--save <name>] [--limit <USD|none>]
78
+ make a key and save it on this computer; --limit
79
+ caps what it can spend in total
61
80
  keys set --id <id> [--limit <USD|none>] [--budget <USD|none>]
62
81
  [--period <days|none>] [--rate <USD|none>] [--name <name>]
63
82
  [--policy-file <path> | --clear-policy]
64
- keys rotate --id <id> [--save <name>] replace only the corresponding saved key
65
- keys revoke --id <id> [--yes] revoke access, keeping workspace credit (--yes: don't ask)
66
- keys saved [--balance] local saved key metadata
67
- keys save <name> [key] validate and save an existing key (prompts if omitted)
68
- keys show [name] print a secret for shell integration only
69
- keys show [name] --copy copy it to the clipboard instead (Mac), for an app's settings
70
- keys rm <name> forget a local copy; remote key keeps working`,
83
+ change a key: its total limit, a budget for each
84
+ period of days, dollars a minute, its name or
85
+ its route policy
86
+ keys rotate --id <id> [--save <name>]
87
+ swap a key for a new one with the same settings;
88
+ the old one stops working, and the copy saved
89
+ here is replaced
90
+ keys revoke --id <id> [--yes] turn a key off for good; its credit stays in the
91
+ workspace (--yes: don't ask)
92
+ keys saved [--balance] the keys saved on this computer (--balance adds
93
+ each one's credit)
94
+ keys save <name> [key] check a key and save it by name; it asks for the
95
+ key when you leave it out
96
+ keys show [name] print a saved key, for PHANTOM_API_KEY=$(...) in
97
+ a shell; keep it out of chat and logs
98
+ keys show [name] --copy copy it to the clipboard instead (Mac), for an
99
+ app's settings
100
+ keys rm <name> forget a key saved here; the key keeps working`,
71
101
  },
72
102
  {
73
103
  name: 'claude', handler: agentCommand, keyless: true,
74
104
  group: 'Run', summary: 'start Claude Code on Phantom AI',
75
- help: ` claude [--key <name>] [--no-browser] -- <agent arguments>`,
105
+ help: ` claude [--key <name>] [--no-browser] -- <agent arguments>
106
+ start Claude Code on Phantom AI; --key picks a
107
+ key saved by name`,
76
108
  },
77
109
  {
78
110
  name: 'codex', handler: agentCommand, keyless: true,
79
111
  group: 'Run', summary: 'start Codex on Phantom AI',
80
- help: ` codex [--key <name>] [--no-browser] -- <agent arguments>`,
112
+ help: ` codex [--key <name>] [--no-browser] -- <agent arguments>
113
+ start Codex on Phantom AI; --key picks a key
114
+ saved by name`,
81
115
  },
82
116
  {
83
117
  name: 'pi', handler: agentCommand, keyless: true,
84
118
  group: 'Run', summary: 'start pi on Phantom AI',
85
119
  help: ` pi [--key <name>] [--no-browser] -- <agent arguments>
86
- run with a saved key`,
120
+ start pi on Phantom AI; --key picks a key saved
121
+ by name`,
87
122
  },
88
123
  {
89
124
  name: 'balance', handler: balanceCommand,
90
125
  group: 'Money', summary: 'your credit, and when it expires',
91
- help: ` balance show credit balance and expiry`,
126
+ help: ` balance what this key can spend, and when it expires`,
92
127
  },
93
128
  {
94
129
  name: 'spend', handler: spendCommand, keyless: ['--workspace'],
95
130
  group: 'Money', summary: 'what you spent, and what phantom-1 saved',
96
- help: ` spend [--from <date>] [--to <date>] what this key spent, by model and day, and what phantom-1
97
- saved; dates are UTC days as YYYY-MM-DD, default this month
98
- spend --workspace every key in the workspace by name (needs phantom login)`,
131
+ help: ` spend [--from <date>] [--to <date>]
132
+ what this key spent, by model and day, and what
133
+ phantom-1 saved; dates are UTC days as
134
+ YYYY-MM-DD, this month by default
135
+ spend --workspace every key in the workspace by name (needs
136
+ phantom login)`,
99
137
  },
100
138
  {
101
139
  name: 'key', advanced: true, handler: keyCommand, keyless: true,
@@ -104,20 +142,29 @@ export const COMMANDS = [
104
142
  key list [--balance] saved keys, by name and id
105
143
  key save <name> [key] save a key by name (prompts if no key is given)
106
144
  key show [name] print a saved key, for PHANTOM_API_KEY=$(...);
107
- no name prints the key phantom is using
145
+ with no name, the key phantom is using
108
146
  key rm <name> forget a saved key (the key keeps working)`,
109
147
  },
110
148
  {
111
149
  name: 'route', handler: routeCommand,
112
150
  group: 'Routing', summary: 'which models "auto" runs, and rules for picking',
113
- help: ` route [get] show which model "auto" runs, and why
151
+ help: ` route [get] which model "auto" runs for this key, and why
114
152
  route set --sort fast|cheap|throughput|default
115
- which providers serve this key's models first: fast
116
- starts answering soonest; cheap is the default
117
- route set --models a,b,c models for "auto", first is the default
118
- [--applies-to auto|all] [--on-empty stop|cheapest] [--fallback]
119
- [--stick-minutes n] keep a conversation's model this long (default 5)
120
- [--stick-by-prompt false] only x-phantom-session marks a conversation
153
+ which providers serve this key's models first:
154
+ fast starts answering soonest, throughput sends
155
+ the most tokens a second, cheap costs least and
156
+ is the default; default goes back to cheap
157
+ route set --models a,b,c the models "auto" picks from; the first is the
158
+ default
159
+ [--applies-to auto|all] all: route requests that name a model too
160
+ [--on-empty stop|cheapest]
161
+ when the cap is used up: refuse requests, or
162
+ run them on the cheapest model
163
+ [--fallback] try the next model when one fails
164
+ [--stick-minutes n] keep a conversation on its model this long
165
+ (default 5)
166
+ [--stick-by-prompt false]
167
+ only x-phantom-session marks a conversation
121
168
  route set --file policy.json replace the whole policy
122
169
  route rule add --if <name=value> --use <model|cheapest|first|next> [--at n]
123
170
  conditions: pace, budget_left_pct_below,
@@ -130,9 +177,11 @@ export const COMMANDS = [
130
177
  {
131
178
  name: 'lineup', handler: lineupCommand,
132
179
  group: 'Routing', summary: 'the model phantom-1 runs in each tier',
133
- help: ` lineup [get] show the model phantom-1 runs in each tier, and the choices
134
- lineup set --economy <model> pick the model for a tier; "default" goes back to the default
135
- [--standard <model>] [--frontier <model>]
180
+ help: ` lineup [get] the model phantom-1 runs in each tier, and the
181
+ models you can pick from
182
+ lineup set --economy <model> pick the model for a tier; "default" puts the
183
+ [--standard <model>] tier back to its default
184
+ [--frontier <model>]
136
185
  [--economy-fallback <model>] [--standard-fallback <model>]
137
186
  [--frontier-fallback <model>]
138
187
  the model to try when a tier's model fails
@@ -141,45 +190,48 @@ export const COMMANDS = [
141
190
  {
142
191
  name: 'models', handler: modelsCommand, keyless: true,
143
192
  group: 'Routing', summary: 'phantom-1, free or zdr: what each can do, and which your agents use',
144
- help: ` models what phantom-1, phantom-1:free and phantom-1:zdr can do,
145
- and the model behind each job; at a terminal, pick one
193
+ help: ` models what phantom-1, phantom-1:free and phantom-1:zdr
194
+ can do, and the model behind each job; at a
195
+ terminal, pick one
146
196
  models use <id> start your agents on it, without the menu`,
147
197
  },
148
198
  {
149
199
  name: 'logout', handler: logoutDispatch, keyless: true,
150
200
  group: 'More', summary: 'sign out on this computer',
151
- help: ` logout sign out: forget workspace access and the default saved key
201
+ help: ` logout sign out: forget workspace access and the
202
+ default saved key
152
203
  logout --all also forget every key saved here by name`,
153
204
  },
154
205
  {
155
206
  name: 'setup', handler: setupCommand, keyless: true,
156
207
  group: 'Start', summary: 'sign in and connect your coding agents',
157
- help: ` setup set up every agent found: install the skill and
158
- point its model calls at Phantom AI; shows each
159
- file's changes and asks first. With no key yet,
160
- signs in first (in a terminal)
208
+ help: ` setup find your agents, install the skill in each, and
209
+ point their model calls at Phantom AI; it shows
210
+ each file's changes and asks first. With no key
211
+ yet, it signs you in first (at a terminal)
161
212
  [--yes] don't ask
162
213
  [--no-browser] print the sign-in link instead of opening it
163
- [--dry-run] preview the changes without making them
214
+ [--dry-run] show the changes without making them
164
215
  [--diff] show every line each file gains or loses
165
- [--no-shell] leave your shell startup file alone and list
216
+ [--no-shell] leave your shell startup file alone and print
166
217
  the lines to add yourself
167
218
  [--limit <USD|none>] cap what this key can spend each month
168
- [--json] print JSON in a terminal too (a pipe always gets JSON)
219
+ [--json] print JSON at a terminal too (a pipe always gets JSON)
169
220
  [--model <id>] the model each agent starts on (default ${SETUP_MODEL})
170
221
  setup --agent <name> install the skill for one agent, without asking:
171
- ${orList(SETUP_NAMES)}
172
- or all
222
+ ${SETUP_NAMES.join(', ')} or all
173
223
  setup [--agent <name>] --provider point that agent's model calls at Phantom AI;
174
- --provider off removes only what phantom wrote
224
+ --provider off takes phantom's settings out and
225
+ puts back what they replaced
175
226
  setup --restore [--agent <name>] put back the files setup changed, from the
176
227
  .phantom.bak copies it kept`,
177
228
  },
178
229
  {
179
230
  name: 'verify', advanced: true, handler: verifyCommand, keyless: ['--receipt'],
180
231
  group: 'More', summary: 'check a signed receipt',
181
- help: ` verify --model <id> make one tiny call and check its signed receipt
182
- names the model you asked for (costs a fraction of a cent)
232
+ help: ` verify --model <id> make one small call and check that its signed
233
+ receipt names the model you asked for (costs a
234
+ fraction of a cent)
183
235
  verify --receipt <receipt> check a receipt you already have`,
184
236
  },
185
237
  ];
package/dist/cli/help.mjs CHANGED
@@ -10,8 +10,10 @@ export const ENV_VARS = [
10
10
  { name: 'PHANTOM_BASE_URL', about: `API base, https:// only (default ${DEFAULT_BASE_URL})` },
11
11
  { name: 'PHANTOM_STATE_DIR', about: 'where phantom keeps keys (default ~/.config/phantom-key)' },
12
12
  { name: 'PHANTOM_KEYCHAIN', about: '0 saves keys to files instead of the macOS Keychain; 1 uses the Keychain on any system, which fails where /usr/bin/security is missing' },
13
- { name: 'PAI_KEYCHAIN', about: 'The old name of PHANTOM_KEYCHAIN, read when PHANTOM_KEYCHAIN is unset' },
13
+ { name: 'PAI_KEYCHAIN', about: 'the old name of PHANTOM_KEYCHAIN, read when PHANTOM_KEYCHAIN is unset' },
14
14
  ];
15
+ /** The first line of both helps: what phantom is for. */
16
+ const TITLE = 'phantom: points your coding agents at Phantom AI';
15
17
  function envHelp() {
16
18
  const width = Math.max(...ENV_VARS.map((v) => v.name.length)) + 2;
17
19
  const lines = ENV_VARS.map((v) => ` ${v.name.padEnd(width)}${v.about}${v.envOnly ? ' (environment only)' : ''}`);
@@ -19,15 +21,16 @@ function envHelp() {
19
21
  }
20
22
  /** Full command reference, printed by `phantom --help --all`. */
21
23
  export const HELP = `
22
- phantom — points your coding agents at Phantom AI
24
+ ${TITLE}
23
25
 
24
26
  Commands:
25
27
  ${COMMANDS.map((command) => command.help).join('\n')}
26
28
 
27
29
  Flags:
28
- --table human-readable output instead of JSON
30
+ --table draw the screen for people, even in a pipe
31
+ --json print JSON, even at a terminal
29
32
  --help, -h print help and run nothing
30
- --all include advanced commands in help
33
+ --all with --help, also list the advanced commands
31
34
  --version, -v print the version
32
35
 
33
36
  ${envHelp()}
@@ -43,7 +46,7 @@ const helpRow = (name, summary) => ` ${name.padEnd(20)}${summary}`;
43
46
  * `phantom <command> --help` and `--help --all` keep the full usage.
44
47
  */
45
48
  export const PRIMARY_HELP = [
46
- 'phantom — points your coding agents at Phantom AI',
49
+ TITLE,
47
50
  '',
48
51
  ...HELP_GROUPS.flatMap((group) => {
49
52
  const shown = COMMANDS.filter((command) => command.group === group && !command.advanced).sort((a, b) => rank(a.name) - rank(b.name));
@@ -54,5 +57,6 @@ export const PRIMARY_HELP = [
54
57
  return rows.length ? [group.toUpperCase(), ...rows, ''] : [];
55
58
  }),
56
59
  'phantom <command> --help shows its flags. phantom --help --all lists every flag,',
57
- 'the advanced commands (receipts and verification) and the environment variables.',
60
+ 'the advanced commands (verify, for receipts, and the older key commands) and the',
61
+ 'environment variables.',
58
62
  ].join('\n');
@@ -107,9 +107,9 @@ export type LineupView = {
107
107
  };
108
108
  /** What each tier is for, in a few words. */
109
109
  export declare const TIER_ABOUT: {
110
- readonly economy: "short, easy requests";
111
- readonly standard: "everyday coding";
112
- readonly frontier: "the hardest work";
110
+ readonly economy: "phantom-1:free only; paid calls skip it";
111
+ readonly standard: "where every task starts";
112
+ readonly frontier: "hard steps: a failed try, an image";
113
113
  };
114
114
  /** `phantom lineup`: the model phantom-1 runs in each tier, whether it's the default or your pick, and its fallback. */
115
115
  export declare function lineupScreen(l: LineupView, style?: ScreenStyle): string;
@@ -156,7 +156,7 @@ export function workspaceScreen(view, style = {}) {
156
156
  export function keysScreen(keys, style = {}) {
157
157
  const p = paint(style.env ?? {}, Boolean(style.color));
158
158
  const w = ruleWidth(style);
159
- return ['', ...caption(p, w, 'KEYS', p.dim(String(keys.length))), ...keyRows(p, keys), ...next(p, 'Set a spending limit:', 'phantom keys set --id <name or id> --limit <USD>')].join('\n');
159
+ return ['', ...caption(p, w, 'KEYS', p.dim(String(keys.length))), ...keyRows(p, keys), ...next(p, 'Cap what a key can spend:', 'phantom keys set --id <name or id> --limit <USD>')].join('\n');
160
160
  }
161
161
  /** After `phantom login`: signed in, where the key is kept, and the next step. */
162
162
  export function signedInScreen(saved, style = {}) {
@@ -229,9 +229,9 @@ export function routeTestScreen(t, style = {}) {
229
229
  }
230
230
  /** What each tier is for, in a few words. */
231
231
  export const TIER_ABOUT = {
232
- economy: 'short, easy requests',
233
- standard: 'everyday coding',
234
- frontier: 'the hardest work',
232
+ economy: 'phantom-1:free only; paid calls skip it',
233
+ standard: 'where every task starts',
234
+ frontier: 'hard steps: a failed try, an image',
235
235
  };
236
236
  /** `phantom lineup`: the model phantom-1 runs in each tier, whether it's the default or your pick, and its fallback. */
237
237
  export function lineupScreen(l, style = {}) {
@@ -267,7 +267,7 @@ export function fundScreen(f, style = {}) {
267
267
  }
268
268
  const p = paint(style.env ?? {}, Boolean(style.color));
269
269
  const w = ruleWidth(style);
270
- 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, 'Check it landed:', `phantom workspace payment --id ${f.payment_id ?? '<id>'}`)].join('\n');
270
+ 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');
271
271
  }
272
272
  /** `phantom workspace payment`: whether a payment has come in. */
273
273
  export function paymentScreen(pay, style = {}) {
@@ -332,7 +332,7 @@ export function keySavedScreen(name, style = {}) {
332
332
  }
333
333
  /** What each of Phantom's own models is for, in a few words. */
334
334
  const MODEL_ABOUT = {
335
- 'phantom-1': 'every job; chat picks economy, standard or frontier for each request',
335
+ 'phantom-1': 'every job; chat starts each task on standard and moves hard steps to frontier',
336
336
  'phantom-1:free': `chat on free models at $0, no card; ${FREE_REQUESTS_A_DAY} requests a day, ${FREE_AGENT_REQUESTS_A_DAY} from an agent`,
337
337
  'phantom-1:zdr': 'chat on providers that keep none of your data, at their prices',
338
338
  };
@@ -350,7 +350,7 @@ export function modelsScreen(v, style = {}) {
350
350
  // Padding goes outside the color, so the row's trailing spaces can be trimmed.
351
351
  const cell = (text, color) => color(text) + ' '.repeat(Math.max(0, COLUMN - text.length));
352
352
  const row = (label, cells) => ` ${label.padEnd(LABEL)}${cells.join('')}`.trimEnd();
353
- const lines = ['', ...caption(p, ruleWidth(style), 'MODELS', p.dim('one name each; your agents send it'))];
353
+ const lines = ['', ...caption(p, ruleWidth(style), 'MODELS', p.dim('each is a model name your agents can send'))];
354
354
  lines.push(row('', v.models.map((m) => cell(m.id, p.bold))));
355
355
  lines.push(row('', v.models.map((m) => cell(m.id === v.using ? 'in use' : '', p.lime))));
356
356
  for (const [job, label] of JOBS) {
@@ -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.4.2";
2
+ export declare const VERSION = "1.4.4";
@@ -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.4.2';
2
+ export const VERSION = '1.4.4';
@@ -1,6 +1,8 @@
1
1
  import { type Env } from '../core/state.mts';
2
2
  export declare function keyPath(env: Env): string;
3
3
  export declare function namedKeyPath(env: Env, name: string): string;
4
+ /** A key's whole SHA-256 hash: the id the workspace routes name a key by (`hashKey` in web/lib/crypto.ts). */
5
+ export declare function keyHash(key: string): string;
4
6
  /** A key's id: the start of its SHA-256 hash, safe to print. */
5
7
  export declare function keyId(key: string): string;
6
8
  /** Where the key a command runs as comes from. */
@@ -25,9 +25,13 @@ export function namedKeyPath(env, name) {
25
25
  die(`Key names use letters, numbers, - and _ (up to 32): ${name}`);
26
26
  return path.join(stateDir(env), 'keys', name);
27
27
  }
28
+ /** A key's whole SHA-256 hash: the id the workspace routes name a key by (`hashKey` in web/lib/crypto.ts). */
29
+ export function keyHash(key) {
30
+ return createHash('sha256').update(key.trim()).digest('hex');
31
+ }
28
32
  /** A key's id: the start of its SHA-256 hash, safe to print. */
29
33
  export function keyId(key) {
30
- return createHash('sha256').update(key.trim()).digest('hex').slice(0, 12);
34
+ return keyHash(key).slice(0, 12);
31
35
  }
32
36
  /**
33
37
  * Which key a command runs as: the saved key named by PHANTOM_KEY_NAME, then
@@ -68,7 +72,7 @@ function writeKeyFile(env, file, key) {
68
72
  export function readNamedKey(env, name) {
69
73
  const file = namedKeyPath(env, name);
70
74
  if (!existsSync(file))
71
- die(`No saved key named ${name}. See: phantom key list`);
75
+ die(`No saved key named ${name}. See the saved keys with phantom keys saved.`);
72
76
  return readSecret(env, file).trim();
73
77
  }
74
78
  /**
@@ -62,7 +62,7 @@ export declare function aiderProvider(ctx: SetupContext, off: boolean): Provider
62
62
  * Compatible provider at `/coding-agent/v1` and is made the one Cline uses.
63
63
  * Cline reads its key only from this file, with no variable or command to
64
64
  * point it at, so this is the one config phantom writes the key into. After
65
- * `phantom rotate`, run setup again to update it.
65
+ * `phantom keys rotate`, run setup again to update it.
66
66
  */
67
67
  export declare function clineProvider(ctx: SetupContext, off: boolean): ProviderPlan;
68
68
  /** Gemini CLI's folder: `.gemini` in `$GEMINI_CLI_HOME`, else in the home folder. */
@@ -290,7 +290,7 @@ export function aiderProvider(ctx, off) {
290
290
  * Compatible provider at `/coding-agent/v1` and is made the one Cline uses.
291
291
  * Cline reads its key only from this file, with no variable or command to
292
292
  * point it at, so this is the one config phantom writes the key into. After
293
- * `phantom rotate`, run setup again to update it.
293
+ * `phantom keys rotate`, run setup again to update it.
294
294
  */
295
295
  export function clineProvider(ctx, off) {
296
296
  const file = path.join(ctx.home, '.cline', 'data', 'settings', 'providers.json');
@@ -328,7 +328,7 @@ export function clineProvider(ctx, off) {
328
328
  on: true,
329
329
  base_url: base,
330
330
  model,
331
- warnings: ['Cline keeps the key in this file (mode 600); run phantom setup --agent cline --provider again after phantom rotate', 'In the editor extension, pick OpenAI Compatible under Settings, API Provider'],
331
+ warnings: ['Cline keeps the key in this file (mode 600); run phantom setup --agent cline --provider again after phantom keys rotate', 'In the editor extension, pick OpenAI Compatible under Settings, API Provider'],
332
332
  },
333
333
  };
334
334
  }
@@ -5,8 +5,9 @@ import { die } from "../core/errors.mjs";
5
5
  import { out, pickIo } from "../core/helpers.mjs";
6
6
  import { BackToMenu, checklist, choose } from "../core/pick.mjs";
7
7
  import { request } from "../core/request.mjs";
8
- import { resolveApiKey } from "../keys/saved.mjs";
9
- import { workspaceLogin } from "../workspace/command.mjs";
8
+ import { PhantomApiError } from "../core/errors.mjs";
9
+ import { keyHash, resolveApiKey } from "../keys/saved.mjs";
10
+ import { savedWorkspace, wire, workspaceLogin } from "../workspace/command.mjs";
10
11
  import { SETUP_AGENTS, SETUP_NAMES } from "./agents.mjs";
11
12
  import { planSetup } from "./plan.mjs";
12
13
  import { applySetup, previewSetup, restoreSetup } from "./apply.mjs";
@@ -75,7 +76,7 @@ export async function setupCommand(input) {
75
76
  if (model === true)
76
77
  die('--model requires a model id, such as auto or claude-sonnet-5');
77
78
  if (flags['mcp'])
78
- die('--mcp has been removed. Phantom inference runs directly through phantom claude, phantom codex, or phantom pi.');
79
+ die('--mcp has been removed. Start your agent on Phantom AI with phantom claude, phantom codex or phantom pi.');
79
80
  const dryRun = Boolean(flags['dry-run']);
80
81
  if (flags['restore']) {
81
82
  // At a terminal, undo shows what it will put back, and asks, the way setup asks before it changes anything.
@@ -237,6 +238,28 @@ function capFlag(value) {
237
238
  die('--limit takes dollars a month above zero, such as 20, or none', 'setup_limit');
238
239
  return usd;
239
240
  }
241
+ /**
242
+ * Sets the key's monthly cap. The key alone may only tighten its caps (the
243
+ * server answers 403 to a raise or a removal), so that change goes through the
244
+ * workspace this computer is signed in to, whose credential may set any cap.
245
+ * False when the key alone may not make the change and no workspace is saved.
246
+ */
247
+ async function setMonthlyCap(input, apiKey, cap) {
248
+ const body = cap === null ? { budget_usd: null } : { budget_usd: cap, period_days: null };
249
+ try {
250
+ await request('PATCH', '/key/budget', apiKey, body, input.baseUrl);
251
+ return true;
252
+ }
253
+ catch (err) {
254
+ if (!(err instanceof PhantomApiError) || err.status !== 403)
255
+ throw err;
256
+ }
257
+ const workspace = savedWorkspace(input);
258
+ if (!workspace)
259
+ return false;
260
+ await wire(workspace.base_url, 'PATCH', `/workspaces/${encodeURIComponent(workspace.workspace_id)}/keys/${keyHash(apiKey)}`, body, workspace.management_credential);
261
+ return true;
262
+ }
240
263
  /**
241
264
  * After setup has written its files: the key's monthly spend cap (PATCH
242
265
  * /key/budget, a calendar month). `--limit` sets it; without one, setup at a
@@ -254,7 +277,7 @@ async function capAfter(input, code, limit, pick) {
254
277
  return code;
255
278
  io.stderr('\n');
256
279
  const answer = await choose(pick, 'Cap what this key can spend each month?', [
257
- { label: 'No cap', hint: 'free use is never charged', value: 0 },
280
+ { label: 'No cap', hint: 'it can spend the whole workspace balance; free models cost nothing', value: 0 },
258
281
  { label: '$10 a month', value: 10 },
259
282
  { label: '$25 a month', value: 25 },
260
283
  { label: '$50 a month', value: 50 },
@@ -263,8 +286,12 @@ async function capAfter(input, code, limit, pick) {
263
286
  return code;
264
287
  cap = answer;
265
288
  }
266
- await request('PATCH', '/key/budget', apiKey, cap === null ? { budget_usd: null } : { budget_usd: cap, period_days: null }, baseUrl);
267
289
  const p = paint(env, colorOn(env, io.isTTY));
290
+ if (!(await setMonthlyCap(input, apiKey, cap))) {
291
+ io.stderr(` ${p.yellow('!')} The key's cap is unchanged. The key alone can only lower its cap; raising or removing it needs its workspace.\n` +
292
+ ` Run ${p.cyan('phantom login')}, then ${p.cyan(`phantom setup --limit ${cap === null ? 'none' : cap}`)} again, or change it in Edit controls on phantom.codes/keys.\n`);
293
+ return 1;
294
+ }
268
295
  io.stderr(cap === null
269
296
  ? ` ${p.lime('✓')} This key has no monthly cap now.\n`
270
297
  : ` ${p.lime('✓')} This key can spend at most $${cap} a month. Change it any time: ${p.cyan('phantom setup --limit <USD|none>')}\n`);
@@ -372,8 +372,8 @@ export function shellBlock(env, fish, state, onPathFn = onPath) {
372
372
  const own = state.agents.flatMap((a) => state.lines.get(a) ?? []);
373
373
  const head = [
374
374
  BLOCK_BEGIN,
375
- '# Written by phantom setup. Sets PHANTOM_API_KEY to the key phantom uses when the',
376
- '# shell starts, for coding agents that read it. The key is not stored here.',
375
+ '# Written by phantom setup. A new shell gets PHANTOM_API_KEY from phantom,',
376
+ '# for the coding agents that read it. The key itself is not in this file.',
377
377
  `# agents: ${state.agents.join(' ')}`,
378
378
  '# Undo: phantom setup --restore',
379
379
  ];
@@ -149,7 +149,7 @@ export function setupScreen(r, opts = {}) {
149
149
  lines.push(` ${p.dim('Undo:')} phantom keeps a copy of each file it changes, and ${p.cyan('phantom setup --restore')} puts them back.`);
150
150
  }
151
151
  if (skills)
152
- lines.push(` ${p.dim('skill:')} a short note that teaches the agent the phantom commands.`);
152
+ lines.push(` ${p.dim('Skill:')} a file that teaches the agent the phantom commands.`);
153
153
  // Most people only see the 'ask' screen, so its hint is the plain command they just ran, plus --diff.
154
154
  if (!opts.diff && opts.hint !== false && r.files.some((f) => f.diff)) {
155
155
  lines.push('', mode === 'ask' ? ` To see every line first, answer n and run: ${p.cyan('phantom setup --diff')}` : ` To see every line, add ${p.cyan('--diff')}.`);
@@ -221,7 +221,7 @@ function doneSummary(agent, a, files, skipped, p) {
221
221
  return 'loads your Phantom AI key in new terminals.';
222
222
  const prov = a?.provider;
223
223
  if (prov?.manual?.length)
224
- return p.yellow('not finished: 2 minutes by hand:');
224
+ return p.yellow('not finished: do these steps by hand.');
225
225
  if (prov && !prov.on)
226
226
  return !files ? p.dim('already off: nothing to remove.') : agent === 'claude' ? 'back on Anthropic.' : 'Phantom AI settings removed.';
227
227
  if (prov?.on) {
@@ -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');
@@ -1,11 +1,24 @@
1
1
  import { type Env } from '../core/state.mts';
2
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
+ };
3
14
  /**
4
15
  * One call to the workspace API, with the limits every call shares ({@link fetchAnswer}): 30 seconds
5
16
  * unless `timeoutMs` says less, and a plain message for a web page, an empty answer or no connection.
6
17
  * @throws {@link PhantomApiError} when the API answers with an error status.
7
18
  */
8
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;
9
22
  /** The management credential `phantom login` saved for this API address, or null when it saved none. */
10
23
  export declare function savedManagement(input: CommandInput): string | null;
11
24
  /** A read from the saved workspace, such as `/spend`, with its management credential. */