@phantomcodes/cli 1.4.0 → 1.4.2

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 +13 -16
  2. package/dist/agents/command.d.mts +36 -0
  3. package/dist/agents/command.mjs +19 -7
  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 +0 -2
  8. package/dist/cli/commands.d.mts +19 -0
  9. package/dist/cli/commands.mjs +1 -11
  10. package/dist/cli/help.d.mts +26 -0
  11. package/dist/cli/help.mjs +1 -1
  12. package/dist/cli/run.d.mts +2 -0
  13. package/dist/cli/screens.d.mts +171 -0
  14. package/dist/cli/screens.mjs +0 -31
  15. package/dist/cli/start.d.mts +34 -0
  16. package/dist/cli/start.mjs +0 -1
  17. package/dist/core/brand.d.mts +12 -0
  18. package/dist/core/errors.d.mts +27 -0
  19. package/dist/core/free.d.mts +13 -0
  20. package/dist/core/helpers.d.mts +75 -0
  21. package/dist/core/helpers.mjs +28 -3
  22. package/dist/core/motion.d.mts +47 -0
  23. package/dist/core/node-trust.d.mts +12 -0
  24. package/dist/core/pick.d.mts +86 -0
  25. package/dist/core/request.d.mts +64 -0
  26. package/dist/core/request.mjs +79 -30
  27. package/dist/core/secrets.d.mts +33 -0
  28. package/dist/core/shapes.d.mts +13 -0
  29. package/dist/core/state.d.mts +3 -0
  30. package/dist/core/style.d.mts +49 -0
  31. package/dist/core/version.d.mts +2 -0
  32. package/dist/core/version.mjs +1 -1
  33. package/dist/keys/command.d.mts +16 -0
  34. package/dist/keys/saved.d.mts +88 -0
  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/phantom.mjs +0 -1
  41. package/dist/receipts/command.d.mts +7 -0
  42. package/dist/receipts/receipts.d.mts +67 -0
  43. package/dist/receipts/receipts.mjs +15 -11
  44. package/dist/setup/agents.d.mts +149 -0
  45. package/dist/setup/agents.mjs +48 -35
  46. package/dist/setup/apply.d.mts +71 -0
  47. package/dist/setup/apply.mjs +7 -2
  48. package/dist/setup/command.d.mts +12 -0
  49. package/dist/setup/editors.d.mts +101 -0
  50. package/dist/setup/editors.mjs +4 -2
  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/shared.d.mts +141 -0
  56. package/dist/setup/shared.mjs +8 -2
  57. package/dist/setup/was.d.mts +42 -0
  58. package/dist/setup/was.mjs +91 -0
  59. package/dist/spend/command.d.mts +5 -0
  60. package/dist/spend/lineup.d.mts +54 -0
  61. package/dist/spend/lineup.mjs +3 -2
  62. package/dist/spend/report.d.mts +105 -0
  63. package/dist/spend/report.mjs +0 -2
  64. package/dist/spend/routing.d.mts +72 -0
  65. package/dist/workspace/command.d.mts +46 -0
  66. package/dist/workspace/command.mjs +83 -37
  67. package/package.json +2 -2
  68. package/skills/phantom-ai/SKILL.md +1 -15
  69. package/dist/plan/command.mjs +0 -91
package/README.md CHANGED
@@ -73,7 +73,13 @@ shell startup file alone, untick "Your shell" in the checklist or pass
73
73
  `--no-shell`; setup then prints the lines to add yourself. Cap what the key can spend each
74
74
  month with `phantom setup --limit 20` (`--limit none` removes it); at a terminal,
75
75
  setup asks once when the key has no cap. The Phantom CLI keeps backups;
76
- undo the changes with `phantom setup --restore`.
76
+ undo the changes with `phantom setup --restore`. To take Phantom out of an agent
77
+ and keep the rest of its settings, run `phantom setup --provider off`: for JSON
78
+ settings files (Claude Code, Qwen Code, Gemini CLI and the others) setup records
79
+ each value it replaces, and puts it back.
80
+
81
+ Claude Code's background calls (titles, summaries and its Explore agent) run on the
82
+ model you chose with `phantom models`, so `phantom-1:zdr` covers them too.
77
83
 
