@phantomcodes/cli 1.6.3 → 1.7.1

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 (140) hide show
  1. package/LICENSE +1 -2
  2. package/README.md +139 -118
  3. package/bin/phantom.mjs +37 -2
  4. package/dist/agents/command.d.mts +8 -27
  5. package/dist/agents/command.mjs +323 -59
  6. package/dist/agents/login.d.mts +3 -0
  7. package/dist/agents/login.mjs +97 -0
  8. package/dist/agents/opencode-check.d.mts +15 -0
  9. package/dist/agents/opencode-check.mjs +193 -0
  10. package/dist/agents/phantom-key.d.mts +7 -0
  11. package/dist/agents/phantom-key.mjs +40 -0
  12. package/dist/agents/proxy.d.mts +26 -28
  13. package/dist/agents/proxy.mjs +225 -33
  14. package/dist/chatgpt/command.d.mts +2 -0
  15. package/dist/chatgpt/command.mjs +119 -0
  16. package/dist/chatgpt/session.d.mts +87 -0
  17. package/dist/chatgpt/session.mjs +253 -0
  18. package/dist/cli/accounts.d.mts +21 -0
  19. package/dist/cli/accounts.mjs +96 -0
  20. package/dist/cli/app.d.mts +4 -24
  21. package/dist/cli/app.mjs +224 -139
  22. package/dist/cli/commands.d.mts +1 -16
  23. package/dist/cli/commands.mjs +144 -239
  24. package/dist/cli/help.d.mts +0 -19
  25. package/dist/cli/help.mjs +30 -55
  26. package/dist/cli/run.mjs +35 -79
  27. package/dist/cli/start.d.mts +2 -31
  28. package/dist/cli/start.mjs +13 -116
  29. package/dist/core/brand.d.mts +0 -7
  30. package/dist/core/brand.mjs +0 -8
  31. package/dist/core/errors.d.mts +0 -16
  32. package/dist/core/errors.mjs +0 -16
  33. package/dist/core/helpers.d.mts +0 -46
  34. package/dist/core/helpers.mjs +1 -64
  35. package/dist/core/node-trust.d.mts +0 -5
  36. package/dist/core/node-trust.mjs +0 -6
  37. package/dist/core/pick.d.mts +7 -55
  38. package/dist/core/pick.mjs +49 -106
  39. package/dist/core/request.d.mts +0 -46
  40. package/dist/core/request.mjs +1 -60
  41. package/dist/core/secrets.d.mts +0 -4
  42. package/dist/core/secrets.mjs +0 -10
  43. package/dist/core/state.d.mts +3 -1
  44. package/dist/core/state.mjs +147 -4
  45. package/dist/core/style.d.mts +0 -27
  46. package/dist/core/style.mjs +0 -20
  47. package/dist/core/version.d.mts +1 -2
  48. package/dist/core/version.mjs +1 -2
  49. package/dist/local/accounts.d.mts +25 -0
  50. package/dist/local/accounts.mjs +40 -0
  51. package/dist/local/agent-headers.d.mts +7 -0
  52. package/dist/local/agent-headers.mjs +44 -0
  53. package/dist/local/chatgpt-plan.d.mts +147 -0
  54. package/dist/local/chatgpt-plan.mjs +384 -0
  55. package/dist/local/command.d.mts +24 -0
  56. package/dist/local/command.mjs +211 -0
  57. package/dist/local/config.d.mts +49 -0
  58. package/dist/local/config.mjs +168 -0
  59. package/dist/local/decide.d.mts +37 -0
  60. package/dist/local/decide.mjs +201 -0
  61. package/dist/local/failure-signs.d.mts +4 -0
  62. package/dist/local/failure-signs.mjs +99 -0
  63. package/dist/local/keys.d.mts +32 -0
  64. package/dist/local/keys.mjs +239 -0
  65. package/dist/local/models.d.mts +53 -0
  66. package/dist/local/models.mjs +117 -0
  67. package/dist/local/replay.d.mts +59 -0
  68. package/dist/local/replay.mjs +143 -0
  69. package/dist/local/report.d.mts +43 -0
  70. package/dist/local/report.mjs +153 -0
  71. package/dist/local/request-log.d.mts +53 -0
  72. package/dist/local/request-log.mjs +69 -0
  73. package/dist/local/retry-after.d.mts +3 -0
  74. package/dist/local/retry-after.mjs +28 -0
  75. package/dist/local/rust-router.d.mts +39 -0
  76. package/dist/local/rust-router.mjs +54 -0
  77. package/dist/local/server.d.mts +27 -0
  78. package/dist/local/server.mjs +449 -0
  79. package/dist/local/status-line.d.mts +17 -0
  80. package/dist/local/status-line.mjs +81 -0
  81. package/dist/local/tiers.d.mts +3 -0
  82. package/dist/local/tiers.mjs +137 -0
  83. package/dist/local/traces.d.mts +69 -0
  84. package/dist/local/traces.mjs +341 -0
  85. package/dist/phantom.d.mts +0 -37
  86. package/dist/phantom.mjs +0 -31
  87. package/package.json +15 -9
  88. package/skills/phantom-ai/SKILL.md +28 -97
  89. package/dist/cli/screens.d.mts +0 -177
  90. package/dist/cli/screens.mjs +0 -398
  91. package/dist/core/free.d.mts +0 -13
  92. package/dist/core/free.mjs +0 -14
  93. package/dist/core/motion.d.mts +0 -47
  94. package/dist/core/motion.mjs +0 -156
  95. package/dist/core/shapes.d.mts +0 -13
  96. package/dist/core/shapes.mjs +0 -1
  97. package/dist/keys/command.d.mts +0 -16
  98. package/dist/keys/command.mjs +0 -143
  99. package/dist/keys/saved.d.mts +0 -96
  100. package/dist/keys/saved.mjs +0 -169
  101. package/dist/models/choice.d.mts +0 -7
  102. package/dist/models/choice.mjs +0 -27
  103. package/dist/models/command.d.mts +0 -8
  104. package/dist/models/command.mjs +0 -66
  105. package/dist/models/list.d.mts +0 -39
  106. package/dist/models/list.mjs +0 -39
  107. package/dist/receipts/command.d.mts +0 -7
  108. package/dist/receipts/command.mjs +0 -41
  109. package/dist/receipts/receipts.d.mts +0 -76
  110. package/dist/receipts/receipts.mjs +0 -118
  111. package/dist/setup/agents.d.mts +0 -149
  112. package/dist/setup/agents.mjs +0 -886
  113. package/dist/setup/apply.d.mts +0 -85
  114. package/dist/setup/apply.mjs +0 -301
  115. package/dist/setup/command.d.mts +0 -12
  116. package/dist/setup/command.mjs +0 -307
  117. package/dist/setup/editors.d.mts +0 -108
  118. package/dist/setup/editors.mjs +0 -500
  119. package/dist/setup/legacy.d.mts +0 -13
  120. package/dist/setup/legacy.mjs +0 -36
  121. package/dist/setup/plan.d.mts +0 -104
  122. package/dist/setup/plan.mjs +0 -132
  123. package/dist/setup/screen.d.mts +0 -30
  124. package/dist/setup/screen.mjs +0 -260
  125. package/dist/setup/shared.d.mts +0 -141
  126. package/dist/setup/shared.mjs +0 -88
  127. package/dist/setup/was.d.mts +0 -42
  128. package/dist/setup/was.mjs +0 -91
  129. package/dist/spend/command.d.mts +0 -5
  130. package/dist/spend/command.mjs +0 -235
  131. package/dist/spend/lineup.d.mts +0 -61
  132. package/dist/spend/lineup.mjs +0 -39
  133. package/dist/spend/reason.d.mts +0 -5
  134. package/dist/spend/reason.mjs +0 -60
  135. package/dist/spend/report.d.mts +0 -105
  136. package/dist/spend/report.mjs +0 -68
  137. package/dist/spend/routing.d.mts +0 -74
  138. package/dist/spend/routing.mjs +0 -57
  139. package/dist/workspace/command.d.mts +0 -59
  140. package/dist/workspace/command.mjs +0 -871
