@phantomcodes/cli 1.6.2 → 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 -114
  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
@@ -1,49 +1,152 @@
1
+ // docs: `phantom pi`, `phantom opencode`, `phantom codex` and `phantom claude` start a coding agent through Phantom. pi and OpenCode route on this computer (phantom-1 in this process, on the accounts in local.json) when local.json exists; codex and claude, and pi or opencode with --server, go through a local proxy to Phantom's server on a Phantom key (agents/phantom-key.mts). The agent never holds a key: it gets a one-run token. `ROUTES_HERE` is which agents route on this computer
1
2
  import os from 'node:os';
3
+ import { randomBytes } from 'node:crypto';
2
4
  import path from 'node:path';
3
- import { spawn } from 'node:child_process';
4
- import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5
- import { die, NO_KEY } from "../core/errors.mjs";
5
+ import { spawn, spawnSync } from 'node:child_process';
6
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { die } from "../core/errors.mjs";
6
8
  import { DEFAULT_BASE_URL, httpsOnly, request } from "../core/request.mjs";
7
- import { keyId, readNamedKey, resolveApiKey } from "../keys/saved.mjs";
8
- import { workspaceLogin } from "../workspace/command.mjs";
9
- import { startModel } from "../models/choice.mjs";
10
- import { claudeModelName } from "../setup/shared.mjs";
11
- /** The key's spend and balance, or null when the answer has no numbers, such as a sign-in page that came back with status 200. */
9
+ import { keyId, readNamedKey, resolveApiKey, startModel } from "./phantom-key.mjs";
10
+ import { loginCommand } from "./login.mjs";
11
+ import { proxyToken, startProxy } from "./proxy.mjs";
12
+ import { currentSession, OPENAI } from "../chatgpt/session.mjs";
13
+ import { startRouter } from "../local/command.mjs";
14
+ import { openCodeRoutingProblem } from "./opencode-check.mjs";
15
+ import { TIERS, TIER_NAME, localConfigPath } from "../local/config.mjs";
16
+ import { shown } from "../local/keys.mjs";
17
+ import { LOCAL_MODEL } from "../local/server.mjs";
12
18
  async function keyStatus(apiKey, baseUrl) {
13
19
  const s = await request('GET', '/key/balance', apiKey, undefined, baseUrl);
14
20
  return Number.isFinite(s.credit_spent_usd) && Number.isFinite(s.credit_balance_usd) ? s : null;
15
21
  }