78
84
  ## Connect for one run
79
85
 
@@ -121,7 +127,12 @@ phantom keys set --id <key-id> --limit 10
121
127
  ```
122
128
 
123
129
  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.
130
+ rates. `--limit`, `--budget`, `--period` and `--rate` take a number of zero or more,
131
+ or `none`; a mistyped value such as `5usd` is refused and changes nothing. Use the
132
+ full key ID from `phantom keys list` when changing or revoking a key. If a new or
133
+ rotated key cannot be saved on this computer (a locked Keychain over SSH, say),
134
+ phantom shows it once on screen and exits with an error, so copy it before you
135
+ close the terminal.
125
136
  Revoking a workspace key preserves workspace funds.
126
137
 
127
138
  ## Choose what answers
@@ -181,20 +192,6 @@ The dates are UTC days and the default is this month. `--workspace` lists every
181
192
  your workspace by name; without it you see the key you run as. The saving is an
182
193
  estimate: the same tokens at the frontier model's price today.
183
194
 
184
- A Pro ($20 a month) or Max ($100 a month) plan pays for `phantom-1` calls up to an amount
185
- of model cost in any 7 days, then your credit pays:
186
-
187
- ```bash
188
- phantom plan --table
189
- phantom plan pro
190
- phantom plan manage
191
- ```
192
-
193
- `plan` shows the key's plan and how much of the last 7 days it has paid for. `plan pro`
194
- and `plan max` print a Stripe Checkout link that puts the plan on this key and open it.
195
- `plan manage` opens Stripe's billing page, where the card changes, the plan switches and
196
- it cancels. A named model, not `phantom-1`, still spends credit.
197
-
198
195
  ## Commands
199
196
 
200
197
  | Task | Commands |
@@ -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: {
@@ -71,7 +83,7 @@ export const AGENTS = {
71
83
  const file = path.join(tmp, 'phantom-provider.ts');
72
84
  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 };
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
  };
@@ -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
@@ -35,7 +35,6 @@ export function mainMenu(s) {
35
35
  { label: 'Models', hint: 'phantom-1, free or zdr: what each can do, and pick one', value: { run: ['models'] } },
36
36
  { label: 'Choose models', hint: 'the model phantom-1 runs in each tier', value: { run: ['lineup', 'set'] } },
37
37
  { label: 'Keys', hint: 'list, new, limits, revoke', value: { open: 'keys' } },
38
- { label: 'Plan', hint: 'Pro or Max, instead of credit', value: { run: ['plan'] } },
39
38
  { label: 'Workspace', hint: 'balance, keys and latest calls together', value: { run: ['workspace'] } },
40
39
  { label: 'More', hint: 'setup, undo, routing, sign out, every command', value: { open: 'more' } },
41
40
  quit,
@@ -78,7 +77,6 @@ export function nextSteps(ran) {
78
77
  fund: [['Balance', ['balance']]],
79
78
  workspace: [['See my keys', ['keys']], ['Spend by key', ['spend', '--workspace']]],
80
79
  keys: [['New key', ['keys', 'create']], ['Set a spending limit', ['keys', 'set']], ['Revoke a key', ['keys', 'revoke']]],
81
- plan: [['Start Pro', ['plan', 'pro']], ['Start Max', ['plan', 'max']], ['Manage billing', ['plan', 'manage']]],
82
80
  models: [['Put it in my agents', ['setup']], ['Choose the model in each tier', ['lineup', 'set']]],
83
81
  route: [['See what a request would get', ['route', 'test']], ['Choose models', ['lineup', 'set']]],
84
82
  'setup --restore': [['Sign out, and forget saved keys', ['logout', '--all']]],
@@ -0,0 +1,19 @@
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
+ /** The definitions used by CLI dispatch, help, and generated documentation. */
19
+ export declare const COMMANDS: readonly CommandDefinition[];
@@ -3,7 +3,6 @@ import { agentCommand } from "../agents/command.mjs";
3
3
  import { balanceCommand, keyCommand, loginCommand, logoutCommand } from "../keys/command.mjs";
4
4
  import { lineupCommand, routeCommand } from "../spend/command.mjs";
5
5
  import { spendCommand } from "../spend/report.mjs";
6
- import { planCommand } from "../plan/command.mjs";
7
6
  import { verifyCommand } from "../receipts/command.mjs";
8
7
  import { setupCommand } from "../setup/command.mjs";
9
8
  import { SETUP_MODEL } from "../setup/shared.mjs";
@@ -58,7 +57,7 @@ export const COMMANDS = [
58
57
  name: 'keys', handler: workspaceCommand, keyless: true,
59
58
  group: 'Keys', summary: "your workspace's keys: list, create, set limits, revoke",
60
59
  help: ` keys [list] remote workspace key metadata, never secrets