package/dist/cli/app.mjs CHANGED
@@ -1,157 +1,245 @@
1
- import { colorOn, paint } from "../core/style.mjs";
2
- import { BackToMenu, Cancelled, choose } from "../core/pick.mjs";
3
- import { onPath } from "../setup/shared.mjs";
4
- import { isSetUp } from "../setup/apply.mjs";
5
- import { resolveApiKey } from "../keys/saved.mjs";
6
- import { hideHints } from "./screens.mjs";
1
+ // docs: The two screens phantom draws at a terminal. `phantom` alone lists, under one routing line, the installed agents that route on your own accounts (`ROUTES_HERE`: pi and OpenCode), then Settings and Report (`phantom report --since 1d`); Enter on an agent starts it with the same command a person would type, and with no local.json it opens the settings first. `phantom config` alone is the settings screen: the PROVIDERS table, then Standard and Frontier (each a list of every connected provider's models, plus its fallback), Providers (ChatGPT, Z.ai and the Gateway, each opening its sign-in or key actions) and Back. Each choice runs the scriptable command (`phantom config --standard zai:glm-5.4`, `phantom config key set zai`, ...). Esc goes back, Ctrl+C stops (130)
2
+ import { existsSync } from 'node:fs';
3
+ import { handleError } from "../core/helpers.mjs";
4
+ import { colorOn, fitLine, paint } from "../core/style.mjs";
5
+ import { askText, BackToMenu, Cancelled, choose, chooseOrType } from "../core/pick.mjs";
6
+ import { AGENTS as LAUNCHERS, ROUTES_HERE, onPath } from "../agents/command.mjs";
7
+ import { ACCOUNT_KINDS } from "../local/accounts.mjs";
8
+ import { STARTER, TIER_NAME, localConfigPath, readLocalConfig, savedOrStarter, writeLocalConfig } from "../local/config.mjs";
9
+ import { shown } from "../local/keys.mjs";
10
+ import { listModels } from "../local/models.mjs";
11
+ import { accountsTable, cut, readAccounts, routingLine } from "./accounts.mjs";
7
12
  import { startHeader } from "./start.mjs";