16
- import { proxyToken, startProxy } from "./proxy.mjs";
22
+ export function onPath(bin) {
23
+ return spawnSync(process.platform === 'win32' ? 'where' : 'which', [bin], { stdio: 'ignore' }).status === 0;
24
+ }
25
+ /** The prefix Claude Code's `/model` picker needs to keep a model: it drops ids without "claude" in them. The server strips it again. */
26
+ const CLAUDE_CODE_PREFIX = 'claude-code/';
27
+ function claudeModelName(model) {
28
+ return CLAUDE_CODE_PREFIX + (model.startsWith(CLAUDE_CODE_PREFIX) ? model.slice(CLAUDE_CODE_PREFIX.length) : model);
29
+ }
30
+ function withoutKeys(env) {
31
+ const child = { ...env };
32
+ for (const name of ['PHANTOM_API_KEY', 'PHANTOM_KEY', 'PHANTOM_KEY_NAME', ...accountKeyVariables(env)])
33
+ delete child[name];
34
+ return child;
35
+ }
36
+ function accountKeyVariables(env) {
37
+ let file;
38
+ try {
39
+ file = JSON.parse(readFileSync(localConfigPath(env), 'utf8'));
40
+ }
41
+ catch {
42
+ return [];
43
+ }
44
+ const accounts = Object.values(file?.accounts ?? {});
45
+ return accounts.flatMap((a) => [a?.key?.from === 'env' ? a.key.name : undefined, a?.keyEnv]).filter((name) => typeof name === 'string');
46
+ }
47
+ const hasModel = (args) => args.some((a) => a === '-m' || a === '--model' || a.startsWith('--model=') || /^model=/.test(a));
48
+ const piOptions = (args) => (args.includes('--') ? args.slice(0, args.indexOf('--')) : args);
49
+ function lastValue(args, flag) {
50
+ const options = piOptions(args);
51
+ const at = options.lastIndexOf(flag);
52
+ return at === -1 ? undefined : options[at + 1];
53
+ }
54
+ function readJson(file) {
55
+ try {
56
+ return JSON.parse(readFileSync(file, 'utf8'));
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ }
17
62
  /**
18
- * The environment an agent starts with: the user's own, without the variables that name or hold a Phantom
19
- * key. The agent talks to the proxy with the run's token and never holds the key, and a stale
20
- * PHANTOM_AGENT_TOKEN from an outer run must not reach it either.
63
+ * pi's agent folder: --agent-dir, then PI_CODING_AGENT_DIR, then ~/.pi/agent. A leading `~` means the home folder
64
+ * and a relative path starts at `cwd`, as in pi 1.7.0 (`expandTildePath` in its dist/config.js, `resolvePath` in
65
+ * dist/utils/paths.js).
21
66
  */
22
- function withoutPhantomKeys(env) {
23
- const { PHANTOM_API_KEY: _key, PHANTOM_KEY_NAME: _name, PHANTOM_AGENT_TOKEN: _token, ...rest } = env;
24
- return rest;
67
+ function piAgentDir(args, env, cwd) {
68
+ const home = env.HOME || os.homedir();
69
+ const dir = lastValue(args, '--agent-dir') || env.PI_CODING_AGENT_DIR;
70
+ if (!dir)
71
+ return path.join(home, '.pi', 'agent');
72
+ return path.resolve(cwd, dir === '~' ? home : dir.startsWith('~/') ? path.join(home, dir.slice(2)) : dir);
25
73
  }
26
- const hasModel = (args) => args.some((a) => a === '-m' || a === '--model' || a.startsWith('--model=') || /^model=/.test(a));
27
- /** The agents phantom can run, by command name. */
74
+ /**
75
+ * Whether pi reads the project's own `.pi/settings.json`, decided the way pi 1.7.0 decides it before it starts
76
+ * (`resolveProjectTrusted` in its dist/core/project-trust.js): the last -a/--approve or -na/--no-approve, then the
77
+ * nearest folder trust.json names (dist/core/trust-manager.js), then `defaultProjectTrust` in the global settings.
78
+ * undefined when none of them decides, and pi will ask at startup (or, without a screen, not trust the project).
79
+ * An extension that answers pi's `project_trust` event decides before trust.json; phantom can't see that.
80
+ */
81
+ function piTrustsProject(args, agentDir, cwd, global) {
82
+ const flag = piOptions(args).findLast((a) => ['-a', '--approve', '-na', '--no-approve'].includes(a));
83
+ if (flag)
84
+ return flag === '-a' || flag === '--approve';
85
+ const trust = readJson(path.join(agentDir, 'trust.json'));
86
+ let dir = realpathSync(cwd);
87
+ for (;;) {
88
+ const decision = Object.entries(trust ?? {}).find(([key]) => path.resolve(key) === dir)?.[1];
89
+ if (typeof decision === 'boolean')
90
+ return decision;
91
+ if (path.dirname(dir) === dir)
92
+ break;
93
+ dir = path.dirname(dir);
94
+ }
95
+ if (global?.defaultProjectTrust === 'always')
96
+ return true;
97
+ if (global?.defaultProjectTrust === 'never')
98
+ return false;
99
+ return undefined;
100
+ }
101
+ /**
102
+ * The user's own pi model scope: the models pi's Ctrl+P cycles through and its /scoped-models lists (and the
103
+ * extensions that read `ctx.scopedModels`, such as a /providers command). It is the user's --models when they pass
104
+ * one. Otherwise it is `enabledModels` from pi's settings: the project's `.pi/settings.json` when it has the key and
105
+ * pi trusts the project, else the global settings.json in pi's agent folder (pi merges the two, the project's
106
+ * winning: dist/core/settings-manager.js `deepMergeSettings`). Empty means no scope, and pi then offers every model.
107
+ * null means phantom can't tell, because the project has a scope and pi will ask whether to trust it.
108
+ */
109
+ function piScope(args, env, cwd) {
110
+ const flag = lastValue(args, '--models');
111
+ if (flag !== undefined)
112
+ return flag.split(',').map((p) => p.trim()).filter(Boolean);
113
+ const agentDir = piAgentDir(args, env, cwd);
114
+ const global = readJson(path.join(agentDir, 'settings.json'));
115
+ const project = readJson(path.join(cwd, '.pi', 'settings.json'));
116
+ let enabledModels = global?.enabledModels;
117
+ if (project?.enabledModels !== undefined) {
118
+ const trusted = piTrustsProject(args, agentDir, cwd, global);
119
+ if (trusted === undefined)
120
+ return null;
121
+ if (trusted)
122
+ enabledModels = project.enabledModels;
123
+ }
124
+ return Array.isArray(enabledModels) ? enabledModels.filter((p) => typeof p === 'string') : [];
125
+ }
126
+ function withoutModels(args) {
127
+ const end = piOptions(args).length;
128
+ return args.filter((a, i) => i >= end || (a !== '--models' && args[i - 1] !== '--models'));
129
+ }
130
+ const OPENCODE_PROVIDER = `phantom-relay-${randomBytes(2).toString('hex')}`;
28
131
  export const AGENTS = {
29
132
  claude: {
30
133
  bin: 'claude',
31
134
  prefix: '/claude-code',
32
135
  launch(proxy, args, env, _tmp, token) {
33
136
  // --settings outranks settings.json, so an env block or apiKeyHelper
34
- // `phantom setup` wrote can't send Claude Code past the proxy. The helper
137
+ // an older CLI's setup wrote can't send Claude Code past the proxy. The helper
35
138
  // reads the token from the environment, so it stays off the command line.
36
- // It runs with this phantom's own Node: the curl installer puts none on PATH.
37
- const helper = `${JSON.stringify(process.execPath)} -p "process.env.PHANTOM_AGENT_TOKEN || ''"`;
38
- // The model picked with `phantom models` (phantom-1 until then), unless the user names one. It goes in the
139
+ // It is a shell builtin: it needs nothing on PATH, and a compiled phantom has no Node to run.
140
+ const helper = 'echo "$PHANTOM_AGENT_TOKEN"';
141
+ // The model an older CLI picked (phantom-1 otherwise), unless the user names one. It goes in the
39
142
  // environment, which Claude Code ranks below --model and below a model in its settings file.
40
143
  const model = hasModel(args) || env.ANTHROPIC_MODEL ? {} : { ANTHROPIC_MODEL: claudeModelName(startModel(env)) };
41
144
  // Claude Code's background calls (titles, summaries, the Explore agent that reads the code) go to its haiku
42
- // model. They follow the chosen model, and sit in --settings, which outranks the haiku model an earlier
43
- // `phantom setup` wrote, so a later `phantom models use phantom-1:zdr` covers them. A haiku model the user set in the shell stays theirs.
145
+ // model. They follow the chosen model, and sit in --settings, which outranks the haiku model an older
146
+ // CLI's setup wrote. A haiku model the user set in the shell stays theirs.
44
147
  const background = env.ANTHROPIC_DEFAULT_HAIKU_MODEL ? {} : { ANTHROPIC_DEFAULT_HAIKU_MODEL: claudeModelName(startModel(env)) };
45
148
  const vars = { ANTHROPIC_BASE_URL: proxy, CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: '1', ENABLE_TOOL_SEARCH: 'true', ...background };
46
- const { ANTHROPIC_AUTH_TOKEN: _auth, ...rest } = withoutPhantomKeys(env);
149
+ const { ANTHROPIC_AUTH_TOKEN: _auth, ...rest } = withoutKeys(env);
47
150
  return {
48
151
  args: ['--settings', JSON.stringify({ apiKeyHelper: helper, env: vars }), ...args],
49
152
  // Claude Code does not know the model `claude-code/phantom-1`, so it warns and guesses a window. Phantom's
@@ -64,7 +167,7 @@ export const AGENTS = {
64
167
  ['env_key', 'PHANTOM_AGENT_TOKEN'],
65
168
  ['model_catalog_url', `${base}/models`],
66
169
  ];
67
- // phantom_run, not phantom: phantom setup saves [model_providers.phantom],
170
+ // phantom_run, not phantom: an older CLI's setup saved [model_providers.phantom],
68
171
  // and -c merges into a table, so keys added there by hand would ride along.
69
172
  const config = [
70
173
  'model_provider="phantom_run"',
@@ -72,31 +175,118 @@ export const AGENTS = {
72
175
  'features.api_key_model_discovery=true',
73
176
  ...(hasModel(args) ? [] : [`model=${JSON.stringify(startModel(env))}`]),
74
177
  ];
75
- return { args: [...config.flatMap((c) => ['-c', c]), ...args], env: { ...withoutPhantomKeys(env), OPENAI_BASE_URL: base, PHANTOM_AGENT_TOKEN: token } };
178
+ return { args: [...config.flatMap((c) => ['-c', c]), ...args], env: { ...withoutKeys(env), OPENAI_BASE_URL: base, PHANTOM_AGENT_TOKEN: token } };
76
179
  },
77
180
  },
78
181
  pi: {
79
182
  bin: 'pi',
80
183
  prefix: '/coding-agent',
81
- launch(proxy, args, env, tmp, token) {
82
- // pi reads providers from models.json or an extension; an extension
83
- // for this run leaves the user's own files alone. Its key is read from
84
- // PHANTOM_AGENT_TOKEN when pi calls, so the file holds no secret.
184
+ launch(proxy, args, env, tmp, token, start = startModel(env)) {
85
185
  const file = path.join(tmp, 'phantom-provider.ts');
86
- const model = { id: startModel(env), name: 'Phantom AI (phantom)', reasoning: true, input: ['text', 'image'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 1_000_000, maxTokens: 64_000 };
87
- writeFileSync(file, `export default function (pi) {\n pi.registerProvider('phantom', ${JSON.stringify({ baseUrl: `${proxy}/v1`, api: 'openai-completions', apiKey: '$PHANTOM_AGENT_TOKEN', models: [model] })});\n}\n`, { mode: 0o600 });
88
- return { args: ['-e', file, ...(hasModel(args) ? [] : ['--provider', 'phantom', '--model', startModel(env)]), ...args], env: { ...withoutPhantomKeys(env), PHANTOM_AGENT_TOKEN: token } };
186
+ const model = { id: start, name: 'Phantom AI (phantom)', reasoning: true, input: ['text', 'image'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 1_000_000, maxTokens: 64_000 };
187
+ const provider = { baseUrl: `${proxy}/v1`, api: 'openai-completions', apiKey: '$PHANTOM_AGENT_TOKEN', models: [model] };
188
+ writeFileSync(file, piExtension(provider), { mode: 0o600 });
189
+ // phantom's model joins the user's model scope for this run, so Ctrl+P and /scoped-models offer it next to
190
+ // their own models and they can switch back to it. pi 1.7.0 (@earendil-works/pi-coding-agent) builds the
191
+ // scope once at startup from --models, or from enabledModels in its settings when there is no --models; a
192
+ // --models replaces enabledModels, and a second --models replaces the first (its dist/main.js,
193
+ // `parsed.models ?? settingsManager.getEnabledModels()`, and dist/cli/args.js; docs/settings.md
194
+ // "enabledModels", docs/cli.md "--models"). It matches the models an extension registers (docs/extensions.md
195
+ // "ctx.scopedModels"), and extensions can only read the scope, not add to it. So phantom passes one
196
+ // --models: its model, then the user's own scope. pi's settings are only read. phantom passes none, and pi
197
+ // keeps its own scope, when there is no scope (pi already offers every model, and a --models would narrow
198
+ // that), when the scope already has a phantom/ model, when phantom can't tell which scope pi will use, and
199
+ // when a pattern has a comma: pi splits --models at every comma, so `claude-{sonnet,opus}*` would break.
200
+ const scope = piScope(args, env, process.cwd());
201
+ const comma = scope?.find((p) => p.includes(','));
202
+ const joins = scope !== null && scope.length > 0 && !comma && !scope.some((p) => p.startsWith('phantom/'));
203
+ const models = joins ? ['--models', [`phantom/${start}`, ...scope].join(',')] : [];
204
+ const rest = joins ? withoutModels(args) : args;
205
+ return {
206
+ args: ['-e', file, ...models, ...(hasModel(args) ? [] : ['--provider', 'phantom', '--model', start]), ...rest],
207
+ env: { ...withoutKeys(env), PHANTOM_AGENT_TOKEN: token },
208
+ ...(comma ? { warning: `phantom: pi's model pattern ${comma} has a comma, which --models can't carry, so phantom/${start} isn't in pi's model scope this run (Ctrl+P and /scoped-models won't offer it).` } : {}),
209
+ };
210
+ },
211
+ },
212
+ opencode: {
213
+ bin: 'opencode',
214
+ prefix: '/coding-agent',
215
+ launch(proxy, args, env, _tmp, token, start = startModel(env)) {
216
+ // OpenCode 2.4.3 reads a whole config from OPENCODE_CONFIG_CONTENT and merges it over the user's
217
+ // ~/.config/opencode/opencode.jsonc, winning where both set a value, so the user's file stays untouched.
218
+ // The `providers` shape is OpenCode's v2 one (https://opencode.ai/docs/providers/): `package`,
219
+ // `settings.baseURL`, and `env`, the variables the key is read from when OpenCode calls, so the key is
220
+ // never in the config. The provider's id, `phantom-relay-<4 letters>`, is new for each phantom run, so no
221
+ // user config can name it: settings a user gives their own `phantom` provider or its models (a model's
222
+ // `settings.baseURL`, say) would merge into a provider named `phantom` and send its calls elsewhere.
223
+ // `policies` (https://opencode.ai/docs/config/) deny every other provider, OpenCode's free models and the
224
+ // user's own `phantom` included: its title, summary and compaction jobs then have only phantom-1 to run on.
225
+ // 2.4.3 reads a `small_model` as the title agent's model (`agents.title`), and with these rules a model on
226
+ // another provider is not offered, so titles run on phantom-1 too. A user's own rules can still turn
227
+ // providers back on, so {@link openCodeRoutingProblem} checks before each run.
228
+ const config = {
229
+ model: `${OPENCODE_PROVIDER}/${start}`,
230
+ policies: [
231
+ { action: 'provider.use', resource: '*', effect: 'deny' },
232
+ { action: 'provider.use', resource: OPENCODE_PROVIDER, effect: 'allow' },
233
+ ],
234
+ providers: {
235
+ [OPENCODE_PROVIDER]: {
236
+ name: 'Phantom AI (phantom)',
237
+ package: '@opencode/ai/providers/openai-compatible',
238
+ env: ['PHANTOM_AGENT_TOKEN'],
239
+ settings: { baseURL: `${proxy}/v1` },
240
+ models: { [start]: { name: start } },
241
+ },
242
+ },
243
+ };
244
+ // --standalone runs OpenCode on a server of its own for this run. Without it OpenCode talks to its
245
+ // shared background server, which "owns sessions, configuration" (https://opencode.ai/docs/cli/) and
246
+ // never sees this run's config or token.
247
+ return { args: ['--standalone', ...args], env: { ...withoutKeys(env), OPENCODE_CONFIG_CONTENT: JSON.stringify(config), PHANTOM_AGENT_TOKEN: token } };
89
248
  },
90
249
  },
91
250
  };
92
- /** Waits for the agent and returns its exit code; a signal counts as 128 plus its number. */
251
+ // pi 1.7.0 docs/extensions.md: "after_provider_response" (each HTTP response's status and lowercased headers),
252
+ // "model_select", "ctx.hasUI", and ctx.ui.setStatus (footer) and ctx.ui.notify.
253
+ const NOTICE_REPEAT_MS = 10 * 60 * 1000;
254
+ function piExtension(provider) {
255
+ return [
256
+ 'export default function (pi) {',
257
+ ` pi.registerProvider('phantom', ${JSON.stringify(provider)});`,
258
+ ' const shownAt = new Map();',
259
+ " pi.on('after_provider_response', (event, ctx) => {",
260
+ " const status = event.headers['x-phantom-local-status'];",
261
+ ' if (!status || !ctx.hasUI) return;',
262
+ " ctx.ui.setStatus('phantom', status);",
263
+ " const notice = event.headers['x-phantom-local-notice'];",
264
+ ' if (!notice) return;',
265
+ ' const lastShown = shownAt.get(notice);',
266
+ ` if (lastShown !== undefined && Date.now() - lastShown < ${NOTICE_REPEAT_MS}) return;`,
267
+ ' shownAt.set(notice, Date.now());',
268
+ " ctx.ui.notify(notice, 'warning');",
269
+ ' });',
270
+ " pi.on('model_select', (event, ctx) => {",
271
+ " if (ctx.hasUI && event.model.provider !== 'phantom') ctx.ui.setStatus('phantom', undefined);",
272
+ ' });',
273
+ '}',
274
+ '',
275
+ ].join('\n');
276
+ }
93
277
  function waitFor(bin, args, env) {
94
278
  return new Promise((resolve, reject) => {
95
279
  const child = spawn(bin, args, { stdio: 'inherit', env: env });
96
- // Ctrl-C reaches the agent itself; phantom stays to stop the proxy and print the spend.
97
280
  const ignore = () => { };
281
+ const passOn = (signal) => child.kill(signal);
98
282
  process.on('SIGINT', ignore);
99
- const done = () => process.off('SIGINT', ignore);
283
+ process.on('SIGTERM', passOn);
284
+ process.on('SIGHUP', passOn);
285
+ const done = () => {
286
+ process.off('SIGINT', ignore);
287
+ process.off('SIGTERM', passOn);
288
+ process.off('SIGHUP', passOn);
289
+ };
100
290
  child.on('error', (err) => {
101
291
  done();
102
292
  reject(err.code === 'ENOENT' ? new Error(notInstalled(bin)) : err);
@@ -107,19 +297,20 @@ function waitFor(bin, args, env) {
107
297
  });
108
298
  });
109
299
  }
110
- /**
111
- * `phantom claude`, `phantom codex` and `phantom pi`: runs the agent through the proxy,
112
- * passing every other argument through, and returns its exit code. The Phantom CLI's own
113
- * flags come first and stop at the first other argument or at `--`; they are
114
- * read here, not with `flags`, because everything after them belongs to the
115
- * agent. Run by `run()`.
116
- */
300
+ export const ROUTES_HERE = ['pi', 'opencode'];
301
+ function nothingToRunOn(name, server) {
302
+ if (ROUTES_HERE.includes(name) && !server)
303
+ return `phantom ${name} has no routing set up yet. Run phantom config to choose your accounts and models, then phantom ${name} again.`;
304
+ if (ROUTES_HERE.includes(name))
305
+ return `phantom ${name} --server needs a Phantom key. Run phantom login, or set PHANTOM_API_KEY. To route on your own accounts instead, run phantom config, then phantom ${name}.`;
306
+ return `phantom ${name} runs on Phantom's server for now and needs a Phantom key. Run phantom login, or set PHANTOM_API_KEY. To route on your own accounts, run phantom config, then phantom pi.`;
307
+ }
117
308
  export async function agentCommand(input) {
118
309
  const { argv, env, io, baseUrl } = input;
119
310
  const name = argv[0];
120
311
  const spec = AGENTS[name];
121
312
  let keyName;
122
- let noBrowser = false;
313
+ let server = false;
123
314
  let i = 1;
124
315
  const value = (flag) => {
125
316
  const v = argv[++i];
@@ -135,23 +326,22 @@ export async function agentCommand(input) {
135
326
  }
136
327
  if (a === '--key')
137
328
  keyName = value(a);
138
- else if (a === '--mpp')
139
- die('--mpp has been removed: an agent run spends your key\'s credit. Run phantom login to sign in, or pick a saved key with --key <name>.');
140
- else if (a === '--no-browser')
141
- noBrowser = true;
329
+ else if (a === '--server')
330
+ server = true;
142
331
  else
143
332
  break;
144
333
  }
145
334
  const agentArgs = argv.slice(i);
335
+ if (ROUTES_HERE.includes(name) && !server && !keyName && existsSync(localConfigPath(env)))
336
+ return routeOnThisComputer(name, agentArgs, input);
146
337
  let apiKey = keyName ? readNamedKey(env, keyName) : resolveApiKey(env);
147
- if (!apiKey) {
148
- if (!io.isTTY)
149
- die(NO_KEY);
150
- await workspaceLogin({ ...input, flags: { ...(noBrowser ? { 'no-browser': true } : {}) } });
338
+ if (!apiKey && !keyName && io.isTTY && (server || !ROUTES_HERE.includes(name))) {
339
+ await loginCommand({ ...input, subcommand: undefined, flags: {}, io: { ...io, stdout: io.stderr } });
151
340
  apiKey = resolveApiKey(env);
152
341
  }
153
342
  if (!apiKey)
154
- die(NO_KEY);
343
+ die(nothingToRunOn(name, server), 'no_key');
344
+ await stopIfOpenCodeCouldSkipPhantom(name, agentArgs, env, startModel(env));
155
345
  const auth = { kind: 'key', apiKey };
156
346
  const before = await keyStatus(apiKey, baseUrl).catch(() => null);
157
347
  const report = async () => {
@@ -162,13 +352,22 @@ export async function agentCommand(input) {
162
352
  };
163
353
  const origin = httpsOnly(baseUrl || env.PHANTOM_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, '').replace(/\/v1$/, '');
164
354
  const token = proxyToken();
165
- const proxy = await startProxy({ upstream: `${origin}${spec.prefix}`, auth, token });
355
+ // Codex speaks the Responses API, the one wire format the ChatGPT plan takes, so on Phantom's server only Codex can use the ChatGPT sign-in.
356
+ const chatgpt = name === 'codex' ? () => currentSession(env) : undefined;
357
+ if (chatgpt && (await chatgpt()).kind === 'signed-in')
358
+ io.stderr(`phantom: Using ChatGPT plan for openai/ models; other models spend Phantom credit. Manage usage: ${OPENAI.usage}\n`);
359
+ const proxy = await startProxy({ upstream: `${origin}${spec.prefix}`, auth, token, chatgpt });
166
360
  const tmp = mkdtempSync(path.join(os.tmpdir(), 'phantom-agent-'));
167
361
  try {
168
- const { args, env: childEnv } = spec.launch(proxy.url, agentArgs, env, tmp, token);
362
+ const { args, env: childEnv, warning } = spec.launch(proxy.url, agentArgs, env, tmp, token);
363
+ if (warning)
364
+ io.stderr(warning + '\n');
169
365
  const code = await waitFor(spec.bin, args, childEnv);
170
366
  await proxy.close();
171
- io.stderr(`phantom: ${name} made ${proxy.forwarded} request${proxy.forwarded === 1 ? '' : 's'} to Phantom AI${proxy.rejected ? `, and refused ${proxy.rejected} from other programs` : ''}; ${await report()}.\n`);
367
+ const plan = proxy.direct ? ` and ${proxy.direct} on your ChatGPT plan` : '';
368
+ for (const note of proxy.notes)
369
+ io.stderr(`phantom: skipped the ChatGPT plan, and Phantom AI served the request instead: ${note}.\n`);
370
+ io.stderr(`phantom: ${name} made ${proxy.forwarded} request${proxy.forwarded === 1 ? '' : 's'} to Phantom AI${plan}${proxy.rejected ? `, and refused ${proxy.rejected} from other programs` : ''}; ${await report()}.\n`);
172
371
  return code;
173
372
  }
174
373
  finally {
@@ -176,13 +375,78 @@ export async function agentCommand(input) {
176
375
  rmSync(tmp, { recursive: true, force: true });
177
376
  }
178
377
  }
179
- /** Where to get each agent phantom starts, for when it isn't installed. */
378
+ async function routeOnThisComputer(name, agentArgs, input) {
379
+ const { env, io } = input;
380
+ const spec = AGENTS[name];
381
+ await stopIfOpenCodeCouldSkipPhantom(name, agentArgs, env, LOCAL_MODEL);
382
+ const token = proxyToken();
383
+ const records = [];
384
+ const later = new Set();
385
+ const router = await startRouter({
386
+ env,
387
+ port: 0,
388
+ token,
389
+ notify: (line) => io.stderr(line + '\n'),
390
+ log: () => { },
391
+ warn: (line) => later.add(line),
392
+ onRequest: (record) => records.push(record),
393
+ });
394
+ io.stderr(`phantom: ${name} routes on this computer: ${tiersText(router.config)}\n`);
395
+ if (router.tracesFolder)
396
+ io.stderr(`phantom: traces are on: each request's full prompt and answer is saved on this computer in ${router.tracesFolder} (phantom config --traces off stops it from the next run)\n`);
397
+ const tmp = mkdtempSync(path.join(os.tmpdir(), 'phantom-agent-'));
398
+ try {
399
+ const launched = spec.launch(router.url, agentArgs, env, tmp, token, LOCAL_MODEL);
400
+ if (launched.warning)
401
+ io.stderr(launched.warning + '\n');
402
+ const code = await waitFor(spec.bin, launched.args, launched.env);
403
+ await router.close();
404
+ for (const line of later)
405
+ io.stderr(line + '\n');
406
+ io.stderr(routedSummary(name, records, router.logFile, router.tracesFolder));
407
+ return code;
408
+ }
409
+ finally {
410
+ await router.close().catch(() => { });
411
+ rmSync(tmp, { recursive: true, force: true });
412
+ }
413
+ }
414
+ async function stopIfOpenCodeCouldSkipPhantom(name, agentArgs, env, model) {
415
+ if (name !== 'opencode')
416
+ return;
417
+ const run = AGENTS.opencode.launch('http://127.0.0.1:9', agentArgs, env, '', 'not-a-token', model);
418
+ const problem = await openCodeRoutingProblem(run.env, agentArgs, process.cwd()).catch((err) => {
419
+ throw err.code === 'ENOENT' ? new Error(notInstalled('opencode')) : err;
420
+ });
421
+ if (problem)
422
+ die(problem, 'opencode_config');
423
+ }
424
+ function tiersText(config) {
425
+ const tiers = TIERS.map((t) => `${TIER_NAME[t]} ${shown(config.tiers[t].model)} on ${shown(config.tiers[t].account)}`).join(', ');
426
+ return `${tiers} (local.json)`;
427
+ }
428
+ function routedSummary(name, records, logFile, tracesFolder) {
429
+ const tiers = TIERS.flatMap((t) => {
430
+ const onTier = records.filter((r) => r.picked === t);
431
+ return onTier.length ? [`${onTier.length} ${TIER_NAME[t]} (${[...new Set(onTier.map((r) => shown(r.account)))].join(', ')})`] : [];
432
+ });
433
+ const fallbacks = records.filter((r) => r.fallback).length;
434
+ const cancelled = records.filter((r) => r.outcome === 'client-closed').length;
435
+ const failed = records.filter((r) => r.outcome !== 'ok' && r.outcome !== 'client-closed').length;
436
+ const parts = [
437
+ ...tiers,
438
+ ...(fallbacks ? [`${fallbacks} fallback${fallbacks === 1 ? '' : 's'}`] : []),
439
+ ...(failed ? [`${failed} failed`] : []),
440
+ ];
441
+ const made = `${records.length} request${records.length === 1 ? '' : 's'}${cancelled ? ` (${cancelled} cancelled by ${name})` : ''}${parts.length ? `: ${parts.join(', ')}` : ''}`;
442
+ return `phantom: ${name} made ${made}; ${logFile ? `log: ${logFile}` : 'no log, since local.json turns it off'}${tracesFolder ? `; traces: ${tracesFolder}` : ''}\n`;
443
+ }
180
444
  const INSTALL = {
181
445
  claude: 'Claude Code: https://code.claude.com/docs/en/setup',
182
446
  codex: 'Codex: npm install -g @openai/codex',
447
+ opencode: 'OpenCode: https://opencode.ai/docs/',
183
448
  };
184
- /** The message when an agent's program isn't installed, in plain words, with where to get it. */
185
- export function notInstalled(bin) {
449
+ function notInstalled(bin) {
186
450
  const how = INSTALL[bin];
187
451
  return `phantom can't find ${bin} on this computer: it isn't installed, or isn't on your PATH.${how ? ` Install ${how}, then run this again.` : ' Install it, then run this again.'}`;
188
452
  }
@@ -0,0 +1,3 @@
1
+ import { type CommandInput } from '../core/helpers.mts';
2
+ export declare function loginCommand(input: CommandInput): Promise<number>;
3
+ export declare function logoutCommand(input: CommandInput): Promise<number>;
@@ -0,0 +1,97 @@
1
+ // docs: `phantom login` and `phantom logout`: sign in to Phantom in the browser with a device code (RFC 8628), then save the Phantom key the server returns where agents/phantom-key.mts reads it, for `phantom claude`, `phantom codex` and `phantom pi --server`. The key is never printed. `phantom claude` and `phantom codex` start this themselves at a terminal when there is no key
2
+ import { existsSync } from 'node:fs';
3
+ import { hostname } from 'node:os';
4
+ import { die } from "../core/errors.mjs";
5
+ import { openUrl, out } from "../core/helpers.mjs";
6
+ import { answerError, apiBase, fetchAnswer, request } from "../core/request.mjs";
7
+ import { removeSecret, writeSecret } from "../core/secrets.mjs";
8
+ import { keyPath } from "./phantom-key.mjs";
9
+ const MIN_WAIT_SECONDS = 1;
10
+ const SLOW_DOWN_SECONDS = 5;
11
+ const wait = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
12
+ function siteOrigin(baseUrl) {
13
+ return new URL(apiBase(baseUrl)).origin;
14
+ }
15
+ async function post(path, body, baseUrl) {
16
+ return fetchAnswer(`${apiBase(baseUrl)}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }, `POST ${path}`);
17
+ }
18
+ async function startLogin(baseUrl) {
19
+ const { res, answer } = await post('/auth/device', { client_name: `phantom on ${hostname()}` }, baseUrl);
20
+ if (!res.ok)
21
+ throw answerError(res.status, answer);
22
+ const started = answer.json;
23
+ if (typeof started.device_code !== 'string' || typeof started.user_code !== 'string' || typeof started.verification_uri_complete !== 'string') {
24
+ die('Phantom AI answered the sign-in request without a code. Try again in a minute.', 'login_bad_answer');
25
+ }
26
+ let link;
27
+ try {
28
+ link = new URL(started.verification_uri_complete);
29
+ }
30
+ catch {
31
+ return die('The approval link is not a web address, so phantom did not open it.', 'device_origin');
32
+ }
33
+ if (link.origin !== siteOrigin(baseUrl))
34
+ die('The approval link belongs to another site, so phantom did not open it.', 'device_origin');
35
+ return {
36
+ device_code: started.device_code,
37
+ user_code: started.user_code,
38
+ verification_uri_complete: link.href,
39
+ interval: typeof started.interval === 'number' ? started.interval : MIN_WAIT_SECONDS,
40
+ expires_in: typeof started.expires_in === 'number' ? started.expires_in : 600,
41
+ };
42
+ }
43
+ async function waitForApproval(started, baseUrl) {
44
+ let interval = Math.max(MIN_WAIT_SECONDS, started.interval);
45
+ for (let waited = 0; waited <= started.expires_in; waited += interval) {
46
+ await wait(interval);
47
+ const { res, answer } = await post('/auth/device/token', { device_code: started.device_code }, baseUrl);
48
+ if (res.ok) {
49
+ const key = answer.json.api_key;
50
+ if (typeof key !== 'string' || !key.startsWith('sk-phantom-'))
51
+ die('Phantom AI answered without a usable key. Nothing was saved.', 'login_bad_answer');
52
+ return key;
53
+ }
54
+ const error = answer.json.error;
55
+ if (error === 'authorization_pending')
56
+ continue;
57
+ if (error === 'slow_down') {
58
+ interval += SLOW_DOWN_SECONDS;
59
+ continue;
60
+ }
61
+ if (error === 'access_denied')
62
+ die('You declined in the browser. Nothing was saved.', 'login_denied');
63
+ if (error === 'expired_token')
64
+ break;
65
+ throw answerError(res.status, answer);
66
+ }
67
+ return die('The code expired before it was approved. Run phantom login to try again. Nothing was saved.', 'login_expired');
68
+ }
69
+ export async function loginCommand(input) {
70
+ const { env, io, flags, table, baseUrl } = input;
71
+ if (existsSync(keyPath(env))) {
72
+ out({ signed_in: true, already: true }, table, () => 'Already signed in on this computer. phantom logout signs out.', io.stdout);
73
+ return 0;
74
+ }
75
+ const started = await startLogin(baseUrl);
76
+ io.stderr(`Sign in to Phantom in your browser. If it did not open, visit:\n ${started.verification_uri_complete}\n` +
77
+ `Check that the page shows this code, then approve it: ${started.user_code}\nWaiting for you to approve...\n`);
78
+ if (!flags['no-browser'])
79
+ openUrl(started.verification_uri_complete);
80
+ const key = await waitForApproval(started, baseUrl);
81
+ writeSecret(env, keyPath(env), key);
82
+ const credit = await request('GET', '/key/balance', key, undefined, baseUrl).then((r) => r.credit_balance_usd, () => null);
83
+ const sentence = credit === null || credit > 0
84
+ ? `Signed in.${credit === null ? '' : ` Credit left: $${credit.toFixed(2)}.`} phantom claude and phantom codex use this key.`
85
+ : `Signed in. No credit yet: add some on your account at ${siteOrigin(baseUrl)}/keys. phantom claude and phantom codex use this key once it has credit.`;
86
+ out({ signed_in: true, credit_usd: credit }, table, () => sentence, io.stdout);
87
+ return 0;
88
+ }
89
+ export async function logoutCommand(input) {
90
+ const { env, io, table, baseUrl } = input;
91
+ const file = keyPath(env);
92
+ const removed = existsSync(file);
93
+ if (removed)
94
+ removeSecret(file);
95
+ out({ signed_in: false, removed }, table, () => (removed ? `Signed out. The key is gone from this computer. It still works until you revoke it at ${siteOrigin(baseUrl)}/keys.` : 'No saved key on this computer.'), io.stdout);
96
+ return 0;
97
+ }
@@ -0,0 +1,15 @@
1
+ import type { Env } from '../core/state.mts';
2
+ /**
3
+ * Why phantom has to ask OpenCode instead of trusting its own settings: OpenCode 2.4.3 lays phantom's run config
4
+ * (`OPENCODE_CONFIG_CONTENT`) over the user's own files, but those files are merged in too. Seen with 2.4.3:
5
+ * - provider rules (`enabled_providers`, or an `allow` in `policies`) turn other providers back on, including one
6
+ * with no key yet, which `/connect` in OpenCode's screen can add a key to during the run;
7
+ * - settings for the run's provider (a model's `settings.baseURL`, a second model) merge into it and send calls
8
+ * elsewhere. The run's provider has an id no user config uses (`phantom-relay-<4 letters>`), so this takes a file
9
+ * that names it on purpose, but it is checked anyway.
10
+ * A call that goes around the relay skips phantom-1: unrouted, unlogged, on another account.
11
+ *
12
+ * The run's provider and models are read from the run's config in `env`. Returns the message to stop with, or null
13
+ * when every folder is clean. Rejects with the spawn error when OpenCode can't be started (not installed).
14
+ */
15
+ export declare function openCodeRoutingProblem(env: Env, args: string[], cwd: string, limitMs?: number): Promise<string | null>;