61
- keys create [--save <name>] [--limit <USD>]
60
+ keys create [--save <name>] [--limit <USD|none>]
62
61
  keys set --id <id> [--limit <USD|none>] [--budget <USD|none>]
63
62
  [--period <days|none>] [--rate <USD|none>] [--name <name>]
64
63
  [--policy-file <path> | --clear-policy]
@@ -97,15 +96,6 @@ export const COMMANDS = [
97
96
  help: ` spend [--from <date>] [--to <date>] what this key spent, by model and day, and what phantom-1
98
97
  saved; dates are UTC days as YYYY-MM-DD, default this month
99
98
  spend --workspace every key in the workspace by name (needs phantom login)`,
100
- },
101
- {
102
- name: 'plan', handler: planCommand,
103
- group: 'Money', summary: 'your Pro or Max plan: status, buy, manage',
104
- help: ` plan [status] this workspace's Pro or Max plan, how much of the week is used,
105
- and what each plan costs
106
- plan pro | max [--no-browser] open Stripe Checkout to put the plan on this workspace (every
107
- key in it); at a terminal, it says the price and asks first
108
- plan manage [--no-browser] the same for Stripe's billing page: card, switch plan, cancel`,
109
99
  },
110
100
  {
111
101
  name: 'key', advanced: true, handler: keyCommand, keyless: true,
@@ -0,0 +1,26 @@
1
+ /** One entry in {@link ENV_VARS}. */
2
+ export type EnvVar = {
3
+ /** The variable's name. */
4
+ name: string;
5
+ /** What it does, in a few words, for HELP and the reference. */
6
+ about: string;
7
+ /** Holds a secret: keep it out of files, logs and the model's context. */
8
+ secret?: boolean;
9
+ /** Read from the environment only, on purpose: no flag or tool argument can set it. */
10
+ envOnly?: boolean;
11
+ /** Limits what an agent can spend. */
12
+ cap?: boolean;
13
+ };
14
+ /**
15
+ * Every environment variable phantom reads. The Environment section of HELP is
16
+ * built from this list.
17
+ */
18
+ export declare const ENV_VARS: readonly EnvVar[];
19
+ /** Full command reference, printed by `phantom --help --all`. */
20
+ export declare const HELP: string;
21
+ /**
22
+ * The help printed by default: each command in one line, under a heading for
23
+ * what it's for, so it fits on one screen. The three agents share one row.
24
+ * `phantom <command> --help` and `--help --all` keep the full usage.
25
+ */
26
+ export declare const PRIMARY_HELP: string;
package/dist/cli/help.mjs CHANGED
@@ -33,7 +33,7 @@ Flags:
33
33
  ${envHelp()}
34
34
  `.trim();
35
35
  /** The order commands take inside their group in the short help: the one most people need first. Others follow in list order. */
36
- const FIRST = ['setup', 'login', 'claude', 'codex', 'pi', 'balance', 'fund', 'spend', 'plan'];
36
+ const FIRST = ['setup', 'login', 'claude', 'codex', 'pi', 'balance', 'fund', 'spend'];
37
37
  const rank = (name) => (FIRST.includes(name) ? FIRST.indexOf(name) : FIRST.length);
38
38
  /** One row of the short help: a command name in its column, then what it does. */
39
39
  const helpRow = (name, summary) => ` ${name.padEnd(20)}${summary}`;
@@ -0,0 +1,2 @@
1
+ import { type CommandInput } from '../core/helpers.mts';
2
+ export declare function run(argv?: string[], env?: Record<string, string | undefined>, io?: CommandInput['io'], node?: string): Promise<number>;
@@ -0,0 +1,171 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import { type Paint } from '../core/style.mts';
3
+ import type { BalanceResult } from '../core/shapes.mts';
4
+ import type { SpendResult } from '../spend/report.mts';
5
+ import { type ModelsView } from '../models/list.mts';
6
+ /** How a screen is drawn: its environment (for colors), whether to color it, and the window's width. */
7
+ export type ScreenStyle = {
8
+ env?: Env;
9
+ color?: boolean;
10
+ columns?: number;
11
+ };
12
+ /** Dollars as people read them: two decimals, or four under a cent so small spend doesn't read as $0.00. */
13
+ export declare function usd(n: number): string;
14
+ /** True while the app runs, so a screen can point at a menu item instead of a command. */
15
+ export declare const inApp: () => boolean;
16
+ /** Hides or shows every screen's "→ type this next" line, and returns what it was, to put back after. The app hides them while it runs. */
17
+ export declare function hideHints(hidden: boolean): boolean;
18
+ /** A thin bar `width` cells long at `share` of full (0 to 1), in `fill`, on a dimmed track: the site's cost bars. */
19
+ export declare function bar(p: Paint, share: number, width: number, fill: (s: string) => string): string;
20
+ /** `phantom balance`: the credit in bold, then what it spent and when the key stops working. */
21
+ export declare function balanceScreen(b: BalanceResult, style?: ScreenStyle): string;
22
+ /**
23
+ * `phantom spend`: the total, what phantom-1 saved, the site's two bars (what
24
+ * the calls cost against what the same calls cost on the frontier model), then
25
+ * each model and each key with a bar for its share.
26
+ */
27
+ export declare function spendScreen(s: SpendResult, style?: ScreenStyle): string;
28
+ /** A key in the workspace view, as the API returns it. */
29
+ type WorkspaceKey = {
30
+ id?: string;
31
+ name?: string;
32
+ prefix?: string;
33
+ is_active?: boolean;
34
+ spent_usd?: number;
35
+ limit_usd?: number | null;
36
+ budget_usd?: number | null;
37
+ period_days?: number | null;
38
+ };
39
+ /** The workspace view from `GET /workspaces/{id}`, the parts these screens read. */
40
+ export type WorkspaceView = {
41
+ name?: string;
42
+ balance_usd: number;
43
+ held_usd?: number;
44
+ account_linked?: boolean;
45
+ keys: WorkspaceKey[];
46
+ charges?: Array<{
47
+ model?: string;
48
+ cost_usd?: number;
49
+ why?: string | null;
50
+ }>;
51
+ };
52
+ /** `phantom workspace`: the shared balance, each key, and the last few charges. */
53
+ export declare function workspaceScreen(view: WorkspaceView, style?: ScreenStyle): string;
54
+ /** `phantom keys`: the workspace's keys alone. */
55
+ export declare function keysScreen(keys: WorkspaceKey[], style?: ScreenStyle): string;
56
+ /** After `phantom login`: signed in, where the key is kept, and the next step. */
57
+ export declare function signedInScreen(saved: {
58
+ saved_as: string;
59
+ storage: string;
60
+ }, style?: ScreenStyle): string;
61
+ /** `phantom login` when this computer already has a key: say so, then how to switch or add one. */
62
+ export declare function alreadySignedInScreen(keyIdShown: string | null, style?: ScreenStyle): string;
63
+ /** The parts of a route policy these screens read (the full type is in spend/routing.mts). */
64
+ type RouteView = {
65
+ route_policy: {
66
+ models: string[];
67
+ applies_to?: 'auto' | 'all';
68
+ on_empty?: 'stop' | 'cheapest';
69
+ fallback_on_error?: boolean;
70
+ stick_minutes?: number;
71
+ stick_by_prompt?: boolean;
72
+ rules?: Array<{
73
+ if: Record<string, unknown>;
74
+ use: string;
75
+ }>;
76
+ sort?: 'cost' | 'ttft' | 'tps';
77
+ zdr?: boolean;
78
+ no_training?: boolean;
79
+ } | null;
80
+ };
81
+ /** `phantom route`: which models "auto" picks from, what it does at the edges, and its rules, in sentences. */
82
+ export declare function routeScreen(r: RouteView, style?: ScreenStyle): string;
83
+ /** `phantom route test`: the model a request would run on right now, and why. */
84
+ export declare function routeTestScreen(t: {
85
+ model: string | null;
86
+ reason: string | null;
87
+ routed: boolean;
88
+ fallbacks?: string[];
89
+ }, style?: ScreenStyle): string;
90
+ /** The parts of a lineup these screens read (the full type is in spend/lineup.mts). */
91
+ export type LineupView = {
92
+ lineup: (Record<string, string | undefined> & {
93
+ fallbacks?: Record<string, string | undefined>;
94
+ }) | null;
95
+ tiers: Record<'economy' | 'standard' | 'frontier', {
96
+ model: string;
97
+ name: string;
98
+ }>;
99
+ choices?: Record<'economy' | 'standard' | 'frontier', Array<{
100
+ model: string;
101
+ name: string;
102
+ input_per_m: number | null;
103
+ output_per_m: number | null;
104
+ context: number | null;
105
+ default: boolean;
106
+ }>>;
107
+ };
108
+ /** What each tier is for, in a few words. */
109
+ export declare const TIER_ABOUT: {
110
+ readonly economy: "short, easy requests";
111
+ readonly standard: "everyday coding";
112
+ readonly frontier: "the hardest work";
113
+ };
114
+ /** `phantom lineup`: the model phantom-1 runs in each tier, whether it's the default or your pick, and its fallback. */
115
+ export declare function lineupScreen(l: LineupView, style?: ScreenStyle): string;
116
+ /** A model's price per million tokens, in and out, for a picker's hint. */
117
+ export declare function priceHint(c: {
118
+ input_per_m: number | null;
119
+ output_per_m: number | null;
120
+ context: number | null;
121
+ default: boolean;
122
+ }): string;
123
+ /** A link to open in the browser (Stripe Checkout, billing, a wallet), with what it's for and the next step. */
124
+ export declare function linkScreen(words: string, url: string, after: [string, string] | null, style?: ScreenStyle & {
125
+ opened?: boolean;
126
+ }): string;
127
+ /** `phantom fund`: the card checkout link, or the wallet payment link with its id to check on. */
128
+ export declare function fundScreen(f: {
129
+ payment_id?: string;
130
+ checkout_url?: string;
131
+ amount_cents?: number;
132
+ solana_pay_url?: string;
133
+ payment_url?: string;
134
+ coin?: string;
135
+ amount?: number | string;
136
+ expires_at?: string;
137
+ }, style?: ScreenStyle & {
138
+ opened?: boolean;
139
+ }): string;
140
+ /** `phantom workspace payment`: whether a payment has come in. */
141
+ export declare function paymentScreen(pay: {
142
+ payment_id: string;
143
+ status: string;
144
+ credit_usd?: number;
145
+ }, style?: ScreenStyle): string;
146
+ /** What a key change did: created, rotated, revoked or updated, and what to do next. */
147
+ export declare function keyChangeScreen(change: 'created' | 'rotated' | 'revoked' | 'updated', name: string | null, style?: ScreenStyle & {
148
+ storage?: string;
149
+ limit?: number | null;
150
+ }): string;
151
+ /** `phantom logout`: signed out on this computer, or nothing to sign out of. */
152
+ export declare function logoutScreen(removed: boolean, style?: ScreenStyle & {
153
+ kept?: string[];
154
+ removedNamed?: string[];
155
+ }): string;
156
+ /** `phantom keys saved`: the keys saved on this computer, by name. */
157
+ export declare function savedKeysScreen(keys: Array<{
158
+ name: string;
159
+ id: string;
160
+ active?: boolean;
161
+ credit_balance_usd?: number;
162
+ }>, style?: ScreenStyle): string;
163
+ /** `phantom keys save <name>`: the key is saved under its name, and how to run an agent on it. */
164
+ export declare function keySavedScreen(name: string, style?: ScreenStyle): string;
165
+ /**
166
+ * `phantom models`: a table of what each of Phantom's own models can do, a
167
+ * column per model, a ✓ per job. Under it, the model behind each job, so you
168
+ * can see what runs before you pick.
169
+ */
170
+ export declare function modelsScreen(v: ModelsView, style?: ScreenStyle): string;
171
+ export {};
@@ -82,8 +82,6 @@ export function spendScreen(s, style = {}) {
82
82
  const range = `${day(s.from)} to ${day(s.to)}, UTC`;
83
83
  const lines = ['', ...caption(p, w, s.scope === 'workspace' ? 'WORKSPACE SPEND' : 'SPEND', p.dim(range))];
84
84
  lines.push(` ${p.bold(usd(s.total.spent_usd))} ${p.dim(`spent on ${plural(s.total.calls, 'call')}`)}`);
85
- if (s.total.plan_usd > 0)
86
- lines.push(` ${p.dim(`${usd(s.total.plan_usd)} of it paid by your plan`)}`);
87
85
  const r = s.routing;
88
86
  if (r.available && r.calls > 0) {
89
87
  // The site's comparison: what phantom-1 cost, in lime, against the same calls on the frontier model.
@@ -255,35 +253,6 @@ export function priceHint(c) {
255
253
  const context = c.context ? ` · ${Math.round(c.context / 1000)}k context` : '';
256
254
  return `${price}${context}${c.default ? ' · default' : ''}`;
257
255
  }
258
- /** `phantom plan`: the plan, as a lime pill, and how much of this week it has used, as a bar. */
259
- export function planScreen(pl, style = {}) {
260
- const p = paint(style.env ?? {}, Boolean(style.color));
261
- const w = ruleWidth(style);
262
- const lines = ['', ...caption(p, w, 'PLAN')];
263
- if (!pl.plan) {
264
- if (!pl.available)
265
- return [...lines, ' No plan, and plans are not open right now.'].join('\n');
266
- lines.push(' No plan. A plan pays for phantom-1 each week, in place of credit, for every key in this workspace.');
267
- if (pl.prices) {
268
- lines.push('');
269
- for (const name of ['pro', 'max']) {
270
- const o = pl.prices[name];
271
- lines.push(` ${p.bold((name === 'max' ? 'Max' : 'Pro').padEnd(6))}$${o.usd_per_month} a month ${p.dim(`pays for $${o.week_limit_usd} of model cost a week; past that, credit`)}`);
272
- }
273
- }
274
- lines.push(...next(p, 'Start one:', 'phantom plan pro'), ...(hintsHidden ? [] : [` ${p.dim(' or')} ${p.cyan('phantom plan max')}`]));
275
- return lines.join('\n');
276
- }
277
- const share = pl.week_limit_usd ? pl.week_used_usd / pl.week_limit_usd : 0;
278
- lines.push(` ${p.pill(` ${pl.plan === 'max' ? 'Max' : 'Pro'} `)} ${pl.status === 'active' ? p.lime('active') : p.yellow(pl.status ?? '')}`, '');
279
- lines.push(` ${p.dim('this week'.padEnd(12))}${bar(p, share, 24, share > 0.9 ? p.yellow : p.lime)} ${usd(pl.week_used_usd)} of ${usd(pl.week_limit_usd)}`);
280
- if (pl.resets_at)
281
- lines.push(` ${p.dim('room frees'.padEnd(12))}from ${day(pl.resets_at)}`);
282
- if (pl.renews_at)
283
- lines.push(` ${p.dim('renews'.padEnd(12))}${day(pl.renews_at)}`);
284
- lines.push(...next(p, 'Card, switch or cancel:', 'phantom plan manage'));
285
- return lines.join('\n');
286
- }
287
256
  /** A link to open in the browser (Stripe Checkout, billing, a wallet), with what it's for and the next step. */
288
257
  export function linkScreen(words, url, after, style = {}) {
289
258
  const p = paint(style.env ?? {}, Boolean(style.color));
@@ -0,0 +1,34 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import type { Choice } from '../core/pick.mts';
3
+ /**
4
+ * The start screen. `signedIn` is whether a key is saved or set, so it shows
5
+ * the first step or the everyday commands.
6
+ */
7
+ export declare function startScreen(env: Env, color: boolean, signedIn: boolean): string;
8
+ /**
9
+ * How many single-letter edits turn `a` into `b`: a letter added, removed or
10
+ * changed, or two neighbours swapped ("yse" is one edit from "yes").
11
+ */
12
+ export declare function editDistance(a: string, b: string): number;
13
+ /**
14
+ * The command `typed` was most likely meant to be: the nearest name at most
15
+ * two edits away, or null. On a tie, the one that starts with the same letter.
16
+ */
17
+ export declare function closestCommand(typed: string, names: readonly string[]): string | null;
18
+ /** The title block over the start menu: the ghost and PHANTOM. */
19
+ export declare function startHeader(env: Env, color: boolean): string;
20
+ /**
21
+ * The start menu's choices, each the command it runs. Without a key, setup
22
+ * comes first. Signed in but never set up, finishing setup comes first.
23
+ * Once set up, the agents and the money do, with undo near the end.
24
+ */
25
+ export declare function startChoices(signedIn: boolean, setUp?: boolean): Choice<string[]>[];
26
+ /** "Unknown <command> subcommand" with the nearest real one, or the list when nothing is close. */
27
+ export declare function unknownSub(command: string, typed: string, subs: readonly string[]): string;
28
+ /**
29
+ * Words people type instead of a command, and the command they mean. These
30
+ * run as that command, and stay out of --help.
31
+ */
32
+ export declare const ALIASES: Record<string, string[]>;
33
+ /** The command a sentence most likely means, from the first word in it that points at one, or null. */
34
+ export declare function commandFromWords(words: string[]): string | null;
@@ -128,7 +128,6 @@ const HINTS = [
128
128
  [/^(balance|left)$/, 'balance'],
129
129
  [/^(key|keys)$/, 'keys'],
130
130
  [/^(claude|codex)$/, 'claude'],
131
- [/^(plan|subscription|subscribe)$/, 'plan'],
132
131
  [/^(login|signin|sign)$/, 'login'],
133
132
  ];
134
133
  /** The command a sentence most likely means, from the first word in it that points at one, or null. */
@@ -0,0 +1,12 @@
1
+ import type { Paint } from './style.mts';
2
+ /** The ghost in block characters: white, eyes set to the right, a wavy hem, and a thin mint edge on its right side. */
3
+ export declare const GHOST: Array<[body: string, rim: string]>;
4
+ export declare const WORDMARK: string[];
5
+ /** The one line that says what phantom does, everywhere the CLI describes itself. */
6
+ export declare const TAGLINE = "Points your coding agents at Phantom AI.";
7
+ /**
8
+ * A screen's title block: the ghost, PHANTOM beside it, and `label` in lime
9
+ * with `line` along the ghost's hem. For example `setup Points your coding
10
+ * agents at Phantom AI.` Without color, a plain one-line title instead.
11
+ */
12
+ export declare function brandHeader(p: Paint, color: boolean, label: string, line?: string): string[];