8
- import { COMMANDS } from "./commands.mjs";
9
- import { FREE_LINE } from "../core/free.mjs";
10
- /** The agents the menu can start, and the program each needs on this computer. */
11
- const AGENTS = [
12
- { label: 'Start Claude Code', bin: 'claude', run: ['claude'] },
13
- { label: 'Start Codex', bin: 'codex', run: ['codex'] },
14
- { label: 'Start pi', bin: 'pi', run: ['pi'] },
15
- ];
16
- /** The main menu for the state this computer is in. */
17
- export function mainMenu(s) {
18
- const quit = { label: 'Quit', value: { run: [] } };
19
- if (!s.signedIn) {
20
- return [
21
- { label: 'Set up my coding agents', hint: 'sign in and connect them, free to start', value: { run: ['setup'] } },
22
- { label: 'Sign in only', hint: 'or save a Phantom key you already have', value: { run: ['login'] } },
23
- { label: 'Every command', hint: 'pick one to run', value: { open: 'commands' } },
24
- quit,
25
- ];
13
+ const AGENT_NAMES = { pi: 'pi', opencode: 'OpenCode', codex: 'Codex', claude: 'Claude Code' };
14
+ const PROVIDERS = { 'chatgpt-plan': 'ChatGPT', 'zai-coding-plan': 'Z.ai', gateway: 'Vercel AI Gateway' };
15
+ const PROVIDER_ORDER = Object.keys(PROVIDERS);
16
+ function readProviders(env, config) {
17
+ const accounts = { ...config.accounts };
18
+ for (const kind of PROVIDER_ORDER) {
19
+ const name = ACCOUNT_KINDS[kind].setupName;
20
+ const lacking = !Object.values(config.accounts).some((a) => a.kind === kind) && !Object.hasOwn(config.accounts, name);
21
+ if (lacking)
22
+ accounts[name] = kind === 'chatgpt-plan' ? { kind } : { kind, key: null };
26
23
  }
27
- // Only agents that are installed here, so the menu never offers one that can't start.
28
- const agents = s.setUp ? AGENTS.filter((a) => s.installed(a.bin)).map((a) => ({ label: a.label, hint: 'on Phantom AI', value: { run: a.run } })) : [];
29
- return [
30
- ...(s.setUp ? [] : [{ label: 'Finish setting up my agents', hint: 'no agent uses Phantom yet', value: { run: ['setup'] } }]),
31
- ...agents,
32
- { label: 'Balance', hint: 'what this key can spend', value: { run: ['balance'] } },
33
- { label: 'Spend', hint: 'what you spent, and what phantom-1 saved', value: { run: ['spend'] } },
34
- { label: 'Add credit', hint: 'by card or crypto', value: { run: ['fund'] } },
35
- { label: 'Models', hint: 'phantom-1, free or zdr: what each can do, and pick one', value: { run: ['models'] } },
36
- { label: 'Choose models', hint: 'the model phantom-1 runs in each tier', value: { run: ['lineup', 'set'] } },
37
- { label: 'Keys', hint: 'list, new, limits, revoke', value: { open: 'keys' } },
38
- { label: 'Workspace', hint: 'balance, keys and latest calls together', value: { run: ['workspace'] } },
39
- { label: 'More', hint: 'setup, undo, routing, sign out, every command', value: { open: 'more' } },
40
- quit,
41
- ];
24
+ return readAccounts(env, { ...config, log: false, accounts })
25
+ .map((view) => ({ ...view, account: accounts[view.name], inFile: Object.hasOwn(config.accounts, view.name) }))
26
+ .sort((a, b) => PROVIDER_ORDER.indexOf(a.kind) - PROVIDER_ORDER.indexOf(b.kind));
27
+ }
28
+ function appState(env) {
29
+ let config = null;
30
+ let problem = null;
31
+ if (existsSync(localConfigPath(env))) {
32
+ try {
33
+ config = readLocalConfig(env);
34
+ }
35
+ catch (err) {
36
+ problem = err.message;
37
+ }
38
+ }
39
+ if (problem)
40
+ return { config, problem, accounts: [], providers: [] };
41
+ return { config, problem, accounts: readAccounts(env, config), providers: readProviders(env, config ?? STARTER) };
42
42
  }
43
- /** The menus a main-menu row opens. */
44
- function subMenu(which, s) {
45
- if (which === 'keys') {
46
- return [
47
- { label: 'See my keys', value: { run: ['keys'] } },
48
- { label: 'New key', hint: 'for a teammate, CI or another computer', value: { run: ['keys', 'create'] } },
49
- { label: 'Cap what a key can spend', value: { run: ['keys', 'set'] } },
50
- { label: 'Revoke a key', hint: 'it stops working at once; its credit stays', value: { run: ['keys', 'revoke'] } },
51
- { label: 'Rotate a key', hint: 'a new key in its place; the old one stops working', value: { run: ['keys', 'rotate'] } },
52
- ];
43
+ const caption = (p, width, text, detail = '') => [` ${p.bold(text)}${detail ? ` ${p.dim(detail)}` : ''}`, ` ${p.dim('─'.repeat(Math.max(10, Math.min(66, width - 4))))}`];
44
+ const screen = (write, env, lines) => write('\x1b[2J\x1b[H' + startHeader(env, colorOn(env, true)) + '\n' + lines.join('\n') + '\n\n');
45
+ function routingText(s, p, width) {
46
+ if (!s.config)
47
+ return fitLine(` ${s.problem ?? 'No routing set up yet.'}`, width);
48
+ const line = routingLine(s.config, s.accounts);
49
+ const at = line.lastIndexOf(' · ');
50
+ const [lead, last] = at === -1 ? ['', line] : [line.slice(0, at + 3), line.slice(at + 3)];
51
+ return fitLine(` ${lead}${last.startsWith('!') ? p.yellow(last) : last.startsWith('✓') ? p.lime(last) : last}`, width);
52
+ }
53
+ export async function runPicker(env, pick, write, runCommand, installed = onPath) {
54
+ const p = paint(env, colorOn(env, true));
55
+ try {
56
+ if (!existsSync(localConfigPath(env)) && (await runConfig(env, pick, write, runCommand)) === 130)
57
+ return 130;
58
+ for (;;) {
59
+ const s = appState(env);
60
+ const width = pick.columns ?? 80;
61
+ const agents = ROUTES_HERE.filter((a) => installed(LAUNCHERS[a].bin));
62
+ const rows = [
63
+ ...agents.map((a) => ({ label: `Start ${AGENT_NAMES[a]}`, hint: s.config ? 'routed on this computer, as above' : 'set up routing in Settings first', value: { agent: a } })),
64
+ { label: 'Settings', hint: 'Standard, Frontier and providers', value: { open: 'settings' } },
65
+ { label: 'Report', hint: 'what routing did in the last day', value: { open: 'report' } },
66
+ ];
67
+ const names = ROUTES_HERE.map((a) => AGENT_NAMES[a]).join(', ');
68
+ const none = agents.length ? [] : ['', ` ${cut(`No coding agent found on this computer. Install ${names}, then run phantom again.`, width - 2)}`];
69
+ screen(write, env, [...caption(p, width, 'ROUTING'), routingText(s, p, width), ...none]);
70
+ const choice = await choose({ ...pick, esc: 'quit' }, 'What next?', rows);
71
+ if (choice === null)
72
+ return 0;
73
+ if ('agent' in choice) {
74
+ write('\n');
75
+ return await runCommand([choice.agent]);
76
+ }
77
+ if (choice.open === 'settings') {
78
+ if ((await runConfig(env, pick, write, runCommand)) === 130)
79
+ return 130;
80
+ continue;
81
+ }
82
+ write('\n');
83
+ if ((await runCommand(['report', '--since', '1d', '--table'])) === 130)
84
+ return 130;
85
+ write('\n');
86
+ await choose({ ...pick, esc: 'back' }, 'Done', [{ label: 'Back', value: true }]);
87
+ }
53
88
  }
54
- if (which === 'commands') {
55
- return COMMANDS.filter((c) => !c.advanced).map((c) => ({ label: c.name, hint: c.summary, value: { run: [c.name] } }));
89
+ catch (err) {
90
+ if (err instanceof Cancelled)
91
+ return 130;
92
+ throw err;
56
93
  }
94
+ }
95
+ const providerName = (p, all) => (all.filter((q) => q.kind === p.kind).length > 1 ? `${PROVIDERS[p.kind]} (${shown(p.name)})` : PROVIDERS[p.kind]);
96
+ function targetText(target, s) {
97
+ const provider = s.providers.find((p) => p.name === target.account);
98
+ return `${target.model} · ${provider ? providerName(provider, s.providers) : shown(target.account)}`;
99
+ }
100
+ const standing = (p) => (p.state.ready ? `✓ ${p.state.word}` : p.inFile ? `! ${p.state.word}` : '– not connected');
101
+ const providersText = (s) => PROVIDER_ORDER.map((kind) => {
102
+ const of = s.providers.filter((p) => p.kind === kind);
103
+ return `${PROVIDERS[kind]} ${of.some((p) => p.state.ready) ? '✓' : of.some((p) => p.inFile) ? '!' : '–'}`;
104
+ }).join(' · ');
105
+ const signInRow = (signedIn, signIn) => signedIn ? { label: 'Sign out of ChatGPT', hint: 'phantom forgets the sign-in', value: { run: ['config', 'chatgpt', 'logout'] } } : { label: 'Sign in to ChatGPT', hint: 'in the browser, to use your ChatGPT plan', value: signIn };
106
+ function configRows(at, s) {
107
+ if (s.problem)
108
+ return [{ label: 'Back', hint: 'fix or delete local.json, then come back', value: { back: true } }];
109
+ const config = s.config ?? STARTER;
110
+ if (at === 'main') {
111
+ const noneConnected = !s.providers.some((p) => p.state.ready);
112
+ const tierRow = (tier) => ({
113
+ label: TIER_NAME[tier],
114
+ hint: targetText(config.tiers[tier], s) + (noneConnected ? ' · connect a provider first' : ''),
115
+ value: noneConnected ? { open: 'providers' } : { tier },
116
+ });
117
+ return [tierRow('standard'), tierRow('frontier'), { label: 'Providers', hint: providersText(s), value: { open: 'providers' } }, { label: 'Back', value: { back: true } }];
118
+ }
119
+ if (at === 'providers')
120
+ return s.providers.map((p) => ({ label: providerName(p, s.providers), hint: standing(p), value: { open: { provider: p.name } } }));
121
+ const provider = s.providers.find((p) => p.name === at.provider);
122
+ if (!provider)
123
+ return [];
124
+ const name = provider.name;
125
+ if (provider.kind === 'chatgpt-plan')
126
+ return [signInRow(provider.from !== null, provider.inFile ? { run: ['config', 'chatgpt', 'login'] } : { addPlan: name })];
57
127
  return [
58
- { label: s.setUp ? 'Set up more agents' : 'Set up my agents', hint: 'or change how they run', value: { run: ['setup'] } },
59
- ...(s.setUp ? [{ label: 'Undo setup', hint: 'put your agents back how they were', value: { run: ['setup', '--restore'] } }] : []),
60
- { label: 'Routing rules', hint: 'how model "auto" picks', value: { run: ['route'] } },
61
- { label: 'Sign out', hint: 'on this computer', value: { run: ['logout'] } },
62
- { label: 'Every command', hint: 'pick one to run', value: { open: 'commands' } },
128
+ { label: 'Save a key', hint: 'paste it; phantom keeps it, in the Keychain on a Mac', value: { run: ['config', 'key', 'set', name] } },
129
+ { label: 'Use a Keychain item', hint: 'one you already have; phantom keeps no copy', value: { keychain: name } },
130
+ ...(provider.hasKey ? [{ label: 'Remove the key', hint: 'phantom stops reading it; a Keychain item you made stays', value: { run: ['config', 'key', 'rm', name] } }] : []),
63
131
  ];
64
132
  }
65
- /**
66
- * Next steps that change or reveal something (copying a key, signing out):
67
- * the marker starts on "Back to the menu" instead, so a stray Enter is safe.
68
- */
69
- const RISKY = new Set(['keys show --copy', 'logout --all']);
70
- /** After a command's result: the next steps that fit it, as choices, so nobody types the "→" line. */
71
- export function nextSteps(ran) {
72
- const key = ran.join(' ');
73
- const steps = {
74
- balance: [['Spend', ['spend']], ['Add credit', ['fund']]],
75
- spend: [['Every key in the workspace', ['spend', '--workspace']], ['Choose models', ['lineup', 'set']]],
76
- 'spend --workspace': [['Keys', ['keys']]],
77
- fund: [['Balance', ['balance']]],
78
- workspace: [['See my keys', ['keys']], ['Spend by key', ['spend', '--workspace']]],
79
- keys: [['New key', ['keys', 'create']], ['Cap what a key can spend', ['keys', 'set']], ['Revoke a key', ['keys', 'revoke']]],
80
- models: [['Put it in my agents', ['setup']], ['Choose the model in each tier', ['lineup', 'set']]],
81
- route: [['See what a request would get', ['route', 'test']], ['Choose models', ['lineup', 'set']]],
82
- 'setup --restore': [['Sign out, and forget saved keys', ['logout', '--all']]],
83
- login: [['Set up my agents', ['setup']]],
84
- 'keys create': [['See my keys', ['keys']]],
85
- 'keys revoke': [['See my keys', ['keys']]],
86
- 'keys set': [['See my keys', ['keys']]],
87
- 'keys rotate': [['See my keys', ['keys']]],
88
- // Cursor and other editors take the key in their own settings: copy it without showing it.
89
- setup: [['Copy my key (for Cursor or another app)', ['keys', 'show', '--copy']]],
90
- };
91
- return (steps[key] ?? []).map(([label, run]) => ({ label, value: run }));
133
+ function configBody(at, s, p, width) {
134
+ if (s.problem)
135
+ return [...caption(p, width, 'SETTINGS'), ` ${cut(s.problem, width - 2)}`];
136
+ if (typeof at === 'object') {
137
+ const provider = s.providers.find((q) => q.name === at.provider);
138
+ const body = provider?.inFile ? accountsTable([provider], p, width) : [` ${provider ? PROVIDERS[provider.kind] : shown(at.provider)} is not connected yet.`];
139
+ return [...caption(p, width, 'PROVIDER'), ...body];
140
+ }
141
+ return [...caption(p, width, 'PROVIDERS', s.config ? '' : 'not saved yet'), ...accountsTable(s.accounts, p, width)];
142
+ }
143
+ const configTitle = (at, s) => {
144
+ if (at === 'main')
145
+ return 'Settings';
146
+ if (at === 'providers')
147
+ return 'Which provider?';
148
+ const provider = s.providers.find((p) => p.name === at.provider);
149
+ return `What should ${provider ? providerName(provider, s.providers) : shown(at.provider)} do?`;
150
+ };
151
+ async function keychainCommand(pick, account) {
152
+ const service = await askText({ ...pick, esc: 'back' }, "The Keychain item's service name?", { placeholder: 'zai-api-key' });
153
+ return service === null ? null : ['config', 'key', 'use-keychain', account, '--service', service];
154
+ }
155
+ const flagValue = (target) => (target ? `${target.account}:${target.model}` : 'none');
156
+ async function tierCommand(env, pick, write, tier, s) {
157
+ const connected = s.providers.filter((p) => p.state.ready);
158
+ write(" Reading each provider's models…\n");
159
+ const lists = await Promise.all(connected.map((p) => listModels(p.name, p.account, env)));
160
+ const models = [];
161
+ lists.forEach((list, k) => {
162
+ const name = providerName(connected[k], s.providers);
163
+ if ('error' in list)
164
+ write(` Could not load ${name}'s models (${list.error}). Type ${shown(list.account)}:<model> instead.\n`);
165
+ else
166
+ models.push(...list.models.filter((m) => !m.hidden).map((m) => ({ label: m.id, hint: name, value: `${list.account}:${m.id}` })));
167
+ });
168
+ const typed = (text) => connected.some((p) => text.startsWith(`${p.name}:`) && text.length > p.name.length + 1);
169
+ const ask = (question, rows, current) => chooseOrType({ ...pick, esc: 'back' }, question, rows, {
170
+ start: Math.max(0, rows.findIndex((row) => row.value === current)),
171
+ placeholder: 'type to filter, or account:model',
172
+ check: (text) => (rows.some((row) => row.value === text) || typed(text) ? null : `Type account:model with one of ${connected.map((p) => shown(p.name)).join(', ')}, or press esc.`),
173
+ });
174
+ const entry = (s.config ?? STARTER).tiers[tier];
175
+ for (;;) {
176
+ const fallbackRow = { label: 'Fallback', hint: entry.fallback ? targetText(entry.fallback, s) : 'none', value: 'fallback' };
177
+ const model = await ask(`${TIER_NAME[tier]} model`, [...models, fallbackRow], flagValue(entry));
178
+ if (model === null)
179
+ return null;
180
+ if (model !== 'fallback')
181
+ return model === flagValue(entry) ? null : ['config', `--${tier}`, model];
182
+ const fallback = await ask(`${TIER_NAME[tier]} fallback`, [{ label: 'No fallback', value: 'none' }, ...models], flagValue(entry.fallback));
183
+ if (fallback === null)
184
+ continue;
185
+ return fallback === flagValue(entry.fallback) ? null : ['config', `--${tier}-fallback`, fallback];
186
+ }
92
187
  }
93
- /**
94
- * Runs the app until Quit, Esc on the main menu, or Ctrl+C. `runCommand` runs
95
- * one command the way `phantom <args>` would and returns its exit code; the app
96
- * passes it `fromMenu`, so a command's first Esc comes back here.
97
- */
98
- export async function runApp(env, pick, write, runCommand, installed = onPath) {
99
- const color = colorOn(env, true);
100
- const p = paint(env, color);
101
- const state = () => ({ signedIn: Boolean(resolveApiKey(env)), setUp: isSetUp(env), installed });
102
- // The "→ type this next" lines would repeat the choices offered after each result, so they're hidden here.
103
- const hintsWere = hideHints(true);
188
+ export async function runConfig(env, pick, write, runCommand) {
189
+ const p = paint(env, colorOn(env, true));
190
+ const open = ['main'];
191
+ const backToSettings = async () => {
192
+ write('\n');
193
+ await choose({ ...pick, esc: 'back' }, 'Done', [{ label: 'Back to settings', value: true }]);
194
+ open.splice(1);
195
+ };
104
196
  try {
105
197
  for (;;) {
106
- // A clean screen for each visit to the menu: a title, then where you are.
107
- write('\x1b[2J\x1b[H' + startHeader(env, color) + '\n');
108
- const s = state();
109
- write(` ${p.dim(s.signedIn ? (s.setUp ? 'Signed in · your agents use Phantom AI' : 'Signed in · no agent set up yet') : 'Not signed in yet')}\n`);
110
- // Before signing in, the one line that says what free means, whole, since it is why most people came.
111
- write(s.signedIn ? '\n' : ` ${p.lime('Free to start:')} ${FREE_LINE}.\n\n`);
112
- let action = await choose({ ...pick, esc: 'quit' }, 'What would you like to do?', mainMenu(s));
113
- if (action === null)
114
- return 0;
115
- // A row that opens another menu; Esc there comes back to the main menu.
116
- while (action && 'open' in action) {
117
- const sub = subMenu(action.open, s);
118
- action = await choose({ ...pick, esc: 'back' }, action.open === 'keys' ? 'Keys' : action.open === 'commands' ? 'Which command?' : 'More', sub);
119
- }
120
- if (!action)
198
+ const at = open[open.length - 1];
199
+ const s = appState(env);
200
+ const width = pick.columns ?? 80;
201
+ screen(write, env, configBody(at, s, p, width));
202
+ const action = await choose({ ...pick, esc: 'back' }, configTitle(at, s), configRows(at, s));
203
+ if (action === null) {
204
+ if (open.length === 1)
205
+ return 0;
206
+ open.pop();
121
207
  continue;
122
- if (!action.run.length)
208
+ }
209
+ if ('back' in action)
123
210
  return 0;
124
- let ran = action.run;
125
- // Run it, then offer what fits next; Back to the menu, or Quit, end the chain.
126
- while (ran) {
211
+ if ('open' in action) {
212
+ open.push(action.open);
213
+ continue;
214
+ }
215
+ if ('addPlan' in action) {
127
216
  try {
128
- // Ctrl+C inside a command (exit 130) stops the app too, as it would anywhere else.
129
- if ((await runCommand(ran)) === 130)
130
- return 130;
217
+ const config = savedOrStarter(env);
218
+ writeLocalConfig(env, { ...config, accounts: { ...config.accounts, [action.addPlan]: { kind: 'chatgpt-plan' } } });
131
219
  }
132
220
  catch (err) {
133
- if (err instanceof Cancelled)
134
- return 130;
135
- if (!(err instanceof BackToMenu))
136
- throw err;
137
- break;
221
+ handleError(err, write, { human: true, env });
222
+ await backToSettings();
223
+ continue;
138
224
  }
139
- write('\n');
140
- const steps = nextSteps(ran);
141
- // A risky step first in the list would run on a stray Enter, so the marker starts on Back then.
142
- const safe = steps.some((s) => RISKY.has(s.value.join(' '))) ? steps.length : 0;
143
- const next = await choose({ ...pick, esc: 'back' }, 'What next?', [
144
- ...steps,
145
- { label: 'Back to the menu', value: ['menu'] },
146
- { label: 'Quit', value: [] },
147
- ], safe);
148
- if (next === null || next[0] === 'menu')
149
- ran = null;
150
- else if (!next.length)
151
- return 0;
152
- else
153
- ran = next;
154
225
  }
226
+ const argv = 'keychain' in action ? await keychainCommand(pick, action.keychain) : 'tier' in action ? await tierCommand(env, pick, write, action.tier, s) : 'addPlan' in action ? ['config', 'chatgpt', 'login'] : action.run;
227
+ if (!argv)
228
+ continue;
229
+ let code;
230
+ try {
231
+ code = await runCommand(argv);
232
+ if (code === 130)
233
+ return 130;
234
+ }
235
+ catch (err) {
236
+ if (!(err instanceof BackToMenu))
237
+ throw err;
238
+ continue;
239
+ }
240
+ if ('tier' in action && code === 0)
241
+ continue;
242
+ await backToSettings();
155
243
  }
156
244
  }
157
245
  catch (err) {
@@ -159,7 +247,4 @@ export async function runApp(env, pick, write, runCommand, installed = onPath) {
159
247
  return 130;
160
248
  throw err;
161
249
  }
162
- finally {
163
- hideHints(hintsWere);
164
- }
165
250
  }
@@ -1,23 +1,8 @@
1
1
  import type { CommandInput } from '../core/helpers.mts';
2
- /** A command's handler, help text, and conditions for running without a key. */
3
2
  export type CommandDefinition = {
4
3
  name: string;
5
4
  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
5
  summary: string;
6
+ help: string;
14
7
  };
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
8
  export declare const COMMANDS: readonly CommandDefinition[];