@phantomcodes/cli 1.6.3 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +138 -117
  2. package/bin/phantom.mjs +37 -2
  3. package/dist/agents/command.d.mts +8 -27
  4. package/dist/agents/command.mjs +323 -59
  5. package/dist/agents/login.d.mts +3 -0
  6. package/dist/agents/login.mjs +97 -0
  7. package/dist/agents/opencode-check.d.mts +15 -0
  8. package/dist/agents/opencode-check.mjs +193 -0
  9. package/dist/agents/phantom-key.d.mts +7 -0
  10. package/dist/agents/phantom-key.mjs +40 -0
  11. package/dist/agents/proxy.d.mts +26 -28
  12. package/dist/agents/proxy.mjs +225 -33
  13. package/dist/chatgpt/command.d.mts +2 -0
  14. package/dist/chatgpt/command.mjs +119 -0
  15. package/dist/chatgpt/session.d.mts +87 -0
  16. package/dist/chatgpt/session.mjs +253 -0
  17. package/dist/cli/accounts.d.mts +21 -0
  18. package/dist/cli/accounts.mjs +96 -0
  19. package/dist/cli/app.d.mts +4 -24
  20. package/dist/cli/app.mjs +224 -139
  21. package/dist/cli/commands.d.mts +1 -16
  22. package/dist/cli/commands.mjs +144 -239
  23. package/dist/cli/help.d.mts +0 -19
  24. package/dist/cli/help.mjs +30 -55
  25. package/dist/cli/run.mjs +35 -79
  26. package/dist/cli/start.d.mts +2 -31
  27. package/dist/cli/start.mjs +13 -116
  28. package/dist/core/brand.d.mts +0 -7
  29. package/dist/core/brand.mjs +0 -8
  30. package/dist/core/errors.d.mts +0 -16
  31. package/dist/core/errors.mjs +0 -16
  32. package/dist/core/helpers.d.mts +0 -46
  33. package/dist/core/helpers.mjs +1 -64
  34. package/dist/core/node-trust.d.mts +0 -5
  35. package/dist/core/node-trust.mjs +0 -6
  36. package/dist/core/pick.d.mts +7 -55
  37. package/dist/core/pick.mjs +49 -106
  38. package/dist/core/request.d.mts +0 -46
  39. package/dist/core/request.mjs +1 -60
  40. package/dist/core/secrets.d.mts +0 -4
  41. package/dist/core/secrets.mjs +0 -10
  42. package/dist/core/state.d.mts +3 -1
  43. package/dist/core/state.mjs +147 -4
  44. package/dist/core/style.d.mts +0 -27
  45. package/dist/core/style.mjs +0 -20
  46. package/dist/core/version.d.mts +1 -2
  47. package/dist/core/version.mjs +1 -2
  48. package/dist/local/accounts.d.mts +25 -0
  49. package/dist/local/accounts.mjs +40 -0
  50. package/dist/local/agent-headers.d.mts +7 -0
  51. package/dist/local/agent-headers.mjs +44 -0
  52. package/dist/local/chatgpt-plan.d.mts +147 -0
  53. package/dist/local/chatgpt-plan.mjs +384 -0
  54. package/dist/local/command.d.mts +24 -0
  55. package/dist/local/command.mjs +211 -0
  56. package/dist/local/config.d.mts +49 -0
  57. package/dist/local/config.mjs +168 -0
  58. package/dist/local/decide.d.mts +37 -0
  59. package/dist/local/decide.mjs +201 -0
  60. package/dist/local/failure-signs.d.mts +4 -0
  61. package/dist/local/failure-signs.mjs +99 -0
  62. package/dist/local/keys.d.mts +32 -0
  63. package/dist/local/keys.mjs +239 -0
  64. package/dist/local/models.d.mts +53 -0
  65. package/dist/local/models.mjs +117 -0
  66. package/dist/local/replay.d.mts +59 -0
  67. package/dist/local/replay.mjs +143 -0
  68. package/dist/local/report.d.mts +43 -0
  69. package/dist/local/report.mjs +153 -0
  70. package/dist/local/request-log.d.mts +53 -0
  71. package/dist/local/request-log.mjs +69 -0
  72. package/dist/local/retry-after.d.mts +3 -0
  73. package/dist/local/retry-after.mjs +28 -0
  74. package/dist/local/rust-router.d.mts +39 -0
  75. package/dist/local/rust-router.mjs +54 -0
  76. package/dist/local/server.d.mts +27 -0
  77. package/dist/local/server.mjs +449 -0
  78. package/dist/local/status-line.d.mts +17 -0
  79. package/dist/local/status-line.mjs +81 -0
  80. package/dist/local/tiers.d.mts +3 -0
  81. package/dist/local/tiers.mjs +137 -0
  82. package/dist/local/traces.d.mts +69 -0
  83. package/dist/local/traces.mjs +341 -0
  84. package/dist/phantom.d.mts +0 -37
  85. package/dist/phantom.mjs +0 -31
  86. package/package.json +15 -9
  87. package/skills/phantom-ai/SKILL.md +28 -97
  88. package/dist/cli/screens.d.mts +0 -177
  89. package/dist/cli/screens.mjs +0 -398
  90. package/dist/core/free.d.mts +0 -13
  91. package/dist/core/free.mjs +0 -14
  92. package/dist/core/motion.d.mts +0 -47
  93. package/dist/core/motion.mjs +0 -156
  94. package/dist/core/shapes.d.mts +0 -13
  95. package/dist/core/shapes.mjs +0 -1
  96. package/dist/keys/command.d.mts +0 -16
  97. package/dist/keys/command.mjs +0 -143
  98. package/dist/keys/saved.d.mts +0 -96
  99. package/dist/keys/saved.mjs +0 -169
  100. package/dist/models/choice.d.mts +0 -7
  101. package/dist/models/choice.mjs +0 -27
  102. package/dist/models/command.d.mts +0 -8
  103. package/dist/models/command.mjs +0 -66
  104. package/dist/models/list.d.mts +0 -39
  105. package/dist/models/list.mjs +0 -39
  106. package/dist/receipts/command.d.mts +0 -7
  107. package/dist/receipts/command.mjs +0 -41
  108. package/dist/receipts/receipts.d.mts +0 -76
  109. package/dist/receipts/receipts.mjs +0 -118
  110. package/dist/setup/agents.d.mts +0 -149
  111. package/dist/setup/agents.mjs +0 -886
  112. package/dist/setup/apply.d.mts +0 -85
  113. package/dist/setup/apply.mjs +0 -301
  114. package/dist/setup/command.d.mts +0 -12
  115. package/dist/setup/command.mjs +0 -307
  116. package/dist/setup/editors.d.mts +0 -108
  117. package/dist/setup/editors.mjs +0 -500
  118. package/dist/setup/legacy.d.mts +0 -13
  119. package/dist/setup/legacy.mjs +0 -36
  120. package/dist/setup/plan.d.mts +0 -104
  121. package/dist/setup/plan.mjs +0 -132
  122. package/dist/setup/screen.d.mts +0 -30
  123. package/dist/setup/screen.mjs +0 -260
  124. package/dist/setup/shared.d.mts +0 -141
  125. package/dist/setup/shared.mjs +0 -88
  126. package/dist/setup/was.d.mts +0 -42
  127. package/dist/setup/was.mjs +0 -91
  128. package/dist/spend/command.d.mts +0 -5
  129. package/dist/spend/command.mjs +0 -235
  130. package/dist/spend/lineup.d.mts +0 -61
  131. package/dist/spend/lineup.mjs +0 -39
  132. package/dist/spend/reason.d.mts +0 -5
  133. package/dist/spend/reason.mjs +0 -60
  134. package/dist/spend/report.d.mts +0 -105
  135. package/dist/spend/report.mjs +0 -68
  136. package/dist/spend/routing.d.mts +0 -74
  137. package/dist/spend/routing.mjs +0 -57
  138. package/dist/workspace/command.d.mts +0 -59
  139. package/dist/workspace/command.mjs +0 -871
