@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
@@ -1,16 +0,0 @@
1
- import { type CommandInput } from '../core/helpers.mts';
2
- /** `--table` output for `balance`. */
3
- export declare function tableBalance(d: unknown): string;
4
- /** `--table` output for `key list`. */
5
- export declare function tableKeys(d: unknown): string;
6
- /** `phantom balance`: the key's credit and expiry. Run by `run()`. */
7
- export declare function balanceCommand(input: CommandInput): Promise<number>;
8
- /** `phantom key list|save|show|rm`: keys saved by name. Run by `run()`. */
9
- export declare function keyCommand({ argv, env, io, subcommand, flags, table, baseUrl }: CommandInput): Promise<number>;
10
- /** `phantom login`: checks a key and saves it as the login key. Run by `run()`. */
11
- export declare function loginCommand({ env, io, subcommand, table, baseUrl }: CommandInput): Promise<number>;
12
- /**
13
- * `phantom logout`: forgets the login key. `forgotWorkspace` says whether the
14
- * workspace sign-in was forgotten too, so the screen doesn't say nothing changed. Run by `run()`.
15
- */
16
- export declare function logoutCommand({ env, io, table, flags }: CommandInput, forgotWorkspace?: boolean): Promise<number>;
@@ -1,143 +0,0 @@
1
- import { unknownSub } from "../cli/start.mjs";
2
- import { createInterface } from 'node:readline/promises';
3
- import { spawnSync } from 'node:child_process';
4
- import { die, NO_KEY } from "../core/errors.mjs";
5
- import { getBalance } from "../core/request.mjs";
6
- import { out, showsScreen } from "../core/helpers.mjs";
7
- import { colorOn, paint } from "../core/style.mjs";
8
- import { balanceScreen, keySavedScreen, logoutScreen, savedKeysScreen } from "../cli/screens.mjs";
9
- import { resolveApiKey, readNamedKey, saveNamedKey, removeNamedKey, listNamedKeys, saveApiKey, removeApiKey } from "./saved.mjs";
10
- /** `--table` output for `balance`. */
11
- export function tableBalance(d) {
12
- const b = d;
13
- return [
14
- `active ${b.active}`,
15
- `kind ${b.kind}`,
16
- `balance $${b.credit_balance_usd.toFixed(4)}`,
17
- `spent $${b.credit_spent_usd.toFixed(4)}`,
18
- `expires_at ${b.expires_at}`,
19
- ].join('\n');
20
- }
21
- /** `--table` output for `key list`. */
22
- export function tableKeys(d) {
23
- const { keys } = d;
24
- if (keys.length === 0)
25
- return 'no saved keys';
26
- return keys
27
- .map((k) => {
28
- const bal = k.credit_balance_usd === undefined ? '' : ` $${k.credit_balance_usd.toFixed(4)}${k.active === false ? ' inactive' : ''}`;
29
- return `${k.name.padEnd(16)}${k.id}${bal}`;
30
- })
31
- .join('\n');
32
- }
33
- /** `phantom balance`: the key's credit and expiry. Run by `run()`. */
34
- export async function balanceCommand(input) {
35
- const { io, apiKey, baseUrl, env } = input;
36
- const result = await getBalance(apiKey, baseUrl);
37
- // The API answers 200 with active: false for a key that was revoked, rotated away or has expired. Its credit is not spendable.
38
- if (!result.active)
39
- die('This key is revoked or has expired. Make a new key with phantom keys create --save <name>, or run phantom logout and phantom login to start again.', 'key_revoked', 2);
40
- out(result, showsScreen(input), (d) => balanceScreen(d, { env, color: colorOn(env, io.stdoutIsTTY) }), io.stdout);
41
- return 0;
42
- }
43
- /** `phantom key list|save|show|rm`: keys saved by name. Run by `run()`. */
44
- export async function keyCommand({ argv, env, io, subcommand, flags, table, baseUrl }) {
45
- const name = argv[2] && !argv[2].startsWith('--') ? argv[2] : undefined;
46
- if (!subcommand || subcommand === 'list') {
47
- const list = listNamedKeys(env);
48
- if (flags['balance']) {
49
- const withBalance = await Promise.all(list.keys.map(async (k) => {
50
- try {
51
- const b = await getBalance(readNamedKey(env, k.name), baseUrl);
52
- return { ...k, active: b.active, credit_balance_usd: b.credit_balance_usd, expires_at: b.expires_at };
53
- }
54
- catch {
55
- return { ...k, active: false };
56
- }
57
- }));
58
- out({ keys: withBalance }, table, (d) => savedKeysScreen(d.keys, { env, color: colorOn(env, io.stdoutIsTTY) }), io.stdout);
59
- }
60
- else {
61
- out(list, table, (d) => savedKeysScreen(d.keys, { env, color: colorOn(env, io.stdoutIsTTY) }), io.stdout);
62
- }
63
- }
64
- else if (subcommand === 'save') {
65
- if (!name)
66
- die('key save requires a name: phantom key save <name> [key]');
67
- let key = argv[3] && !argv[3].startsWith('--') ? argv[3] : undefined;
68
- if (!key) {
69
- const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: false });
70
- if (io.isTTY)
71
- io.stderr('Paste the key: ');
72
- key = (await rl[Symbol.asyncIterator]().next()).value ?? '';
73
- rl.close();
74
- }
75
- key = (key ?? '').trim();
76
- if (!key.startsWith('sk-phantom-'))
77
- die('That is not a Phantom AI key. Keys start with sk-phantom-');
78
- await getBalance(key, baseUrl);
79
- out(saveNamedKey(env, name, key), table, (d) => keySavedScreen(d.name, { env, color: colorOn(env, io.stdoutIsTTY) }), io.stdout);
80
- }
81
- else if (subcommand === 'show') {
82
- // Raw, for PHANTOM_API_KEY=$(phantom key show <name>). With no name, the
83
- // key phantom itself would use, which is what Claude Code's apiKeyHelper runs.
84
- const key = name ? readNamedKey(env, name) : resolveApiKey(env);
85
- if (!key)
86
- die(NO_KEY);
87
- // --copy: to the clipboard instead of the screen, for pasting into an app's settings (Cursor's API key box).
88
- if (flags['copy']) {
89
- const copied = process.platform === 'darwin' ? spawnSync('pbcopy', { input: key }).status === 0 : false;
90
- if (!copied)
91
- die('Copying needs pbcopy, which is on every Mac. Elsewhere: phantom keys show | your clipboard tool.', 'copy_unavailable');
92
- io.stderr(` ${paint(env, colorOn(env, io.isTTY)).lime('✓')} Copied your key. Paste it where it's asked for; it works like a password.\n`);
93
- return 0;
94
- }
95
- io.stdout(key + '\n');
96
- }
97
- else if (subcommand === 'rm') {
98
- if (!name)
99
- die('key rm requires a name');
100
- out(removeNamedKey(env, name), table, (d) => `removed ${d.removed}`, io.stdout);
101
- }
102
- else {
103
- die(unknownSub('key', String(subcommand), ['list', 'save', 'show', 'rm']), 'key_usage');
104
- }
105
- return 0;
106
- }
107
- /** `phantom login`: checks a key and saves it as the login key. Run by `run()`. */
108
- export async function loginCommand({ env, io, subcommand, table, baseUrl }) {
109
- let key = subcommand;
110
- if (!key) {
111
- // Prompt rather than take the key as an argument, so it stays out of
112
- // shell history.
113
- const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: false });
114
- if (io.isTTY)
115
- io.stderr('Paste your Phantom AI key: ');
116
- key = (await rl[Symbol.asyncIterator]().next()).value ?? '';
117
- rl.close();
118
- }
119
- key = (key ?? '').trim();
120
- if (!key.startsWith('sk-phantom-'))
121
- die('That is not a Phantom AI key. Keys start with sk-phantom-');
122
- // Check the key works before saving it.
123
- const balance = await getBalance(key, baseUrl);
124
- const saved = saveApiKey(env, key);
125
- out({ ...saved, ...balance }, table, (d) => `\n ${paint(env, colorOn(env, io.stdoutIsTTY)).lime('✓')} Key saved.\n${balanceScreen(d, { env, color: colorOn(env, io.stdoutIsTTY) })}`, io.stdout);
126
- return 0;
127
- }
128
- /**
129
- * `phantom logout`: forgets the login key. `forgotWorkspace` says whether the
130
- * workspace sign-in was forgotten too, so the screen doesn't say nothing changed. Run by `run()`.
131
- */
132
- export async function logoutCommand({ env, io, table, flags }, forgotWorkspace = false) {
133
- const result = removeApiKey(env);
134
- // --all also forgets the keys saved by name; without it they stay, and the screen says so.
135
- const named = listNamedKeys(env).keys.map((k) => k.name);
136
- if (flags['all'])
137
- for (const name of named)
138
- removeNamedKey(env, name);
139
- const kept = flags['all'] ? [] : named;
140
- const removedNamed = flags['all'] ? named : [];
141
- out({ ...result, removed_named: removedNamed, kept_named: kept }, table, (d) => logoutScreen(d.removed || forgotWorkspace || removedNamed.length > 0, { env, color: colorOn(env, io.stdoutIsTTY), kept, removedNamed }), io.stdout);
142
- return 0;
143
- }
@@ -1,96 +0,0 @@
1
- import { type Env } from '../core/state.mts';
2
- export declare function keyPath(env: Env): string;
3
- export declare function namedKeyPath(env: Env, name: string): string;
4
- /** A key's whole SHA-256 hash: the id the workspace routes name a key by (`hashKey` in web/lib/crypto.ts). */
5
- export declare function keyHash(key: string): string;
6
- /** A key's id: the start of its SHA-256 hash, safe to print. */
7
- export declare function keyId(key: string): string;
8
- /** Where the key a command runs as comes from. */
9
- export type KeySource = {
10
- /** PHANTOM_API_KEY. */
11
- from: 'env';
12
- } | {
13
- /** A key saved by name, chosen with PHANTOM_KEY_NAME. */
14
- from: 'named';
15
- /** The saved key's name. */
16
- name: string;
17
- } | {
18
- /** The default key, saved by `phantom keys create` or `phantom keys save default`. */
19
- from: 'login';
20
- } | {
21
- /** No key at all. */
22
- from: 'none';
23
- };
24
- /**
25
- * Which key a command runs as: the saved key named by PHANTOM_KEY_NAME, then
26
- * PHANTOM_API_KEY, then the default key. It only looks; {@link resolveApiKey}
27
- * reads the key.
28
- */
29
- export declare function keySource(env: Env): KeySource;
30
- /** The key a command runs as, chosen by {@link keySource}. An empty string when there is none. */
31
- export declare function resolveApiKey(env: Env): string;
32
- /**
33
- * A key saved by name.
34
- * @throws {@link CliError} when no key has that name, or the name is not valid.
35
- */
36
- export declare function readNamedKey(env: Env, name: string): string;
37
- /**
38
- * Saves a key by name, in the Keychain or a mode 600 file (see {@link keychain}).
39
- * Refuses a name already in use unless `replace` is set, and anything that
40
- * doesn't start with `sk-phantom-`.
41
- * @returns The name, and the key's {@link keyId}.
42
- */
43
- export declare function saveNamedKey(env: Env, name: string, key: string, opts?: {
44
- replace?: boolean;
45
- }): {
46
- /** The name the key was saved under. */
47
- name: string;
48
- /** The key's id, as {@link keyId} computes it. */
49
- id: string;
50
- };
51
- /** Forgets a saved key. The key itself keeps working. */
52
- export declare function removeNamedKey(env: Env, name: string): {
53
- /** The name asked for. */
54
- name: string;
55
- /** False when no key was saved under that name. */
56
- removed: boolean;
57
- };
58
- /** Every key saved by name, sorted, with its id. Never returns the keys. */
59
- export declare function listNamedKeys(env: Env): {
60
- /** One entry per saved key. */
61
- keys: Array<{
62
- /** The saved name. */
63
- name: string;
64
- /** The key's id, as {@link keyId} computes it. */
65
- id: string;
66
- }>;
67
- };
68
- /**
69
- * What to say when a command needs a key and has none. Keys saved only by
70
- * name (`phantom login --save ci`) don't run unless PHANTOM_KEY_NAME names one,
71
- * so the message lists them instead of saying there is no key at all.
72
- */
73
- export declare function noKeyMessage(env: Env): string;
74
- /** The default key, the one `phantom keys create` saves when no name is given, or null when none is saved. */
75
- export declare function defaultKey(env: Env): string | null;
76
- /** Saves the default key, the one used when neither PHANTOM_KEY_NAME nor PHANTOM_API_KEY is set. */
77
- export declare function saveApiKey(env: Env, key: string): {
78
- /** The path of the file that holds the key or its Keychain pointer. */
79
- saved: string;
80
- };
81
- /** Forgets the default key. */
82
- export declare function removeApiKey(env: Env): {
83
- /** False when no default key was saved. */
84
- removed: boolean;
85
- };
86
- /**
87
- * Where a new key will be saved: the name in `save` (`--save`), or `default`.
88
- * Run it before anything is asked for: it refuses a name already in use and,
89
- * with no name, a default key that is saved already.
90
- * @throws {@link CliError} `key_exists`, or `cli_error` for `--save` with no name.
91
- */
92
- export declare function saveTarget(env: Env, save: string | true | undefined): string;
93
- /** Saves a key under a {@link saveTarget}: `default`, or a name. */
94
- export declare function saveKeyAs(env: Env, target: string, key: string): void;
95
- /** Forgets a key saved under a {@link saveTarget}. */
96
- export declare function forgetKeyAs(env: Env, target: string): void;
@@ -1,169 +0,0 @@
1
- import path from 'node:path';
2
- import { createHash } from 'node:crypto';
3
- import { existsSync, readdirSync } from 'node:fs';
4
- import { die, NO_KEY } from "../core/errors.mjs";
5
- import { stateDir } from "../core/state.mjs";
6
- import { writeSecret, readSecret, removeSecret } from "../core/secrets.mjs";
7
- /**
8
- * `login` saves the key to a file only the user can read, so an agent that
9
- * reaches the CLI through bash (pi has no MCP) needs no environment set up.
10
- *
11
- * Other keys can be saved by name in `keys/`, one file each, so an agent can
12
- * find them again in a later session. The file holds nothing but the key.
13
- * `phantom keys create` also keeps a record with no secret in it beside each key
14
- * it makes (see {@link SessionRecord}).
15
- *
16
- * Which key a command runs as: the saved key named by PHANTOM_KEY_NAME, then
17
- * PHANTOM_API_KEY, then the default key.
18
- */
19
- const KEY_NAME = /^[a-z0-9][a-z0-9_-]{0,31}$/i;
20
- export function keyPath(env) {
21
- return path.join(stateDir(env), 'key');
22
- }
23
- export function namedKeyPath(env, name) {
24
- if (!KEY_NAME.test(name))
25
- die(`Key names use letters, numbers, - and _ (up to 32): ${name}`);
26
- return path.join(stateDir(env), 'keys', name);
27
- }
28
- /** A key's whole SHA-256 hash: the id the workspace routes name a key by (`hashKey` in web/lib/crypto.ts). */
29
- export function keyHash(key) {
30
- return createHash('sha256').update(key.trim()).digest('hex');
31
- }
32
- /** A key's id: the start of its SHA-256 hash, safe to print. */
33
- export function keyId(key) {
34
- return keyHash(key).slice(0, 12);
35
- }
36
- /**
37
- * Which key a command runs as: the saved key named by PHANTOM_KEY_NAME, then
38
- * PHANTOM_API_KEY, then the default key. It only looks; {@link resolveApiKey}
39
- * reads the key.
40
- */
41
- export function keySource(env) {
42
- // A named key is the more specific choice, so it wins. A subagent started
43
- // with PHANTOM_KEY_NAME=<name> from a shell that also exports
44
- // PHANTOM_API_KEY must run as the named key, not quietly spend the other.
45
- if (env.PHANTOM_KEY_NAME)
46
- return { from: 'named', name: env.PHANTOM_KEY_NAME };
47
- if (env.PHANTOM_API_KEY)
48
- return { from: 'env' };
49
- return existsSync(keyPath(env)) ? { from: 'login' } : { from: 'none' };
50
- }
51
- /** The key a command runs as, chosen by {@link keySource}. An empty string when there is none. */
52
- export function resolveApiKey(env) {
53
- const src = keySource(env);
54
- if (src.from === 'env')
55
- return env.PHANTOM_API_KEY ?? '';
56
- if (src.from === 'named')
57
- return readNamedKey(env, src.name);
58
- if (src.from === 'login')
59
- return readSecret(env, keyPath(env)).trim();
60
- return '';
61
- }
62
- function writeKeyFile(env, file, key) {
63
- const k = key.trim();
64
- if (!k.startsWith('sk-phantom-'))
65
- die('That is not a Phantom AI key. Keys start with sk-phantom-');
66
- writeSecret(env, file, k + '\n');
67
- }
68
- /**
69
- * A key saved by name.
70
- * @throws {@link CliError} when no key has that name, or the name is not valid.
71
- */
72
- export function readNamedKey(env, name) {
73
- const file = namedKeyPath(env, name);
74
- if (!existsSync(file))
75
- die(`No saved key named ${name}. See the saved keys with phantom keys saved.`);
76
- return readSecret(env, file).trim();
77
- }
78
- /**
79
- * Saves a key by name, in the Keychain or a mode 600 file (see {@link keychain}).
80
- * Refuses a name already in use unless `replace` is set, and anything that
81
- * doesn't start with `sk-phantom-`.
82
- * @returns The name, and the key's {@link keyId}.
83
- */
84
- export function saveNamedKey(env, name, key, opts = {}) {
85
- const file = namedKeyPath(env, name);
86
- if (existsSync(file) && !opts.replace)
87
- die(`A key named ${name} is already saved. Pick another name, or remove it first.`);
88
- writeKeyFile(env, file, key);
89
- return { name, id: keyId(key) };
90
- }
91
- /** Forgets a saved key. The key itself keeps working. */
92
- export function removeNamedKey(env, name) {
93
- const file = namedKeyPath(env, name);
94
- if (!existsSync(file))
95
- return { name, removed: false };
96
- removeSecret(file);
97
- return { name, removed: true };
98
- }
99
- /** Every key saved by name, sorted, with its id. Never returns the keys. */
100
- export function listNamedKeys(env) {
101
- const dir = path.join(stateDir(env), 'keys');
102
- if (!existsSync(dir))
103
- return { keys: [] };
104
- const keys = readdirSync(dir)
105
- .filter((n) => KEY_NAME.test(n))
106
- .sort()
107
- .map((name) => ({ name, id: keyId(readSecret(env, path.join(dir, name))) }));
108
- return { keys };
109
- }
110
- /**
111
- * What to say when a command needs a key and has none. Keys saved only by
112
- * name (`phantom login --save ci`) don't run unless PHANTOM_KEY_NAME names one,
113
- * so the message lists them instead of saying there is no key at all.
114
- */
115
- export function noKeyMessage(env) {
116
- const dir = path.join(stateDir(env), 'keys');
117
- const names = existsSync(dir) ? readdirSync(dir).filter((n) => KEY_NAME.test(n)).sort() : [];
118
- if (!names.length)
119
- return NO_KEY;
120
- return `No default Phantom key. Keys saved by name: ${names.join(', ')}. Run as one with PHANTOM_KEY_NAME=${names[0]}, or run phantom login to sign in.`;
121
- }
122
- /** The default key, the one `phantom keys create` saves when no name is given, or null when none is saved. */
123
- export function defaultKey(env) {
124
- return existsSync(keyPath(env)) ? readSecret(env, keyPath(env)).trim() : null;
125
- }
126
- /** Saves the default key, the one used when neither PHANTOM_KEY_NAME nor PHANTOM_API_KEY is set. */
127
- export function saveApiKey(env, key) {
128
- writeKeyFile(env, keyPath(env), key);
129
- return { saved: keyPath(env) };
130
- }
131
- /** Forgets the default key. */
132
- export function removeApiKey(env) {
133
- const p = keyPath(env);
134
- if (!existsSync(p))
135
- return { removed: false };
136
- removeSecret(p);
137
- return { removed: true };
138
- }
139
- /**
140
- * Where a new key will be saved: the name in `save` (`--save`), or `default`.
141
- * Run it before anything is asked for: it refuses a name already in use and,
142
- * with no name, a default key that is saved already.
143
- * @throws {@link CliError} `key_exists`, or `cli_error` for `--save` with no name.
144
- */
145
- export function saveTarget(env, save) {
146
- if (save === true)
147
- die('--save requires a name for the key');
148
- if (typeof save === 'string' && existsSync(namedKeyPath(env, save))) {
149
- die(`A key named ${save} is already saved. Pick another name, or remove it first.`, 'key_exists');
150
- }
151
- if (save === undefined && existsSync(keyPath(env))) {
152
- die('A default key is already saved. Name the new key with --save <name>.', 'key_exists');
153
- }
154
- return save ?? 'default';
155
- }
156
- /** Saves a key under a {@link saveTarget}: `default`, or a name. */
157
- export function saveKeyAs(env, target, key) {
158
- if (target === 'default')
159
- saveApiKey(env, key);
160
- else
161
- saveNamedKey(env, target, key);
162
- }
163
- /** Forgets a key saved under a {@link saveTarget}. */
164
- export function forgetKeyAs(env, target) {
165
- if (target === 'default')
166
- removeApiKey(env);
167
- else
168
- removeNamedKey(env, target);
169
- }
@@ -1,7 +0,0 @@
1
- import { type Env } from '../core/state.mts';
2
- /** The model you picked with `phantom models`, or undefined when you never picked one. */
3
- export declare function savedModel(env: Env): string | undefined;
4
- /** Saves the model your agents start on. */
5
- export declare function saveModel(env: Env, id: string): void;
6
- /** The model agents start on: the one you picked, or phantom-1. */
7
- export declare function startModel(env: Env): string;
@@ -1,27 +0,0 @@
1
- import path from 'node:path';
2
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { stateDir } from "../core/state.mjs";
4
- import { SETUP_MODEL } from "../setup/shared.mjs";
5
- // The model you picked with `phantom models`. Setup writes it into each
6
- // agent's settings, and `phantom claude`, `phantom codex` and `phantom pi`
7
- // start on it. It lives in one plain file, `model`, in the state folder.
8
- /** The file that holds the model you picked. */
9
- const choiceFile = (env) => path.join(stateDir(env), 'model');
10
- /** The model you picked with `phantom models`, or undefined when you never picked one. */
11
- export function savedModel(env) {
12
- try {
13
- return readFileSync(choiceFile(env), 'utf-8').trim() || undefined;
14
- }
15
- catch {
16
- return undefined;
17
- }
18
- }
19
- /** Saves the model your agents start on. */
20
- export function saveModel(env, id) {
21
- mkdirSync(stateDir(env), { recursive: true, mode: 0o700 });
22
- writeFileSync(choiceFile(env), `${id}\n`);
23
- }
24
- /** The model agents start on: the one you picked, or phantom-1. */
25
- export function startModel(env) {
26
- return savedModel(env) ?? SETUP_MODEL;
27
- }
@@ -1,8 +0,0 @@
1
- import { type CommandInput } from '../core/helpers.mts';
2
- /**
3
- * `phantom models`: phantom-1, phantom-1:free and phantom-1:private side by side,
4
- * with the jobs each can do and the model behind each job. At a terminal you
5
- * pick one, and your agents start on it (`./choice.mts`).
6
- * `phantom models use <id>` picks without the menu.
7
- */
8
- export declare function modelsCommand(input: CommandInput): Promise<number>;
@@ -1,66 +0,0 @@
1
- import { die } from "../core/errors.mjs";
2
- import { out, pickIo, showsScreen } from "../core/helpers.mjs";
3
- import { choose } from "../core/pick.mjs";
4
- import { colorOn, paint } from "../core/style.mjs";
5
- import { hideHints, modelsScreen } from "../cli/screens.mjs";
6
- import { unknownSub } from "../cli/start.mjs";
7
- import { isSetUp } from "../setup/apply.mjs";
8
- import { saveModel, startModel } from "./choice.mjs";
9
- import { getModels } from "./list.mjs";
10
- /**
11
- * `phantom models`: phantom-1, phantom-1:free and phantom-1:private side by side,
12
- * with the jobs each can do and the model behind each job. At a terminal you
13
- * pick one, and your agents start on it (`./choice.mts`).
14
- * `phantom models use <id>` picks without the menu.
15
- */
16
- export async function modelsCommand(input) {
17
- const { io, env, subcommand, argv, baseUrl, apiKey } = input;
18
- const table = showsScreen(input);
19
- const style = { env, color: colorOn(env, io.stdoutIsTTY), columns: io.columns };
20
- const models = await getModels(baseUrl, apiKey);
21
- const ids = models.map((m) => m.id);
22
- if (subcommand === 'use') {
23
- const id = argv[2] && !argv[2].startsWith('--') ? argv[2] : undefined;
24
- if (!id || !ids.includes(id))
25
- die(`models use needs one of: ${ids.join(', ')}`, 'models_usage');
26
- saveModel(env, id);
27
- out({ using: id }, table, () => picked(input, id), io.stdout);
28
- return 0;
29
- }
30
- if (subcommand)
31
- die(unknownSub('models', subcommand, ['use']), 'models_usage');
32
- const view = { models, using: startModel(env) };
33
- const pick = pickIo(input);
34
- if (!pick) {
35
- out(view, table, (d) => modelsScreen(d, style), io.stdout);
36
- return 0;
37
- }
38
- // At a terminal: the table, then a picker, instead of a command to type.
39
- const hintsWere = hideHints(true);
40
- let id;
41
- try {
42
- io.stdout(modelsScreen(view, style) + '\n\n');
43
- const choices = models.map((m) => ({ label: m.id, hint: m.id === view.using ? 'what they use now' : m.name, value: m.id }));
44
- id = await choose({ ...pick, esc: 'back' }, 'Which one should your agents use?', choices, Math.max(0, ids.indexOf(view.using)));
45
- }
46
- finally {
47
- hideHints(hintsWere);
48
- }
49
- if (id === null)
50
- return 0;
51
- if (id === view.using) {
52
- io.stdout(`\n Your agents already use ${id}.\n`);
53
- return 0;
54
- }
55
- saveModel(env, id);
56
- io.stdout(`\n${picked(input, id)}\n`);
57
- return 0;
58
- }
59
- /** The lines after a pick: what changed, and how to put it in agents set up already. */
60
- function picked(input, id) {
61
- const p = paint(input.env, colorOn(input.env, input.io.stdoutIsTTY));
62
- const lines = [` ${p.lime('✓')} Your agents start on ${id} from now on.`];
63
- if (isSetUp(input.env))
64
- lines.push(` ${p.dim('Agents set up already keep their model until you run')} ${p.cyan('phantom setup')}${p.dim('.')}`);
65
- return lines.join('\n');
66
- }
@@ -1,39 +0,0 @@
1
- /** Each job a model can do, with its name on screen, in the order the table lists them. */
2
- export declare const JOBS: readonly [readonly ["chat", "Chat"], readonly ["vision", "Images in"], readonly ["embedding", "Embeddings"], readonly ["rerank", "Rerank"], readonly ["image", "Make images"], readonly ["video", "Make video"], readonly ["speech", "Text to speech"], readonly ["transcription", "Speech to text"]];
3
- /** One of {@link JOBS}. */
4
- export type Job = (typeof JOBS)[number][0];
5
- /** One chat model a Phantom model picks between. */
6
- export type ChatModel = {
7
- /** Model id. */
8
- id: string;
9
- /** standard, frontier or free (phantom-1:free's models). */
10
- tier: string;
11
- /** True when it costs $0. */
12
- free: boolean;
13
- };
14
- /** One of Phantom's own models, as `phantom models` shows it. */
15
- export type PhantomModel = {
16
- /** The name an agent sends, such as phantom-1:private. */
17
- id: string;
18
- /** Display name. */
19
- name: string;
20
- /** What it does, from the server. */
21
- description: string;
22
- /** The chat models it picks between, in order. */
23
- chat: ChatModel[];
24
- /** The model that runs each job other than chat. Images in can run on the chat models, so it may be missing here and still be in `can`. */
25
- jobs: Partial<Record<Job, string>>;
26
- /** Every job it can do. */
27
- can: Job[];
28
- };
29
- /** What `phantom models` prints: every model, and the one your agents start on. */
30
- export type ModelsView = {
31
- models: PhantomModel[];
32
- using: string;
33
- };
34
- /**
35
- * Phantom's own models from the server. /v1/routers names each one's chat
36
- * models and the model behind every other job; /v1/models says whether it
37
- * takes images. Neither needs a key.
38
- */
39
- export declare function getModels(baseUrl?: string, apiKey?: string): Promise<PhantomModel[]>;
@@ -1,39 +0,0 @@
1
- import { request } from "../core/request.mjs";
2
- // Phantom's own models (phantom-1, phantom-1:free, phantom-1:private) and what
3
- // each can do, read from the server, so a model Phantom adds or changes shows
4
- // up with no new CLI release. `phantom models` shows them.
5
- /** Each job a model can do, with its name on screen, in the order the table lists them. */
6
- export const JOBS = [
7
- ['chat', 'Chat'],
8
- ['vision', 'Images in'],
9
- ['embedding', 'Embeddings'],
10
- ['rerank', 'Rerank'],
11
- ['image', 'Make images'],
12
- ['video', 'Make video'],
13
- ['speech', 'Text to speech'],
14
- ['transcription', 'Speech to text'],
15
- ];
16
- /**
17
- * Phantom's own models from the server. /v1/routers names each one's chat
18
- * models and the model behind every other job; /v1/models says whether it
19
- * takes images. Neither needs a key.
20
- */
21
- export async function getModels(baseUrl, apiKey = '') {
22
- const [routers, list] = await Promise.all([
23
- request('GET', '/routers', apiKey, undefined, baseUrl),
24
- request('GET', '/models', apiKey, undefined, baseUrl),
25
- ]);
26
- const takesImages = new Set(list.data.filter((m) => m.modalities?.input?.includes('image')).map((m) => m.id));
27
- return routers.data.map((r) => {
28
- const can = JOBS.map(([job]) => job).filter((job) => {
29
- if (job === 'chat')
30
- return r.models.length > 0;
31
- // phantom-1 names a model for images; phantom-1:private sends them to its chat models.
32
- if (job === 'vision')
33
- return Boolean(r.jobs.vision) || takesImages.has(r.id);
34
- return Boolean(r.jobs[job]);
35
- });
36
- const chat = r.models.map((m) => ({ id: m.id, tier: m.tier === 'economy' ? 'free' : m.tier, free: m.pricing.prompt === 0 && m.pricing.completion === 0 }));
37
- return { id: r.id, name: r.name, description: r.description, chat, jobs: r.jobs, can };
38
- });
39
- }
@@ -1,7 +0,0 @@
1
- import { type CommandInput } from '../core/helpers.mts';
2
- /** `--table` output for `verify --model`. */
3
- export declare function tableVerifyModel(d: unknown): string;
4
- /** `--table` output for `verify --receipt`. */
5
- export declare function tableReceiptCheck(d: unknown): string;
6
- /** `phantom verify`: checks a receipt, or makes one small call and checks its receipt. Run by `run()`. */
7
- export declare function verifyCommand({ io, apiKey, flags, table, baseUrl }: CommandInput): Promise<number>;