@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
package/README.md CHANGED
@@ -1,28 +1,41 @@
1
- # Your agents have expensive taste.
1
+ # Phantom CLI
2
2
 
3
- Connect your agents to Phantom AI. Route models, control spending and pay from your terminal.
3
+ `phantom` connects Claude Code, Codex, pi and other coding agents to [Phantom AI](https://phantom.codes), an OpenAI-compatible API. It signs you in, keeps your key on your computer, adds credit and caps what each key can spend.
4
4
 
5
- **Phantom CLI** (`phantom`) by [Phantom AI](https://phantom.codes) · [Docs](https://phantom.codes/docs) · [npm](https://www.npmjs.com/package/@phantomcodes/cli)
5
+ [Docs](https://phantom.codes/docs) · [npm](https://www.npmjs.com/package/@phantomcodes/cli)
6
6
 
7
- Use Phantom AI's router to send requests to cheaper models when your rules allow
8
- it, or choose a model yourself. Connect the coding agents you already use, fund
9
- their inference and control spending—all from your terminal.
7
+ ## Install and set up
10
8
 
11
- ## Install the agent skill
12
-
13
- The `phantom-ai` skill ships in the package. `phantom setup` installs it for
14
- each agent it finds:
9
+ You need Node 24 or newer and the coding agent itself.
15
10
 
16
11
  ```bash
17
12
  npm i -g @phantomcodes/cli
18
- phantom setup --agent claude
13
+ phantom setup
19
14
  ```
20
15
 
21
- The skill covers workspace setup, funding, spending controls and model routing.
16
+ With no key saved yet, `phantom setup` signs you in first, with the same browser approval as `phantom login`. Then it finds the agents on your computer, shows what it will change in each file, and asks before it writes anything. Restart your agent, or open a new terminal, to use the connection.
17
+
18
+ With no credit, phantom-1 runs on free models, up to 200 requests a day from a coding agent, and you don't need a card. Free calls leave out web search, which costs money on any model.
19
+
20
+ If you used pai, this CLI's old name, run `phantom setup` once after you install. Until then, Claude Code and the shell block that pai wrote still call `pai`, and phantom prints a reminder.
21
+
22
+ ### What setup changes
23
+
24
+ Setup writes model settings for Claude Code, Codex, opencode, Continue, Goose, Aider, GitHub Copilot CLI, Cline, Gemini CLI, Crush, Qwen Code, Kilo Code, Kimi Code, Droid, Mistral Vibe and Zed. Cursor, VS Code, JetBrains AI Assistant, Warp and Trae keep these settings on their own settings screens, so setup prints the steps for you to follow. pi gets the skill only.
25
+
26
+ It also installs the `phantom-ai` skill, a file that teaches the agent the phantom commands. To install the skill for one agent and change nothing else, run `phantom setup --agent claude` (or the agent's name).
27
+
28
+ - `phantom setup --dry-run` shows the changes and writes nothing.
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
+ - `--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.
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
+
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.
22
35
 
23
36
  ## Let your agent set it up
24
37
 
25
- Copy this into Claude Code, Codex, Cursor or another agent with terminal access:
38
+ Paste this into Claude Code, Codex, Cursor or another agent that can run terminal commands:
26
39
 
27
40
  ```text
28
41
  Help me set up phantom for AI inference through Phantom AI.
@@ -36,128 +49,81 @@ then create a named workspace key with that cap.
36
49
  Ask whether I want to connect my existing agent for future runs or use a temporary
37
50
  connection for one run. For saved setup, preview the changes with phantom setup --dry-run
38
51
  and show them to me before applying the setup I approve. Make sure any spending cap
39
- is on the key my agent will actually use. Ask before adding funds or starting paid
40
- inference. Keep keys and recovery credentials out of chat. Finish with the command
41
- to launch my agent, and explain how to undo any saved setup.
52
+ is on the key my agent uses. Ask before adding funds or starting paid inference.
53
+ Keep keys and recovery credentials out of chat. Finish with the command to launch
54
+ my agent, and explain how to undo any saved setup.
42
55
  ```
43
56
 
44
- ## Connect your existing agents
45
-
46
- Keep using your coding agent, with Phantom AI handling its inference and model
47
- routing. Connect it using your saved key:
57
+ ## Run an agent for one session
48
58
 
49
59
  ```bash
50
- npm i -g @phantomcodes/cli
51
- phantom setup
52
- ```
53
-
54
- With no key saved yet, `phantom setup` signs you in first (the same device
55
- approval as `phantom login`), then sets up your agents with the new key.
56
-
57
- Used pai, this CLI's old name? Run `phantom setup` once after you install. Until
58
- then, Claude Code and the shell block pai set up still call `pai`, and phantom
59
- prints a reminder.
60
-
61
- The Phantom CLI detects supported agents, previews the configuration changes, then asks before
62
- applying them. It connects their model calls to Phantom AI and wires up the saved
63
- key. Restart your agent, or open a new terminal, to use the connection.
64
-
65
- Saved setup covers Claude Code, Codex, opencode, Continue, Goose, Aider, GitHub
66
- Copilot CLI, Cline, Gemini CLI, Crush, Qwen Code, Kilo Code, Kimi Code, Droid,
67
- Mistral Vibe and Zed. Cursor, VS Code, JetBrains AI Assistant, Warp and Trae
68
- keep these settings on their own settings screens, so setup prints the steps;
69
- pi gets the agent skill.
70
-
71
- Preview without changing files with `phantom setup --dry-run`. To leave your
72
- shell startup file alone, untick "Your shell" in the checklist or pass
73
- `--no-shell`; setup then prints the lines to add yourself. Cap what the key can spend each
74
- month with `phantom setup --limit 20` (`--limit none` removes it); at a terminal,
75
- setup asks once when the key has no cap. The Phantom CLI keeps backups;
76
- undo the changes with `phantom setup --restore`.
77
-
78
- ## Connect for one run
79
-
80
- ```bash
81
- npm i -g @phantomcodes/cli
82
60
  phantom login
83
61
  phantom fund --amount 10 --card
84
62
  phantom workspace status
85
63
  phantom codex
86
64
  ```
87
65
 
88
- Both setup options require **Node 24+** and your coding agent installed. Connect, then
89
- launch **Codex** (`phantom codex`), **Claude Code** (`phantom claude`), **pi**
90
- (`phantom pi`), or **any other compatible agent**. Each runs phantom-1 unless you
91
- pick a model (`--model` after `--`), and phantom-1 runs on free models until you add
92
- credit. Free calls leave out web search, which costs money on any model.
66
+ `phantom claude`, `phantom codex` and `phantom pi` start the agent with a connection that lasts for that run, and leave your saved agent settings alone. When the agent exits, phantom prints what the run spent. The agent starts on phantom-1, or on the model you picked with `phantom models`; pass `--model` after `--` to choose another.
93
67
 
94
- Login opens a device approval page and saves a key privately. Funding opens
95
- checkout; check your workspace balance after payment. Agent runs use temporary
96
- configuration and print spending afterward. Your existing agent configuration
97
- stays in place.
68
+ `phantom login` opens a page in your browser. You check that it shows the same short code as your terminal, approve it, and phantom saves the key on this computer (in the macOS Keychain on a Mac). If you already have a key, `phantom login --paste` saves it.
98
69
 
99
- Already have a Phantom key? Use `phantom login --paste` to save it locally.
70
+ Put phantom's own flags before the agent's arguments, with `--` between them:
100
71
 
101
- ## Fund your workspace
72
+ ```bash
73
+ phantom codex --key coding -- exec "explain this repository"
74
+ ```
102
75
 
103
- Add credit first, then let your agents spend from the shared balance:
76
+ ## Add credit
104
77
 
105
78
  ```bash
106
79
  phantom fund --amount 10 --card
107
80
  phantom fund --amount 10 --coin usdc
108
81
  ```
109
82
 
110
- Credit is available after the payment is verified. Check balance anytime 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. The credit appears once Stripe confirms the payment. Check it with `phantom balance`.
111
84
 
112
- ## Give each agent a budget
85
+ ## Give each agent its own key and cap
113
86
 
114
- Create a key with its own cap, sharing your workspace balance:
87
+ Every key in a workspace spends from the same balance. Make one key per agent, each with its own cap:
115
88
 
116
89
  ```bash
117
90
  phantom keys create --save coding --limit 5
118
91
  phantom claude --key coding
119
92
  phantom keys list
120
- phantom keys set --id <key-id> --limit 10
93
+ phantom keys set --id coding --limit 10
121
94
  ```
122
95
 
123
- Workspace key controls include total limits, periodic budgets and spending
124
- rates. Use the full key ID from `phantom keys list` when changing or revoking a key.
125
- Revoking a workspace key preserves workspace funds.
96
+ `phantom keys set` changes three caps:
126
97
 
127
- ## Choose what answers
98
+ - `--limit`: the most the key can spend in total.
99
+ - `--budget`: the most it can spend each month, or each `--period` days.
100
+ - `--rate`: the most it can spend in one minute, in dollars.
128
101
 
129
- Let the router choose a model for `auto` requests. Your policy can prefer cheaper
130
- models and change the choice for tool use, reasoning or spending limits:
102
+ Each takes a number of zero or more, or `none`. phantom refuses a mistyped value such as `5usd` and changes nothing. `--id` takes the key's name, its id, or the first 4 or more characters of its id, as `phantom keys list` shows them.
131
103
 
132
- ```bash
133
- PHANTOM_KEY_NAME=coding phantom route set --models <model-a>,<model-b>
134
- PHANTOM_KEY_NAME=coding phantom route test --table
135
- ```
104
+ Revoking a key turns it off for good; its credit stays in the workspace.
136
105
 
137
- Prefer a specific model? Select it in your agent. Policies that apply only to
138
- `auto` leave explicit model choices alone.
106
+ If phantom can't save a new or rotated key on this computer (a locked Keychain over SSH, for example), it prints the key once and exits with an error. Copy the key before you close the terminal.
139
107
 
140
- Phantom has three models of its own. `phantom models` shows what each can do
141
- (chat, images in, embeddings, rerank, images, video, speech, transcription) and
142
- the model behind each job:
108
+ ## Choose the model
143
109
 
144
- - `phantom-1` does every job, and picks economy, standard or frontier for each chat request.
110
+ Phantom has three models of its own. `phantom models` shows what each can do (chat, images in, embeddings, rerank, images, video, speech, transcription) and the model behind each job:
111
+
112
+ - `phantom-1` does every job. For each chat request it picks a tier: economy, standard or frontier.
145
113
  - `phantom-1:free` is chat on free models at $0, with no card.
146
114
  - `phantom-1:zdr` is chat (with images) on providers that keep none of your data.
147
115
 
148
- At a terminal, `phantom models` asks which one your agents should use. To pick
149
- without the menu:
116
+ At a terminal, `phantom models` asks which one your agents should use. To pick without the menu:
150
117
 
151
118
  ```bash
152
119
  phantom models use phantom-1:zdr
153
120
  ```
154
121
 
155
- `phantom claude`, `phantom codex` and `phantom pi` start on the model you pick,
156
- and so does the next `phantom setup`. Agents set up before you picked keep their
157
- model until you run `phantom setup` again.
122
+ `phantom claude`, `phantom codex`, `phantom pi` and the next `phantom setup` start on the model you pick. Agents you set up earlier keep their model until you run `phantom setup` again.
123
+
124
+ ### Pick the model in each tier
158
125
 
159
- `phantom-1` picks a tier for each request: economy, standard or frontier. Your key's
160
- lineup picks the model in each tier, and a fallback model to try when it fails:
126
+ Your key's lineup sets the model phantom-1 runs in each tier, and a fallback model to try when that one fails:
161
127
 
162
128
  ```bash
163
129
  phantom lineup --table
@@ -165,11 +131,20 @@ phantom lineup set --frontier <model> --economy-fallback <model>
165
131
  phantom lineup reset
166
132
  ```
167
133
 
168
- `lineup` shows the choices for each tier. `default` in place of a model puts that tier
169
- back to its default.
134
+ `phantom lineup` lists the models each tier can run. Write `default` in place of a model to put that tier back to its default.
135
+
136
+ ### Set rules for `auto`
170
137
 
171
- See what a key spent, and what `phantom-1` saved against always running its frontier
172
- model:
138
+ A route policy is your key's own rules for which model answers a request for `auto`. It can prefer cheaper models, and switch models for tool use, reasoning or a budget that is running low:
139
+
140
+ ```bash
141
+ PHANTOM_KEY_NAME=coding phantom route set --models <model-a>,<model-b>
142
+ PHANTOM_KEY_NAME=coding phantom route test --table
143
+ ```
144
+
145
+ A request that names its own model skips the policy, unless you set `--applies-to all`. `phantom route set --sort fast` sends each request to the provider that starts answering soonest, and `--sort default` goes back to cheapest first.
146
+
147
+ ## See what you spent
173
148
 
174
149
  ```bash
175
150
  phantom spend --table
@@ -177,65 +152,56 @@ phantom spend --from 2026-09-01 --to 2026-09-30
177
152
  phantom spend --workspace --table
178
153
  ```
179
154
 
180
- The dates are UTC days and the default is this month. `--workspace` lists every key in
181
- your workspace by name; without it you see the key you run as. The saving is an
182
- estimate: the same tokens at the frontier model's price today.
155
+ Dates are UTC days, and the default is this month. Without `--workspace` you see the key you run as; with it, every key in your workspace by name. The "saved" figure compares what phantom-1 cost with the same tokens at the frontier model's price today, so it is an estimate.
183
156
 
184
- ## Commands
157
+ ## Commands by task
185
158
 
186
159
  | Task | Commands |
187
160
  | --- | --- |
188
- | Connect | `phantom login`, `phantom logout` |
189
- | Connect existing agents | `phantom setup`, `phantom setup --dry-run`, `phantom setup --restore` |
190
- | Providers that answer soonest | `phantom route set --sort fast` (`--sort default` for cheapest first) |
191
- | Run inference | `phantom claude`, `phantom codex`, `phantom pi` |
192
- | Fund and check spending | `phantom fund`, `phantom balance`, `phantom spend`, `phantom workspace status` |
193
- | Manage workspace keys | `phantom keys create`, `phantom keys set`, `phantom keys rotate`, `phantom keys revoke` |
194
- | Manage local copies | `phantom keys saved`, `phantom keys save`, `phantom keys rm` |
195
- | Route models | `phantom route` |
196
- | See phantom-1, phantom-1:free and phantom-1:zdr, and pick one | `phantom models`, `phantom models use <id>` |
197
- | Pick phantom-1's models | `phantom lineup`, `phantom lineup set`, `phantom lineup reset` |
198
-
199
- Put phantom flags before agent arguments; use `--` to separate them:
161
+ | Sign in and out | `phantom login`, `phantom logout` |
162
+ | Set up your agents | `phantom setup`, `phantom setup --dry-run`, `phantom setup --restore` |
163
+ | Start an agent for one run | `phantom claude`, `phantom codex`, `phantom pi` |
164
+ | Add credit and check spending | `phantom fund`, `phantom balance`, `phantom spend`, `phantom workspace status` |
165
+ | Manage the workspace's keys | `phantom keys create`, `phantom keys set`, `phantom keys rotate`, `phantom keys revoke` |
166
+ | Manage the keys saved on this computer | `phantom keys saved`, `phantom keys save`, `phantom keys rm` |
167
+ | Pick phantom-1, phantom-1:free or phantom-1:zdr | `phantom models`, `phantom models use <id>` |
168
+ | Pick the model in each tier | `phantom lineup`, `phantom lineup set`, `phantom lineup reset` |
169
+ | Set rules for `auto` | `phantom route` |
170
+ | Use the providers that answer soonest | `phantom route set --sort fast` (`--sort default` for cheapest first) |
200
171
 
201
- ```bash
202
- phantom codex --key coding -- exec "explain this repository"
203
- ```
172
+ ## Output and exit codes
173
+
174
+ At a terminal, commands draw a screen, and choices are pickers (arrow keys, Enter, Esc to go back). When scripts and agents run them through a pipe, they print JSON on stdout and errors on stderr. `--json` prints JSON at a terminal, and `--table` draws the screen in a pipe. phantom refuses a flag it doesn't know.
175
+
176
+ `phantom claude`, `phantom codex` and `phantom pi` run in your terminal and print a spending summary on stderr when the agent exits.
204
177
 
205
- In a terminal, commands draw a screen for people, and choices are pickers
206
- (arrow keys, Enter, Esc to go back). Piped, as scripts and agents run them,
207
- they print JSON on stdout and errors on stderr; `--json` forces JSON in a
208
- terminal, and `--table` the screen in a pipe. Unknown flags are refused.
209
- Agent commands inherit the terminal and print a spending summary on stderr.
210
- Exit codes: 0 success (and Esc), 1 error, 2 rejected key, 130 Ctrl+C;
211
- `phantom setup` returns 1 when it could only install the skills (no key yet,
212
- `"complete": false`). Agent runs return the agent's exit code.
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.
213
179
 
214
180
  <details>
215
- <summary><strong>Advanced tools, integrations and legacy commands</strong></summary>
181
+ <summary><strong>Advanced and older commands</strong></summary>
216
182
 
217
- `phantom --help` shows the main workflows. `phantom --help --all` covers every command.
183
+ `phantom --help` shows the main commands. `phantom --help --all` lists every command and flag.
218
184
 
219
- The older `phantom key` commands still work.
220
- `phantom keys list` reads the workspace; `phantom keys saved` lists local copies.
221
- `phantom keys show` prints a secret for shell integration; keep it out of chat and logs.
185
+ The older `phantom key` commands still work. `phantom keys list` reads the workspace, and `phantom keys saved` lists the keys saved on this computer. `phantom keys show` prints a saved key for shell use, as in `PHANTOM_API_KEY=$(phantom keys show)`; keep it out of chat and logs.
222
186
 
223
187
  </details>
224
188
 
225
189
  <details>
226
190
  <summary><strong>Development and contributing</strong></summary>
227
191
 
192
+ The CLI lives in `cli/` in the Phantom repo, which uses pnpm. Install once at the repo root, then run the checks from `cli/`:
193
+
228
194
  ```bash
229
- npm ci
230
- npm run typecheck
231
- npm run build
232
- npm run coverage
195
+ pnpm install
196
+ cd cli
197
+ pnpm typecheck
198
+ pnpm test
199
+ pnpm build
200
+ pnpm coverage
233
201
  ```
234
202
 
235
203
  Report a security problem privately to support@phantom.codes, not in a public issue.
236
204
 
237
205
  </details>
238
206
 
239
- ---
240
-
241
207
  phantom is proprietary, under the [Phantom Proprietary License](LICENSE). It lets you install and run phantom to use Phantom AI, the hosted API it calls.
@@ -0,0 +1,36 @@
1
+ import type { CommandInput } from '../core/helpers.mts';
2
+ import type { Env } from '../core/state.mts';
3
+ /**
4
+ * `phantom claude`, `phantom codex` and `phantom pi` run a coding agent against Phantom
5
+ * AI through a local proxy ({@link startProxy}). The agent gets the proxy's
6
+ * address and the run's secret token as its key, in PHANTOM_AGENT_TOKEN; the
7
+ * proxy checks the token, drops it, adds the real key, and phantom prints what
8
+ * the run paid when the agent exits. The token never goes on a command line,
9
+ * where other programs could read it, or to Phantom AI.
10
+ */
11
+ /** How phantom starts one agent against the proxy. */
12
+ export type AgentSpec = {
13
+ /** The program phantom runs. */
14
+ bin: string;
15
+ /** Phantom AI's path for this agent: `/claude-code`, `/codex` or `/coding-agent`. */
16
+ prefix: string;
17
+ /** The arguments and environment that point the agent at `proxy`, with `token` as its key. `tmp` is a folder phantom deletes after the run. */
18
+ launch(proxy: string, args: string[], env: Env, tmp: string, token: string): {
19
+ /** Everything the agent is started with: phantom's settings, then the user's arguments. */
20
+ args: string[];
21
+ /** The agent's environment. */
22
+ env: Env;
23
+ };
24
+ };
25
+ /** The agents phantom can run, by command name. */
26
+ export declare const AGENTS: Record<'claude' | 'codex' | 'pi', AgentSpec>;
27
+ /**
28
+ * `phantom claude`, `phantom codex` and `phantom pi`: runs the agent through the proxy,
29
+ * passing every other argument through, and returns its exit code. The Phantom CLI's own
30
+ * flags come first and stop at the first other argument or at `--`; they are
31
+ * read here, not with `flags`, because everything after them belongs to the
32
+ * agent. Run by `run()`.
33
+ */
34
+ export declare function agentCommand(input: CommandInput): Promise<number>;
35
+ /** The message when an agent's program isn't installed, in plain words, with where to get it. */
36
+ export declare function notInstalled(bin: string): string;
@@ -7,14 +7,22 @@ import { DEFAULT_BASE_URL, httpsOnly, request } from "../core/request.mjs";
7
7
  import { keyId, readNamedKey, resolveApiKey } from "../keys/saved.mjs";
8
8
  import { workspaceLogin } from "../workspace/command.mjs";
9
9
  import { startModel } from "../models/choice.mjs";
10
- /** The model as Claude Code names it: its picker keeps only ids that say "claude", so Phantom lists them as `claude-code/<id>`. */
11
- const claudeName = (model) => `claude-code/${model}`;
10
+ import { claudeModelName } from "../setup/shared.mjs";
12
11
  /** The key's spend and balance, or null when the answer has no numbers, such as a sign-in page that came back with status 200. */
13
12
  async function keyStatus(apiKey, baseUrl) {
14
13
  const s = await request('GET', '/key/balance', apiKey, undefined, baseUrl);
15
14
  return Number.isFinite(s.credit_spent_usd) && Number.isFinite(s.credit_balance_usd) ? s : null;
16
15
  }
17
16
  import { proxyToken, startProxy } from "./proxy.mjs";
17
+ /**
18
+ * The environment an agent starts with: the user's own, without the variables that name or hold a Phantom
19
+ * key. The agent talks to the proxy with the run's token and never holds the key, and a stale
20
+ * PHANTOM_AGENT_TOKEN from an outer run must not reach it either.
21
+ */
22
+ function withoutPhantomKeys(env) {
23
+ const { PHANTOM_API_KEY: _key, PHANTOM_KEY_NAME: _name, PHANTOM_AGENT_TOKEN: _token, ...rest } = env;
24
+ return rest;
25
+ }
18
26
  const hasModel = (args) => args.some((a) => a === '-m' || a === '--model' || a.startsWith('--model=') || /^model=/.test(a));
19
27
  /** The agents phantom can run, by command name. */
20
28
  export const AGENTS = {
@@ -29,9 +37,13 @@ export const AGENTS = {
29
37
  const helper = `${JSON.stringify(process.execPath)} -p "process.env.PHANTOM_AGENT_TOKEN || ''"`;
30
38
  // The model picked with `phantom models` (phantom-1 until then), unless the user names one. It goes in the
31
39
  // environment, which Claude Code ranks below --model and below a model in its settings file.
32
- const model = hasModel(args) || env.ANTHROPIC_MODEL ? {} : { ANTHROPIC_MODEL: claudeName(startModel(env)) };
33
- const vars = { ANTHROPIC_BASE_URL: proxy, CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: '1', ENABLE_TOOL_SEARCH: 'true' };
34
- const { ANTHROPIC_AUTH_TOKEN: _auth, ...rest } = env;
40
+ const model = hasModel(args) || env.ANTHROPIC_MODEL ? {} : { ANTHROPIC_MODEL: claudeModelName(startModel(env)) };
41
+ // Claude Code's background calls (titles, summaries, the Explore agent that reads the code) go to its haiku
42
+ // model. They follow the chosen model, and sit in --settings, which outranks the haiku model an earlier
43
+ // `phantom setup` wrote, so a later `phantom models use phantom-1:zdr` covers them. A haiku model the user set in the shell stays theirs.
44
+ const background = env.ANTHROPIC_DEFAULT_HAIKU_MODEL ? {} : { ANTHROPIC_DEFAULT_HAIKU_MODEL: claudeModelName(startModel(env)) };
45
+ const vars = { ANTHROPIC_BASE_URL: proxy, CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: '1', ENABLE_TOOL_SEARCH: 'true', ...background };
46
+ const { ANTHROPIC_AUTH_TOKEN: _auth, ...rest } = withoutPhantomKeys(env);
35
47
  return {
36
48
  args: ['--settings', JSON.stringify({ apiKeyHelper: helper, env: vars }), ...args],
37
49
  env: { ...rest, ...model, ANTHROPIC_BASE_URL: proxy, ANTHROPIC_API_KEY: token, PHANTOM_AGENT_TOKEN: token },
@@ -58,7 +70,7 @@ export const AGENTS = {
58
70
  'features.api_key_model_discovery=true',
59
71
  ...(hasModel(args) ? [] : [`model=${JSON.stringify(startModel(env))}`]),
60
72
  ];
61
- return { args: [...config.flatMap((c) => ['-c', c]), ...args], env: { ...env, OPENAI_BASE_URL: base, PHANTOM_AGENT_TOKEN: token } };
73
+ return { args: [...config.flatMap((c) => ['-c', c]), ...args], env: { ...withoutPhantomKeys(env), OPENAI_BASE_URL: base, PHANTOM_AGENT_TOKEN: token } };
62
74
  },
63
75
  },
64
76
  pi: {
@@ -69,9 +81,9 @@ export const AGENTS = {
69
81
  // for this run leaves the user's own files alone. Its key is read from
70
82
  // PHANTOM_AGENT_TOKEN when pi calls, so the file holds no secret.
71
83
  const file = path.join(tmp, 'phantom-provider.ts');
72
- const model = { id: startModel(env), name: 'Phantom AI router (phantom)', reasoning: true, input: ['text', 'image'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 1_000_000, maxTokens: 64_000 };
84
+ const model = { id: startModel(env), name: 'Phantom AI (phantom)', reasoning: true, input: ['text', 'image'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 1_000_000, maxTokens: 64_000 };
73
85
  writeFileSync(file, `export default function (pi) {\n pi.registerProvider('phantom', ${JSON.stringify({ baseUrl: `${proxy}/v1`, api: 'openai-completions', apiKey: '$PHANTOM_AGENT_TOKEN', models: [model] })});\n}\n`, { mode: 0o600 });
74
- return { args: ['-e', file, ...(hasModel(args) ? [] : ['--provider', 'phantom', '--model', startModel(env)]), ...args], env: { ...env, PHANTOM_AGENT_TOKEN: token } };
86
+ return { args: ['-e', file, ...(hasModel(args) ? [] : ['--provider', 'phantom', '--model', startModel(env)]), ...args], env: { ...withoutPhantomKeys(env), PHANTOM_AGENT_TOKEN: token } };
75
87
  },
76
88
  },
77
89
  };
@@ -122,7 +134,7 @@ export async function agentCommand(input) {
122
134
  if (a === '--key')
123
135
  keyName = value(a);
124
136
  else if (a === '--mpp')
125
- die('--mpp has been removed. Phantom stays prepaid only. Run phantom login to sign in, or use a saved key.');
137
+ die('--mpp has been removed: an agent run spends your key\'s credit. Run phantom login to sign in, or pick a saved key with --key <name>.');
126
138
  else if (a === '--no-browser')
127
139
  noBrowser = true;
128
140
  else
@@ -170,5 +182,5 @@ const INSTALL = {
170
182
  /** The message when an agent's program isn't installed, in plain words, with where to get it. */
171
183
  export function notInstalled(bin) {
172
184
  const how = INSTALL[bin];
173
- return `I can't find the ${bin} program on this computer, so it isn't installed yet (or isn't on your PATH).${how ? ` Install ${how}, then run this again.` : ' Install it, then run this again.'}`;
185
+ return `phantom can't find ${bin} on this computer: it isn't installed, or isn't on your PATH.${how ? ` Install ${how}, then run this again.` : ' Install it, then run this again.'}`;
174
186
  }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The local proxy `phantom claude`, `phantom codex` and `phantom pi` point the agent at.
3
+ * It listens on 127.0.0.1 only, forwards each request to Phantom AI, and
4
+ * streams the answer back as it arrives, server-sent events included. The
5
+ * agent never holds a key: the proxy drops whatever auth the agent sends and
6
+ * adds its own.
7
+ *
8
+ * Because the proxy spends the user's key or wallet, it serves only the agent
9
+ * it started: each request must carry the run's token ({@link proxyToken}),
10
+ * must name the proxy in its Host header (so a page that rebinds a DNS name
11
+ * to 127.0.0.1 is refused), and must carry no Origin header (so no browser
12
+ * page can call it).
13
+ */
14
+ /** A fresh secret for one run, which the agent sends as its key. */
15
+ export declare function proxyToken(): string;
16
+ /** How the proxy authenticates requests. */
17
+ export type ProxyAuth = {
18
+ /** Send a saved API key with every request. */
19
+ kind: 'key';
20
+ /** The key. It goes upstream only, never to the agent. */
21
+ apiKey: string;
22
+ };
23
+ /** A running proxy. */
24
+ export type AgentProxy = {
25
+ /** `http://127.0.0.1:<port>`. */
26
+ url: string;
27
+ /** Requests refused because of their Host, Origin or token. */
28
+ rejected: number;
29
+ /** Requests forwarded so far. */
30
+ forwarded: number;
31
+ /** Stops listening and ends open connections. */
32
+ close(): Promise<void>;
33
+ };
34
+ /**
35
+ * Starts the proxy on a free port of 127.0.0.1.
36
+ * @param opts.upstream Where requests go: Phantom AI's address for this agent, such as `https://phantom.codes/claude-code`. The request's path is added to it.
37
+ * @param opts.auth A saved key, or a paying fetch.
38
+ * @param opts.token The run's secret ({@link proxyToken}). A request without it, as `Authorization: Bearer` or `x-api-key`, gets 401.
39
+ */
40
+ export declare function startProxy(opts: {
41
+ upstream: string;
42
+ auth: ProxyAuth;
43
+ token: string;
44
+ }): Promise<AgentProxy>;
@@ -1,5 +1,6 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { randomBytes, timingSafeEqual } from 'node:crypto';
3
+ import { explainNetworkError } from "../core/request.mjs";
3
4
  /**
4
5
  * The local proxy `phantom claude`, `phantom codex` and `phantom pi` point the agent at.
5
6
  * It listens on 127.0.0.1 only, forwards each request to Phantom AI, and
@@ -112,9 +113,10 @@ export async function startProxy(opts) {
112
113
  catch (err) {
113
114
  if (aborter.signal.aborted)
114
115
  return;
115
- const message = err instanceof Error ? err.message : String(err);
116
+ const offline = explainNetworkError(err, new URL(upstream).host);
117
+ const message = offline ?? `phantom could not get this from Phantom AI: ${err instanceof Error ? err.message : String(err)}`;
116
118
  if (!res.headersSent)
117
- sendJson(res, 502, { error: { type: 'proxy_error', message: `phantom could not get this from Phantom AI: ${message}` } });
119
+ sendJson(res, 502, { error: { type: 'proxy_error', message } });
118
120
  else
119
121
  res.destroy();
120
122
  }
@@ -0,0 +1,25 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import { type Choice, type PickIo } from '../core/pick.mts';
3
+ /** What a menu row does: run a command, or open another menu. Quit is an empty command. */
4
+ type Action = {
5
+ run: string[];
6
+ } | {
7
+ open: 'keys' | 'more' | 'commands';
8
+ };
9
+ /** What the app knows about this computer, without asking the network: signed in, set up, which agents are installed. */
10
+ export type AppState = {
11
+ signedIn: boolean;
12
+ setUp: boolean;
13
+ installed: (bin: string) => boolean;
14
+ };
15
+ /** The main menu for the state this computer is in. */
16
+ export declare function mainMenu(s: AppState): Choice<Action>[];
17
+ /** After a command's result: the next steps that fit it, as choices, so nobody types the "→" line. */
18
+ export declare function nextSteps(ran: string[]): Choice<string[]>[];
19
+ /**
20
+ * Runs the app until Quit, Esc on the main menu, or Ctrl+C. `runCommand` runs
21
+ * one command the way `phantom <args>` would and returns its exit code; the app
22
+ * passes it `fromMenu`, so a command's first Esc comes back here.
23
+ */
24
+ export declare function runApp(env: Env, pick: PickIo, write: (s: string) => void, runCommand: (argv: string[]) => Promise<number>, installed?: (bin: string) => boolean): Promise<number>;
25
+ export {};
package/dist/cli/app.mjs CHANGED
@@ -46,7 +46,7 @@ function subMenu(which, s) {
46
46
  return [
47
47
  { label: 'See my keys', value: { run: ['keys'] } },
48
48
  { label: 'New key', hint: 'for a teammate, CI or another computer', value: { run: ['keys', 'create'] } },
49
- { label: 'Set a spending limit', value: { run: ['keys', 'set'] } },
49
+ { label: 'Cap what a key can spend', value: { run: ['keys', 'set'] } },
50
50
  { label: 'Revoke a key', hint: 'it stops working at once; its credit stays', value: { run: ['keys', 'revoke'] } },
51
51
  { label: 'Rotate a key', hint: 'a new key in its place; the old one stops working', value: { run: ['keys', 'rotate'] } },
52
52
  ];
@@ -76,7 +76,7 @@ export function nextSteps(ran) {
76
76
  'spend --workspace': [['Keys', ['keys']]],
77
77
  fund: [['Balance', ['balance']]],
78
78
  workspace: [['See my keys', ['keys']], ['Spend by key', ['spend', '--workspace']]],
79
- keys: [['New key', ['keys', 'create']], ['Set a spending limit', ['keys', 'set']], ['Revoke a key', ['keys', 'revoke']]],
79
+ keys: [['New key', ['keys', 'create']], ['Cap what a key can spend', ['keys', 'set']], ['Revoke a key', ['keys', 'revoke']]],
80
80
  models: [['Put it in my agents', ['setup']], ['Choose the model in each tier', ['lineup', 'set']]],
81
81
  route: [['See what a request would get', ['route', 'test']], ['Choose models', ['lineup', 'set']]],
82
82
  'setup --restore': [['Sign out, and forget saved keys', ['logout', '--all']]],
@@ -0,0 +1,23 @@
1
+ import type { CommandInput } from '../core/helpers.mts';
2
+ /** A command's handler, help text, and conditions for running without a key. */
3
+ export type CommandDefinition = {
4
+ name: string;
5
+ handler: (input: CommandInput) => Promise<number>;
6
+ help: string;
7
+ keyless?: true | readonly string[];
8
+ /** Shown in full help rather than the default workflow. */
9
+ advanced?: true;
10
+ /** The heading it sits under in the short `--help`. */
11
+ group: HelpGroup;
12
+ /** What it does, in a few words, for the short `--help`. */
13
+ summary: string;
14
+ };
15
+ /** The short `--help`'s headings, in the order they print. */
16
+ export declare const HELP_GROUPS: readonly ["Start", "Run", "Money", "Keys", "Routing", "More"];
17
+ export type HelpGroup = (typeof HELP_GROUPS)[number];
18
+ /**
19
+ * The definitions used by CLI dispatch, help, and generated documentation.
20
+ * `run()` reads each command's flags from its `help`, so every flag a command
21
+ * takes must appear there as `--name`.
22
+ */
23
+ export declare const COMMANDS: readonly CommandDefinition[];