package/dist/cli/run.mjs CHANGED
@@ -1,42 +1,18 @@
1
+ // docs: `run()`, the CLI's one entry: reads the command line, opens the agent picker for `phantom` alone and the settings screen for `phantom config` alone at a terminal, prints help, refuses an unknown command or flag, and hands everything else to the command's handler in commands.mts
1
2
  import { VERSION } from "../core/version.mjs";
2
3
  import { nodeTrustWarning } from "../core/node-trust.mjs";
3
4
  import { die } from "../core/errors.mjs";
5
+ import { moveOldStateFolder } from "../core/state.mjs";
4
6
  import { colorOn, fitText } from "../core/style.mjs";
5
- import { ALIASES, closestCommand, commandFromWords, startScreen } from "./start.mjs";
6
7
  import { BackToMenu } from "../core/pick.mjs";
7
- import { runApp } from "./app.mjs";
8
8
  import { handleError, parseFlags, pickIo } from "../core/helpers.mjs";
9
- import { noKeyMessage, resolveApiKey } from "../keys/saved.mjs";
9
+ import { closestCommand, startScreen } from "./start.mjs";
10
+ import { runConfig, runPicker } from "./app.mjs";
10
11
  import { COMMANDS } from "./commands.mjs";
11
- import { HELP, PRIMARY_HELP } from "./help.mjs";
12
- import { LEGACY_SETUP_HINT, legacySetupFound } from "../setup/legacy.mjs";
13
- /**
14
- * Runs one CLI command and returns its exit code: 0 on success, 2 when the
15
- * API rejected the key, 1 for other errors. `verify` returns 1 when the check
16
- * fails. Errors go to `io.stderr` as JSON. It never calls `process.exit`.
17
- * @param argv The arguments after `phantom`.
18
- * @param env The environment to read settings from.
19
- * @param io Where output goes, whether stderr is a terminal (for progress lines),
20
- * and whether stdout is one (setup prints a summary there instead of JSON).
21
- * @param node The Node version it runs on; one too old to reject forged
22
- * eMudhra certificates gets a warning on stderr first.
23
- */
24
- /** Retired flags, accepted so the command can say what replaced them, and never suggested for a typo. */
25
- const RETIRED_FLAGS = ['pay', 'mpp'];
26
- /** Retired flags of one command: it refuses them with its own message, so they get past the unknown-flag check. */
27
- const RETIRED_COMMAND_FLAGS = { lineup: ['economy', 'economy-fallback'] };
28
- /** The flags every command takes, and the retired ones. */
29
- const EVERY_COMMAND_FLAGS = ['table', 'json', 'help', 'all', 'version', 'mcp', ...RETIRED_FLAGS];
30
- /**
31
- * The flags a command reads: each one its help names, plus those of the
32
- * command its subcommand names (`workspace fund` reads `fund`'s), plus
33
- * {@link EVERY_COMMAND_FLAGS}. A typo such as --yse, or a flag only another
34
- * command takes (balance --key), is refused instead of quietly ignored, which
35
- * in CI would otherwise drop the flag without a word.
36
- */
37
- function flagsOf(command, subcommand) {
38
- const helps = [command.help, COMMANDS.find((c) => c.name === subcommand)?.help ?? ''].join('\n');
39
- return new Set([...[...helps.matchAll(/--([a-z][a-z0-9-]*)/g)].map((m) => m[1]), ...EVERY_COMMAND_FLAGS, ...(RETIRED_COMMAND_FLAGS[command.name] ?? [])]);
12
+ import { HELP } from "./help.mjs";
13
+ const EVERY_COMMAND_FLAGS = ['table', 'json', 'help'];
14
+ function flagsOf(command) {
15
+ return new Set([...[...command.help.matchAll(/--([a-z][a-z0-9-]*)/g)].map((m) => m[1]), ...EVERY_COMMAND_FLAGS]);
40
16
  }
41
17
  export async function run(argv = process.argv.slice(2), env = process.env, io = {
42
18
  stdout: (s) => process.stdout.write(s),
@@ -45,7 +21,6 @@ export async function run(argv = process.argv.slice(2), env = process.env, io =
45
21
  stdoutIsTTY: Boolean(process.stdout.isTTY),
46
22
  columns: process.stdout.columns || process.stderr.columns,
47
23
  }, node = process.versions.node) {
48
- // A line wider than the terminal breaks at a word, under its own column, rather than wherever the edge falls.
49
24
  if (io.columns) {
50
25
  const { columns, stdout, stderr } = io;
51
26
  io = {
@@ -57,76 +32,57 @@ export async function run(argv = process.argv.slice(2), env = process.env, io =
57
32
  const unsafe = nodeTrustWarning(node);
58
33
  if (unsafe)
59
34
  io.stderr(unsafe);
35
+ const notice = moveOldStateFolder(env);
36
+ if (notice)
37
+ io.stderr(notice + '\n');
60
38
  if (argv[0] === '--version' || argv[0] === '-v') {
61
39
  io.stdout(VERSION + '\n');
62
40
  return 0;
63
41
  }
64
- // Words people type for a command run as that command: `phantom undo` is setup --restore,
65
- // `phantom help setup` is setup --help, and `phantom start` opens the menu.
66
- if (argv[0] === 'help' && COMMANDS.some((c) => c.name === argv[1]))
67
- argv = [argv[1], '--help'];
68
- else if (argv[0] && Object.hasOwn(ALIASES, argv[0]))
69
- argv = [...ALIASES[argv[0]], ...(argv[0] === 'help' ? [] : argv.slice(1))];
70
- // `--help` anywhere before a `--` asks for help, so `phantom setup --help`
71
- // prints it rather than running setup.
42
+ if (argv[0] === 'help')
43
+ argv = [...argv.slice(1, 2), '--help'];
72
44
  const own = argv.includes('--') ? argv.slice(0, argv.indexOf('--')) : argv;
73
- // Only a person at a terminal sees the hint: scripts and agents read stderr
74
- // as JSON errors, and the MCP server and setup itself have no use for it.
75
- if (io.isTTY && !['setup', 'mcp', 'key', 'keys'].includes(own[0] ?? '') && legacySetupFound(env)) {
76
- io.stderr(LEGACY_SETUP_HINT + '\n');
77
- }
45
+ const runCommand = (next) => run(next, env, { ...io, fromMenu: true }, node);
46
+ const pick = pickIo({ io, env });
78
47
  if (argv.length === 0) {
79
- const signedIn = Boolean(resolveApiKey(env));
80
- const pick = pickIo({ io, env });
81
48
  if (!pick) {
82
- io.stdout(startScreen(env, colorOn(env, io.stdoutIsTTY), signedIn) + '\n');
49
+ io.stdout(startScreen(env, colorOn(env, io.stdoutIsTTY)) + '\n');
83
50
  return 0;
84
51
  }
85
- // At a terminal, phantom alone is an app you stay in: a menu, each command's result, and what to do next.
86
- return runApp(env, pick, io.stderr, (next) => run(next, env, { ...io, fromMenu: true }, node));
52
+ return runPicker(env, pick, io.stderr, runCommand);
87
53
  }
88
54
  if (own.includes('--help') || own.includes('-h')) {
89
- const commandHelp = COMMANDS.find((entry) => entry.name === own[0])?.help;
90
- io.stdout((own.includes('--all') ? HELP : commandHelp?.replace(/\s+$/, '') ?? PRIMARY_HELP) + '\n');
55
+ const usage = COMMANDS.find((entry) => entry.name === own[0])?.help;
56
+ io.stdout((usage ?? HELP) + '\n');
91
57
  return 0;
92
58
  }
93
59
  try {
94
60
  const command = COMMANDS.find((entry) => entry.name === argv[0]);
95
61
  if (!command) {
96
- // A near miss ("stup"), then a word in a sentence ("how do i add money"), then the way in.
97
- const guess = closestCommand(argv[0], COMMANDS.map((entry) => entry.name)) ?? commandFromWords(argv);
98
- die(guess ? `Unknown command "${argv[0]}". Did you mean phantom ${guess}?` : `Unknown command "${argv[0]}". Try phantom (a menu), phantom setup, or phantom --help for every command.`);
62
+ const guess = closestCommand(argv[0], COMMANDS.map((entry) => entry.name));
63
+ die(guess
64
+ ? `Unknown command "${argv[0]}". Did you mean phantom ${guess}?`
65
+ : `Unknown command "${argv[0]}". phantom starts your coding agents: phantom (pick one), phantom config for settings, phantom report for activity, phantom --help for the rest.`, 'unknown_command');
99
66
  }
100
- const keyless = command.keyless === true ||
101
- (command.keyless?.some((flag) => own.slice(1).some((arg) => arg === flag || arg.startsWith(flag + '='))) ?? false);
102
- const apiKey = keyless ? '' : resolveApiKey(env);
103
- if (!apiKey && !keyless)
104
- die(noKeyMessage(env));
67
+ if (command.name === 'config' && own.length === 1 && pick)
68
+ return await runConfig(env, pick, io.stderr, runCommand);
105
69
  const subcommand = argv[1] && !argv[1].startsWith('--') ? argv[1] : undefined;
106
- const flagArgs = subcommand ? argv.slice(2) : argv.slice(1);
107
- // Flags after -- belong to the agent phantom starts, so only the ones before it are checked.
108
- const flags = parseFlags(flagArgs);
109
- const ownFlags = parseFlags(flagArgs.includes('--') ? flagArgs.slice(0, flagArgs.indexOf('--')) : flagArgs);
110
- // claude, codex and pi hand their arguments to the agent, so they check their own.
111
- const passesArgs = command.handler === COMMANDS.find((c) => c.name === 'claude')?.handler;
112
- const known = flagsOf(command, subcommand);
113
- for (const name of passesArgs ? [] : Object.keys(ownFlags)) {
114
- if (known.has(name))
115
- continue;
116
- const guess = closestCommand(name, [...known].filter((flag) => !RETIRED_FLAGS.includes(flag) && !(RETIRED_COMMAND_FLAGS[argv[0]] ?? []).includes(flag)));
117
- die(`Unknown flag --${name} for phantom ${argv[0]}.${guess ? ` Did you mean --${guess}?` : ''} See phantom ${argv[0]} --help.`, 'unknown_flag');
70
+ const flags = parseFlags(own.slice(subcommand ? 2 : 1));
71
+ if (command.handler !== COMMANDS[0].handler) {
72
+ const known = flagsOf(command);
73
+ for (const name of Object.keys(flags)) {
74
+ if (known.has(name))
75
+ continue;
76
+ const guess = closestCommand(name, [...known]);
77
+ die(`Unknown flag --${name} for phantom ${argv[0]}.${guess ? ` Did you mean --${guess}?` : ''} See phantom ${argv[0]} --help.`, 'unknown_flag');
78
+ }
118
79
  }
119
- // A person at a terminal reads each command's screen; a pipe (scripts, agents) or --json gets JSON.
120
80
  const table = Boolean(flags['table']) || (Boolean(io.stdoutIsTTY) && !flags['json']);
121
- const baseUrl = env.PHANTOM_BASE_URL;
122
- const input = { argv, env, io, apiKey, subcommand, flags, table, baseUrl };
123
- return await command.handler(input);
81
+ return await command.handler({ argv, env, io, subcommand, flags, table, baseUrl: env.PHANTOM_BASE_URL });
124
82
  }
125
83
  catch (err) {
126
- // Esc on the first step of a command the menu started: let the menu show again.
127
84
  if (err instanceof BackToMenu && io.fromMenu)
128
85
  throw err;
129
- // A person at a terminal gets a sentence; scripts and agents reading stderr get JSON.
130
86
  return handleError(err, io.stderr, { human: io.isTTY, env });
131
87
  }
132
88
  }
@@ -1,34 +1,5 @@
1
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
- */
2
+ export declare function startScreen(env: Env, color: boolean): string;
3
+ export declare function startHeader(env: Env, color: boolean): string;
12
4
  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
5
  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;
@@ -1,33 +1,20 @@
1
- // What `phantom` alone prints: the way in. With no key yet, one command to
2
- // start, `phantom setup`. Once signed in, the handful of commands people use
3
- // day to day. It reads no network, so it prints at once, even offline.
1
+ // docs: What `phantom` alone prints without a terminal (three lines: the agents that route on your own accounts, settings, report), the ghost title over the screens, and the guess at a mistyped command. Reads no network, so it prints at once, even offline
2
+ import { ROUTES_HERE } from "../agents/command.mjs";
4
3
  import { brandHeader } from "../core/brand.mjs";
5
4
  import { paint } from "../core/style.mjs";
6
- import { FREE_LINE } from "../core/free.mjs";
7
- /** One row: a command in cyan, padded, then what it does. */
8
- const row = (p, command, about) => ` ${p.cyan(command.padEnd(18))}${about}`;
9
- /** An uppercase caption over a thin rule, like the site's section labels. */
10
- const caption = (p, text) => [` ${p.bold(text)}`, ` ${p.dim('─'.repeat(56))}`];
11
- /**
12
- * The start screen. `signedIn` is whether a key is saved or set, so it shows
13
- * the first step or the everyday commands.
14
- */
15
- export function startScreen(env, color, signedIn) {
5
+ const LINE = 'Routes your coding agents to your own plans.';
6
+ export function startScreen(env, color) {
16
7
  const p = paint(env, color);
17
- const lines = ['', ...brandHeader(p, color, '')];
18
- if (!signedIn) {
19
- lines.push(...caption(p, 'START HERE'), row(p, 'phantom setup', 'signs you in and connects your coding agents'), ` ${' '.repeat(18)}${p.dim(FREE_LINE)}`, '', ` Then use your agent as usual, or start it with ${p.cyan('phantom claude')}, ${p.cyan('phantom codex')} or ${p.cyan('phantom pi')}.`);
20
- }
21
- else {
22
- lines.push(` ${p.lime('✓')} Signed in.`, '', ...caption(p, 'EVERYDAY'), row(p, 'phantom claude', 'run Claude Code on Phantom AI (also codex, pi)'), row(p, 'phantom balance', 'your credit'), row(p, 'phantom spend', 'what you spent, and what phantom-1 saved'), row(p, 'phantom setup', 'connect more agents, or change how they run'));
23
- }
24
- lines.push('', ` All commands: ${p.cyan('phantom --help')}`, '');
25
- return lines.join('\n');
8
+ return [
9
+ ...(color ? ['', ...brandHeader(p, color, '', LINE)] : []),
10
+ `Start an agent: ${ROUTES_HERE.map((a) => p.cyan(`phantom ${a}`)).join(', ')}`,
11
+ `Settings: ${p.cyan('phantom config')}`,
12
+ `Report: ${p.cyan('phantom report --since 1d')}`,
13
+ ].join('\n');
14
+ }
15
+ export function startHeader(env, color) {
16
+ return ['', ...brandHeader(paint(env, color), color, '', LINE)].join('\n');
26
17
  }
27
- /**
28
- * How many single-letter edits turn `a` into `b`: a letter added, removed or
29
- * changed, or two neighbours swapped ("yse" is one edit from "yes").
30
- */
31
18
  export function editDistance(a, b) {
32
19
  const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
33
20
  for (let i = 1; i <= a.length; i++) {
@@ -39,104 +26,14 @@ export function editDistance(a, b) {
39
26
  }
40
27
  return d[a.length][b.length];
41
28
  }
42
- /**
43
- * The command `typed` was most likely meant to be: the nearest name at most
44
- * two edits away, or null. On a tie, the one that starts with the same letter.
45
- */
46
29
  export function closestCommand(typed, names) {
47
30
  const t = typed.toLowerCase();
48
31
  let best = null;
49
32
  let bestScore = 3;
50
33
  for (const name of names) {
51
- // A different first letter counts a little against a guess, so "yse" means "yes", not "use".
52
34
  const score = editDistance(t, name) + (name[0] === t[0] ? 0 : 0.5);
53
35
  if (score < bestScore)
54
36
  [best, bestScore] = [name, score];
55
37
  }
56
38
  return best;
57
39
  }
58
- /** The title block over the start menu: the ghost and PHANTOM. */
59
- export function startHeader(env, color) {
60
- return ['', ...brandHeader(paint(env, color), color, '')].join('\n');
61
- }
62
- /**
63
- * The start menu's choices, each the command it runs. Without a key, setup
64
- * comes first. Signed in but never set up, finishing setup comes first.
65
- * Once set up, the agents and the money do, with undo near the end.
66
- */
67
- export function startChoices(signedIn, setUp = signedIn) {
68
- const quit = { label: 'Quit', value: [] };
69
- if (!signedIn) {
70
- return [
71
- { label: 'Set up my coding agents', hint: 'sign in and connect them, free to start', value: ['setup'] },
72
- { label: 'Sign in only', hint: 'or save a Phantom key you already have', value: ['login'] },
73
- { label: 'See every command', value: ['--help'] },
74
- quit,
75
- ];
76
- }
77
- const finish = setUp ? [] : [{ label: 'Finish setting up my agents', hint: "you're signed in, but no agent uses Phantom yet", value: ['setup'] }];
78
- return [
79
- ...finish,
80
- { label: 'Start Claude Code', hint: 'on Phantom AI', value: ['claude'] },
81
- { label: 'Start Codex', hint: 'on Phantom AI', value: ['codex'] },
82
- { label: 'Start pi', hint: 'on Phantom AI', value: ['pi'] },
83
- { label: 'Balance', hint: 'your credit', value: ['balance'] },
84
- { label: 'Spend', hint: 'what you spent, and what phantom-1 saved', value: ['spend'] },
85
- { label: 'Add credit', hint: 'by card or crypto', value: ['fund'] },
86
- ...(setUp ? [{ label: 'Set up more agents', hint: 'or change how they run', value: ['setup'] }] : []),
87
- ...(setUp ? [{ label: 'Undo setup', hint: 'put your agents back how they were', value: ['setup', '--restore'] }] : []),
88
- { label: 'See every command', value: ['--help'] },
89
- quit,
90
- ];
91
- }
92
- /** "Unknown <command> subcommand" with the nearest real one, or the list when nothing is close. */
93
- export function unknownSub(command, typed, subs) {
94
- const guess = closestCommand(typed, subs);
95
- return guess
96
- ? `Unknown phantom ${command} subcommand "${typed}". Did you mean phantom ${command} ${guess}?`
97
- : `Unknown phantom ${command} subcommand "${typed}". It takes: ${subs.join(', ')}.`;
98
- }
99
- /**
100
- * Words people type instead of a command, and the command they mean. These
101
- * run as that command, and stay out of --help.
102
- */
103
- export const ALIASES = {
104
- help: ['--help'],
105
- undo: ['setup', '--restore'],
106
- uninstall: ['setup', '--restore'],
107
- signin: ['login'],
108
- 'sign-in': ['login'],
109
- signout: ['logout'],
110
- 'sign-out': ['logout'],
111
- add: ['fund'],
112
- topup: ['fund'],
113
- 'top-up': ['fund'],
114
- credit: ['fund'],
115
- savings: ['spend'],
116
- usage: ['spend'],
117
- costs: ['spend'],
118
- status: ['workspace'],
119
- start: [],
120
- menu: [],
121
- };
122
- /** Words in a sentence typed as a command ("how do i add money"), and the command they point at. */
123
- const HINTS = [
124
- [/^(money|credit|fund|pay|topup|top-up|card)$/, 'fund'],
125
- [/^(charged|charge|cost|costs|spent|spend|saving|savings|bill|billing)$/, 'spend'],
126
- [/^(undo|uninstall|remove|revert|reset)$/, 'setup --restore'],
127
- [/^(setup|connect|install|configure)$/, 'setup'],
128
- [/^(balance|left)$/, 'balance'],
129
- [/^(key|keys)$/, 'keys'],
130
- [/^(claude|codex)$/, 'claude'],
131
- [/^(login|signin|sign)$/, 'login'],
132
- ];
133
- /** The command a sentence most likely means, from the first word in it that points at one, or null. */
134
- export function commandFromWords(words) {
135
- for (const word of words) {
136
- const w = word.toLowerCase().replace(/[^a-z-]/g, '');
137
- const hit = HINTS.find(([re]) => re.test(w));
138
- if (hit)
139
- return hit[1];
140
- }
141
- return null;
142
- }
@@ -1,12 +1,5 @@
1
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
2
  export declare const GHOST: Array<[body: string, rim: string]>;
4
3
  export declare const WORDMARK: string[];
5
- /** The one line that says what phantom does, everywhere the CLI describes itself. */
6
4
  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
5
  export declare function brandHeader(p: Paint, color: boolean, label: string, line?: string): string[];
@@ -1,11 +1,9 @@
1
- /** The ghost in block characters: white, eyes set to the right, a wavy hem, and a thin mint edge on its right side. */
2
1
  export const GHOST = [
3
2
  [' ▄████▄', ''],
4
3
  ['████ █ ', '▌'],
5
4
  ['███████', '▌'],
6
5
  ['▀█▀█▀█▀', ''],
7
6
  ];
8
- /** PHANTOM in three rows of half blocks. Each letter is its three rows, top to bottom. */
9
7
  const LETTERS = {
10
8
  P: ['█▀▀▄', '█▀▀ ', '▀ '],
11
9
  H: ['█ █', '█▀▀█', '▀ ▀'],
@@ -16,13 +14,7 @@ const LETTERS = {
16
14
  M: ['█▄ ▄█', '█ ▀ █', '▀ ▀'],
17
15
  };
18
16
  export const WORDMARK = [0, 1, 2].map((row) => [...'PHANTOM'].map((c) => LETTERS[c][row]).join(' '));
19
- /** The one line that says what phantom does, everywhere the CLI describes itself. */
20
17
  export const TAGLINE = 'Points your coding agents at Phantom AI.';
21
- /**
22
- * A screen's title block: the ghost, PHANTOM beside it, and `label` in lime
23
- * with `line` along the ghost's hem. For example `setup Points your coding
24
- * agents at Phantom AI.` Without color, a plain one-line title instead.
25
- */
26
18
  export function brandHeader(p, color, label, line = TAGLINE) {
27
19
  if (!color)
28
20
  return [` ${p.bold(`phantom ${label}`.trim())} ${line}`, ''];
@@ -1,27 +1,11 @@
1
- /** An error answer from the Phantom AI API: 401 or 403 maps to exit code 2. */
2
1
  export declare class PhantomApiError extends Error {
3
- /** The HTTP status code of the answer. */
4
2
  readonly status: number;
5
- /** The API's error code, or the status code as text when the answer carries none. */
6
3
  readonly code: string;
7
4
  constructor(status: number, code: string, message: string);
8
5
  }
9
- /** An error phantom raises itself, such as a missing flag or a refused payment. */
10
6
  export declare class CliError extends Error {
11
- /** A short code for the error, such as `keychain_failed`. `cli_error` when none is given. */
12
7
  readonly code: string;
13
- /** The process exit code {@link run} returns for it. 1 unless given. */
14
8
  readonly exitCode: number;
15
9
  constructor(message: string, code?: string, exitCode?: number);
16
10
  }
17
- /**
18
- * Throws a {@link CliError}. Every refusal in phantom goes through here.
19
- * @param msg The message the user sees.
20
- * @param code The error code, printed in the JSON error.
21
- * @param exitCode The process exit code.
22
- */
23
11
  export declare function die(msg: string, code?: string, exitCode?: number): never;
24
- /** How to get a key, for every message about a missing one. */
25
- export declare const GET_A_KEY = "Run phantom login to sign in, or set PHANTOM_API_KEY.";
26
- /** The message for a command that needs a key and has none. */
27
- export declare const NO_KEY = "No Phantom key yet. Run phantom login to sign in, or set PHANTOM_API_KEY.";
@@ -1,8 +1,5 @@
1
- /** An error answer from the Phantom AI API: 401 or 403 maps to exit code 2. */
2
1
  export class PhantomApiError extends Error {
3
- /** The HTTP status code of the answer. */
4
2
  status;
5
- /** The API's error code, or the status code as text when the answer carries none. */
6
3
  code;
7
4
  constructor(status, code, message) {
8
5
  super(message);
@@ -11,11 +8,8 @@ export class PhantomApiError extends Error {
11
8
  this.code = code;
12
9
  }
13
10
  }
14
- /** An error phantom raises itself, such as a missing flag or a refused payment. */
15
11
  export class CliError extends Error {
16
- /** A short code for the error, such as `keychain_failed`. `cli_error` when none is given. */
17
12
  code;
18
- /** The process exit code {@link run} returns for it. 1 unless given. */
19
13
  exitCode;
20
14
  constructor(message, code = 'cli_error', exitCode = 1) {
21
15
  super(message);
@@ -24,16 +18,6 @@ export class CliError extends Error {
24
18
  this.exitCode = exitCode;
25
19
  }
26
20
  }
27
- /**
28
- * Throws a {@link CliError}. Every refusal in phantom goes through here.
29
- * @param msg The message the user sees.
30
- * @param code The error code, printed in the JSON error.
31
- * @param exitCode The process exit code.
32
- */
33
21
  export function die(msg, code = 'cli_error', exitCode = 1) {
34
22
  throw new CliError(msg, code, exitCode);
35
23
  }
36
- /** How to get a key, for every message about a missing one. */
37
- export const GET_A_KEY = 'Run phantom login to sign in, or set PHANTOM_API_KEY.';
38
- /** The message for a command that needs a key and has none. */
39
- export const NO_KEY = `No Phantom key yet. ${GET_A_KEY}`;
@@ -1,75 +1,29 @@
1
1
  import type { Env } from './state.mts';
2
2
  import { type KeySource, type PickIo } from './pick.mts';
3
- /**
4
- * Where a picker draws and reads, when this run can show one: a person at a
5
- * terminal (or keys a test scripted), not CI. Null means use flags and the
6
- * plain prompts instead.
7
- */
8
3
  export declare function pickIo(input: Pick<CommandInput, 'io' | 'env'>): PickIo | null;
9
- /**
10
- * Whether a command should draw its screen rather than print JSON: with
11
- * `--table`, or when stdout is a terminal, unless `--json` asks for JSON.
12
- * Scripts and agents read stdout through a pipe, so they keep getting JSON.
13
- */
14
- export declare function showsScreen(input: Pick<CommandInput, 'table' | 'io' | 'flags'>): boolean;
15
- /**
16
- * Prints an error to stderr as one line of JSON, `{"error":{...}}`, and
17
- * returns the exit code: 2 for a key the API rejected (401 or 403), the
18
- * {@link CliError}'s own code, or 1 for anything else.
19
- */
20
4
  export declare function handleError(err: unknown, stderr?: (s: string) => void, opts?: {
21
5
  human?: boolean;
22
6
  env?: Env;
23
7
  }): number;
24
- /**
25
- * Reads `--name value`, `--name=value` and bare `--name` (true) from the
26
- * arguments. A value that starts with `--` counts as the next flag. Anything
27
- * not after a `--name` is skipped.
28
- */
29
8
  export declare function parseFlags(args: string[]): Record<string, string | true>;
30
- /**
31
- * A flag's value as a number, or undefined when the flag is absent.
32
- * @throws {@link CliError} when the flag has no value or the value is not a number.
33
- */
34
9
  export declare function flagNum(flags: Record<string, string | true>, name: string): number | undefined;
35
- /**
36
- * A spending control's value for a key: a number above zero, `none` for no limit (null), or
37
- * undefined when the flag is absent. A mistyped value stops the command, because a number that
38
- * silently became "no limit" would remove the key's cap.
39
- * @param dollars True for money flags, which may start with `$`.
40
- * @throws {@link CliError} `key_usage` when the flag has no value, or the value is not a finite number above zero. The server refuses 0 for every one of these, and `setup --limit` does too.
41
- */
42
- export declare function limitFlag(flags: Record<string, string | true>, name: string, dollars?: boolean): number | null | undefined;
43
- /** Opens a URL in the user's default browser. */
44
10
  export declare function openUrl(url: string): void;
45
- /** Prints a result: JSON by default, or `render(data)` with `--table`. */
46
11
  export declare function out(data: unknown, table: boolean, render: (d: unknown) => string, stdout?: (s: string) => void): void;
47
- /** What `run()` hands the handler of each command: the parsed command line, and where output goes. */
48
12
  export type CommandInput = {
49
- /** The arguments after `phantom`. */
50
13
  argv: string[];
51
- /** The environment to read settings from. */
52
14
  env: Env;
53
- /** Where output goes, whether stderr and stdout are terminals, and how to ask a question. */
54
15
  io: {
55
16
  stdout: (s: string) => void;
56
17
  stderr: (s: string) => void;
57
18
  isTTY?: boolean;
58
19
  stdoutIsTTY?: boolean;
59
- /** The terminal's width. When set, screen text wider than it breaks at a word (`fitText`); JSON never does. */
60
20
  columns?: number;
61
21
  ask?: (question: string) => Promise<string>;
62
22
  keys?: () => KeySource;
63
23
  fromMenu?: boolean;
64
24
  };
65
- /** The key the command runs as. Empty for a command that needs none. */
66
- apiKey: string;
67
- /** The word after the command, when it is not a flag. */
68
25
  subcommand: string | undefined;
69
- /** The flags, from {@link parseFlags}. */
70
26
  flags: Record<string, string | true>;
71
- /** True with `--table`. */
72
27
  table: boolean;
73
- /** PHANTOM_BASE_URL, when set. */
74
28
  baseUrl: string | undefined;
75
29
  };