@phantomcodes/cli 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +13 -2
  2. package/dist/agents/command.d.mts +36 -0
  3. package/dist/agents/command.mjs +19 -7
  4. package/dist/agents/proxy.d.mts +44 -0
  5. package/dist/agents/proxy.mjs +4 -2
  6. package/dist/cli/app.d.mts +25 -0
  7. package/dist/cli/commands.d.mts +19 -0
  8. package/dist/cli/commands.mjs +1 -1
  9. package/dist/cli/help.d.mts +26 -0
  10. package/dist/cli/run.d.mts +2 -0
  11. package/dist/cli/screens.d.mts +171 -0
  12. package/dist/cli/start.d.mts +34 -0
  13. package/dist/core/brand.d.mts +12 -0
  14. package/dist/core/errors.d.mts +27 -0
  15. package/dist/core/free.d.mts +13 -0
  16. package/dist/core/helpers.d.mts +75 -0
  17. package/dist/core/helpers.mjs +27 -2
  18. package/dist/core/motion.d.mts +47 -0
  19. package/dist/core/node-trust.d.mts +12 -0
  20. package/dist/core/pick.d.mts +86 -0
  21. package/dist/core/request.d.mts +64 -0
  22. package/dist/core/request.mjs +78 -29
  23. package/dist/core/secrets.d.mts +33 -0
  24. package/dist/core/shapes.d.mts +13 -0
  25. package/dist/core/state.d.mts +3 -0
  26. package/dist/core/style.d.mts +49 -0
  27. package/dist/core/version.d.mts +2 -0
  28. package/dist/core/version.mjs +1 -1
  29. package/dist/keys/command.d.mts +16 -0
  30. package/dist/keys/saved.d.mts +88 -0
  31. package/dist/models/choice.d.mts +7 -0
  32. package/dist/models/choice.mjs +1 -1
  33. package/dist/models/command.d.mts +8 -0
  34. package/dist/models/list.d.mts +39 -0
  35. package/dist/phantom.d.mts +45 -0
  36. package/dist/receipts/command.d.mts +7 -0
  37. package/dist/receipts/receipts.d.mts +67 -0
  38. package/dist/receipts/receipts.mjs +15 -11
  39. package/dist/setup/agents.d.mts +149 -0
  40. package/dist/setup/agents.mjs +48 -35
  41. package/dist/setup/apply.d.mts +71 -0
  42. package/dist/setup/apply.mjs +7 -2
  43. package/dist/setup/command.d.mts +12 -0
  44. package/dist/setup/editors.d.mts +101 -0
  45. package/dist/setup/editors.mjs +4 -2
  46. package/dist/setup/legacy.d.mts +13 -0
  47. package/dist/setup/plan.d.mts +104 -0
  48. package/dist/setup/plan.mjs +5 -3
  49. package/dist/setup/screen.d.mts +30 -0
  50. package/dist/setup/shared.d.mts +141 -0
  51. package/dist/setup/shared.mjs +8 -2
  52. package/dist/setup/was.d.mts +42 -0
  53. package/dist/setup/was.mjs +91 -0
  54. package/dist/spend/command.d.mts +5 -0
  55. package/dist/spend/lineup.d.mts +54 -0
  56. package/dist/spend/lineup.mjs +3 -2
  57. package/dist/spend/report.d.mts +105 -0
  58. package/dist/spend/routing.d.mts +72 -0
  59. package/dist/workspace/command.d.mts +46 -0
  60. package/dist/workspace/command.mjs +83 -37
  61. package/package.json +2 -2
@@ -0,0 +1,39 @@
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
+ /** economy, standard or frontier. */
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:zdr. */
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[]>;
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * phantom: points your coding agents at Phantom AI.
4
+ *
5
+ * Keys, money and setup for any AI agent: a Phantom AI key, model routing,
6
+ * and receipts that show which model answered. It runs as a CLI and through
7
+ * the phantom-ai skill, so pi, Claude Code, Codex and Cursor can all drive it
8
+ * by prompt.
9
+ *
10
+ * This file is the entry point. The code lives in one folder per feature
11
+ * beside it, and this file exports the public API from them. From a
12
+ * checkout: `node src/phantom.mts`.
13
+ */
14
+ export { DEFAULT_BASE_URL, REQUEST_TIMEOUT_MS, request, httpsOnly, getBalance } from './core/request.mts';
15
+ export { VERSION } from './core/version.mts';
16
+ export { PhantomApiError, CliError, die } from './core/errors.mts';
17
+ export type { BalanceResult } from './core/shapes.mts';
18
+ export { getLineup, putLineup, resetLineup, LINEUP_TIERS } from './spend/lineup.mts';
19
+ export type { Lineup, LineupPicks, LineupTier, LineupChoice, LineupTierModel, LineupResult } from './spend/lineup.mts';
20
+ export { getRoute, putRoute, patchRoute, clearRoute, testRoute, parseCondition } from './spend/routing.mts';
21
+ export type { RouteRule, RoutePolicy, RouteResult, RouteTestResult } from './spend/routing.mts';
22
+ export { getSpend, tableSpend } from './spend/report.mts';
23
+ export type { SpendResult, SpendLine, SpendTotal, SpendKey, SpendKeyModel, SpendModel, SpendDay, SpendRouting, SpendDates } from './spend/report.mts';
24
+ export { checkReceipt, modelsMatch, verifyModel } from './receipts/receipts.mts';
25
+ export type { Receipt, ReceiptCheck, VerifyModelResult } from './receipts/receipts.mts';
26
+ export type { Env } from './core/state.mts';
27
+ export { keychain } from './core/secrets.mts';
28
+ export { keyId, keySource, resolveApiKey, readNamedKey, saveNamedKey, removeNamedKey, listNamedKeys, saveApiKey, removeApiKey } from './keys/saved.mts';
29
+ export type { KeySource } from './keys/saved.mts';
30
+ export { SETUP_MODEL, agentBaseUrl } from './setup/shared.mts';
31
+ export type { SetupAgent, AgentPath, ProviderResult } from './setup/shared.mts';
32
+ export { planSetup } from './setup/plan.mts';
33
+ export type { SetupFile, SetupPlan, SetupResult, SetupOptions } from './setup/plan.mts';
34
+ export { applySetup, previewSetup, setupAgents, restoreSetup } from './setup/apply.mts';
35
+ export type { RestoreResult } from './setup/apply.mts';
36
+ export type { SetupContext, SetupEdit, ProviderPlan, SetupAgentSpec } from './setup/shared.mts';
37
+ export { jsonEdit, tomlSet, tomlRemoveOurs, yamlSetTop, yamlAddModel, yamlRemoveOurs, shellRcFile, shellBlock } from './setup/editors.mts';
38
+ export type { JsonChange, ShellBlockState } from './setup/editors.mts';
39
+ export { SETUP_AGENTS } from './setup/agents.mts';
40
+ export { claudeProvider } from './setup/apply.mts';
41
+ export { ENV_VARS, HELP } from './cli/help.mts';
42
+ export type { EnvVar } from './cli/help.mts';
43
+ export { run } from './cli/run.mts';
44
+ /** The installed entry point: {@link run} with the process's arguments, then `process.exit` with its code when it is not 0. */
45
+ export declare function main(): Promise<void>;
@@ -0,0 +1,7 @@
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>;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The signed content of a receipt. phantom reads the fields listed here; the
3
+ * server signs more (such as hashes of the request and response), and they
4
+ * pass through untouched.
5
+ */
6
+ export type Receipt = {
7
+ /** The receipt format version. {@link checkReceipt} accepts only version 1. */
8
+ v: number;
9
+ /** Phantom AI's id for the call. */
10
+ request_id: string;
11
+ /** When the receipt was signed, as an ISO 8601 time. */
12
+ ts: string;
13
+ /** The model id the call asked for. */
14
+ model_requested: string;
15
+ /** The model id the upstream's own response named. */
16
+ model_served: string;
17
+ /** Tokens in the prompt. */
18
+ prompt_tokens: number;
19
+ /** Tokens in the answer. */
20
+ completion_tokens: number;
21
+ /** Reasoning tokens in the answer. 0 when there were none. */
22
+ reasoning_tokens: number;
23
+ /** What the call cost, in millionths of a US dollar. */
24
+ cost_micro_usd: number;
25
+ /** Other signed fields. */
26
+ [field: string]: unknown;
27
+ };
28
+ /** The result of checking a receipt with {@link checkReceipt}. */
29
+ export type ReceiptCheck = {
30
+ /** True when the signature matches Phantom AI's published key. */
31
+ valid: boolean;
32
+ /** The decoded receipt, or null when it could not be read. */
33
+ receipt: Receipt | null;
34
+ /** Why the check failed. Absent when it passed. */
35
+ reason?: string;
36
+ };
37
+ /** The result of {@link verifyModel}. */
38
+ export type VerifyModelResult = {
39
+ /** The model id phantom asked for. */
40
+ model_requested: string;
41
+ /** The model the receipt says answered. null when there was no readable receipt. */
42
+ model_served: string | null;
43
+ /** True when the signature is valid and the served model matches the one asked for ({@link modelsMatch}). */
44
+ match: boolean;
45
+ /** True when the receipt's signature matches Phantom AI's published key. */
46
+ signature_valid: boolean;
47
+ /** What the call cost, in USD. null without a receipt. */
48
+ cost_usd: number | null;
49
+ /** Phantom AI's id for the call. null without a receipt. */
50
+ request_id: string | null;
51
+ /** The compact receipt from the x-phantom-receipt header. null when the answer had none. */
52
+ receipt: string | null;
53
+ /** Why it did not match or could not be checked. Absent when all is well. */
54
+ reason?: string;
55
+ };
56
+ /**
57
+ * Checks a compact receipt (`payload.signature`, both base64url) against the
58
+ * public key from GET /receipts/key. Needs no API key.
59
+ * @param timeoutMs How long to wait for the key. Defaults to {@link REQUEST_TIMEOUT_MS}.
60
+ * @throws {@link PhantomApiError} when the public key cannot be fetched.
61
+ * @throws {@link CliError} `request_timeout` when the server does not answer in time, `bad_answer` when it sends a web page.
62
+ */
63
+ export declare function checkReceipt(compact: string, baseUrl?: string, timeoutMs?: number): Promise<ReceiptCheck>;
64
+ /** The served id can drop the provider prefix, so a bare name counts as a match. */
65
+ export declare function modelsMatch(requested: string, served: string): boolean;
66
+ /** One small priced call to `model`, then a check of the receipt it returns. */
67
+ export declare function verifyModel(apiKey: string, model: string, baseUrl?: string, timeoutMs?: number): Promise<VerifyModelResult>;
@@ -1,5 +1,6 @@
1
1
  import { createPublicKey, verify as cryptoVerify } from 'node:crypto';
2
- import { apiBase, apiError } from "../core/request.mjs";
2
+ import { die } from "../core/errors.mjs";
3
+ import { REQUEST_TIMEOUT_MS, answerError, apiBase, fetchAnswer } from "../core/request.mjs";
3
4
  /**
4
5
  * Every priced call returns a receipt signed with Phantom AI's Ed25519 key. The
5
6
  * check runs here, against the public key from /receipts/key, so the answer
@@ -10,13 +11,17 @@ const RECEIPT_VERSION = 1;
10
11
  /**
11
12
  * Checks a compact receipt (`payload.signature`, both base64url) against the
12
13
  * public key from GET /receipts/key. Needs no API key.
14
+ * @param timeoutMs How long to wait for the key. Defaults to {@link REQUEST_TIMEOUT_MS}.
13
15
  * @throws {@link PhantomApiError} when the public key cannot be fetched.
16
+ * @throws {@link CliError} `request_timeout` when the server does not answer in time, `bad_answer` when it sends a web page.
14
17
  */
15
- export async function checkReceipt(compact, baseUrl) {
16
- const res = await fetch(`${apiBase(baseUrl)}/receipts/key`);
17
- const json = (await res.json().catch(() => ({})));
18
+ export async function checkReceipt(compact, baseUrl, timeoutMs = REQUEST_TIMEOUT_MS) {
19
+ const { res, answer } = await fetchAnswer(`${apiBase(baseUrl)}/receipts/key`, {}, 'GET /receipts/key', timeoutMs);
18
20
  if (!res.ok)
19
- throw apiError(res.status, json);
21
+ throw answerError(res.status, answer);
22
+ if (answer.kind === 'text')
23
+ die('Phantom AI sent a web page instead of its receipt key. Check PHANTOM_BASE_URL, and try again in a minute.', 'bad_answer');
24
+ const json = answer.json;
20
25
  if (!json.signs || !json.public_key_jwk) {
21
26
  return { valid: false, receipt: null, reason: 'This deployment signs no receipts' };
22
27
  }
@@ -45,15 +50,14 @@ export function modelsMatch(requested, served) {
45
50
  return requested.toLowerCase() === served.toLowerCase() || bare(requested) === bare(served);
46
51
  }
47
52
  /** One small priced call to `model`, then a check of the receipt it returns. */
48
- export async function verifyModel(apiKey, model, baseUrl) {
49
- const res = await fetch(`${apiBase(baseUrl)}/chat/completions`, {
53
+ export async function verifyModel(apiKey, model, baseUrl, timeoutMs = REQUEST_TIMEOUT_MS) {
54
+ const { res, answer } = await fetchAnswer(`${apiBase(baseUrl)}/chat/completions`, {
50
55
  method: 'POST',
51
56
  headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
52
57
  body: JSON.stringify({ model, max_tokens: 16, messages: [{ role: 'user', content: 'Reply with ok.' }] }),
53
- });
54
- const json = await res.json().catch(() => ({}));
58
+ }, 'POST /chat/completions', timeoutMs);
55
59
  if (!res.ok)
56
- throw apiError(res.status, json);
60
+ throw answerError(res.status, answer);
57
61
  const compact = res.headers.get('x-phantom-receipt');
58
62
  if (!compact) {
59
63
  return {
@@ -67,7 +71,7 @@ export async function verifyModel(apiKey, model, baseUrl) {
67
71
  reason: 'The response carried no receipt',
68
72
  };
69
73
  }
70
- const check = await checkReceipt(compact, baseUrl);
74
+ const check = await checkReceipt(compact, baseUrl, timeoutMs);
71
75
  const r = check.receipt;
72
76
  return {
73
77
  model_requested: model,
@@ -0,0 +1,149 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import { type SetupAgent, type SetupAgentSpec, type SetupContext, type ProviderPlan } from './shared.mts';
3
+ /** An agent whose model settings live on its own settings screen: setup prints the steps. */
4
+ export declare function manualProvider(where: string, steps: (ctx: SetupContext) => string[], note?: string): NonNullable<SetupAgentSpec['provider']>;
5
+ /** Codex's folder: `$CODEX_HOME`, else `~/.codex`. */
6
+ export declare function codexDir(env: Env, home: string): string;
7
+ /**
8
+ * Codex: `config.toml` in Codex's folder gets a `phantom` model provider at
9
+ * `/codex/v1` that reads the key from PHANTOM_API_KEY (as Vercel's writes a
10
+ * `vercel` provider with `env_key`). phantom also writes the model, and Phantom
11
+ * AI's model list at `/codex/v1/models`, which Codex 0.156 reads only with
12
+ * `[features] api_key_model_discovery`.
13
+ */
14
+ export declare function codexProvider(ctx: SetupContext, off: boolean): ProviderPlan;
15
+ /** Claude Code's folder: `$CLAUDE_CONFIG_DIR`, else `~/.claude`. */
16
+ export declare function claudeDir(env: Env, home: string): string;
17
+ /** The plan behind {@link claudeProvider}. */
18
+ export declare function claudePlan(env: Env, opts: {
19
+ off?: boolean;
20
+ model?: string;
21
+ onPath?: (bin: string) => boolean;
22
+ }): ProviderPlan;
23
+ /** GitHub Copilot CLI's folder: `$COPILOT_HOME`, else `~/.copilot`. */
24
+ export declare function copilotDir(env: Env, home: string): string;
25
+ /** GitHub Copilot CLI: set up by the shell block alone, as Vercel's setup does. Its variables are in {@link SetupAgentSpec.shellEnv}. */
26
+ export declare function copilotProvider(ctx: SetupContext, off: boolean): ProviderPlan;
27
+ /** opencode's config file: `opencode.json` (or `.jsonc`) in `$XDG_CONFIG_HOME/opencode`, else `~/.config/opencode`. */
28
+ export declare function opencodeFile(env: Env, home: string): string;
29
+ /**
30
+ * opencode: a `phantom` provider at `/coding-agent/v1` whose key is
31
+ * `{env:PHANTOM_API_KEY}`. Like Vercel's setup, it pins no model unless
32
+ * `--model` asks; pick `phantom/<model>` in opencode.
33
+ */
34
+ export declare function opencodeProvider(ctx: SetupContext, off: boolean): ProviderPlan;
35
+ /**
36
+ * Continue: `~/.continue/config.yaml` gets a model at `/coding-agent/v1`,
37
+ * first in `models:` so the `cn` CLI starts with it, with the key from
38
+ * `${{ secrets.PHANTOM_API_KEY }}`. Like Vercel's setup it also writes
39
+ * `.onboarding_complete` beside it, so `cn`'s first-run questions don't
40
+ * replace the list.
41
+ */
42
+ export declare function continueProvider(ctx: SetupContext, off: boolean): ProviderPlan;
43
+ /**
44
+ * Goose, as Vercel's setup does it: a custom provider file,
45
+ * `custom_providers/custom_phantom.json` in Goose's folder, at
46
+ * `/coding-agent/v1/chat/completions` with the key from PHANTOM_API_KEY, and
47
+ * GOOSE_PROVIDER and GOOSE_MODEL in Goose's `config.yaml`, which the desktop
48
+ * app reads too.
49
+ */
50
+ export declare function gooseProvider(ctx: SetupContext, off: boolean): ProviderPlan;
51
+ /**
52
+ * Aider, as Vercel's setup does it: `~/.aider.conf.yml` gets
53
+ * `openai-api-base` at `/coding-agent/v1` and the model as `openai/<model>`,
54
+ * `~/.aider.model.metadata.json` and `~/.aider.model.settings.yml` tell Aider
55
+ * the model's context window and edit format, and the key comes from
56
+ * AIDER_OPENAI_API_KEY in the shell block.
57
+ */
58
+ export declare function aiderProvider(ctx: SetupContext, off: boolean): ProviderPlan;
59
+ /**
60
+ * Cline, as Vercel's setup does it: `~/.cline/data/settings/providers.json`
61
+ * (mode 600), which Cline's CLI and editor extension share, gets an OpenAI
62
+ * Compatible provider at `/coding-agent/v1` and is made the one Cline uses.
63
+ * Cline reads its key only from this file, with no variable or command to
64
+ * point it at, so this is the one config phantom writes the key into. After
65
+ * `phantom rotate`, run setup again to update it.
66
+ */
67
+ export declare function clineProvider(ctx: SetupContext, off: boolean): ProviderPlan;
68
+ /** Gemini CLI's folder: `.gemini` in `$GEMINI_CLI_HOME`, else in the home folder. */
69
+ export declare function geminiDir(env: Env, home: string): string;
70
+ /**
71
+ * Gemini CLI speaks Google's API, which Phantom AI serves at `/gemini-cli`.
72
+ * The shell block sets GOOGLE_GEMINI_BASE_URL to it and GEMINI_API_KEY to
73
+ * the Phantom key; `settings.json` in Gemini CLI's folder picks API key
74
+ * sign-in (`security.auth.selectedType`) and the model (`model.name`).
75
+ * `--provider off` takes out a phantom model; the sign-in choice stays, and
76
+ * `phantom setup --restore` puts the file back as it was.
77
+ */
78
+ export declare function geminiProvider(ctx: SetupContext, off: boolean): ProviderPlan;
79
+ /** Crush's config folder: `$CRUSH_GLOBAL_CONFIG`, else `crush` in the config folder. */
80
+ export declare function crushDir(env: Env, home: string): string;
81
+ /**
82
+ * Crush: `crush.json` in Crush's config folder gets a `phantom` provider at
83
+ * `/coding-agent/v1` whose key is `$PHANTOM_API_KEY`, which Crush expands
84
+ * when it loads, and phantom-1 as both its large and small model. Crush 0.99
85
+ * reads this file beside a `crushrc`.
86
+ */
87
+ export declare function crushProvider(ctx: SetupContext, off: boolean): ProviderPlan;
88
+ /** Qwen Code's folder: `$QWEN_HOME`, else `~/.qwen`. */
89
+ export declare function qwenDir(env: Env, home: string): string;
90
+ /**
91
+ * Qwen Code: `settings.json` in its folder gets a model under
92
+ * `modelProviders.openai` at `/coding-agent/v1` that reads its key from
93
+ * PHANTOM_API_KEY (`envKey`), is picked as the model (`model.name`), and the
94
+ * OpenAI-compatible sign-in (`security.auth.selectedType`), so Qwen Code
95
+ * starts without asking. Its other models stay.
96
+ */
97
+ export declare function qwenProvider(ctx: SetupContext, off: boolean): ProviderPlan;
98
+ /** Kilo Code's config file: `kilo.jsonc` (or `kilo.json`) in `$XDG_CONFIG_HOME/kilo`, else `~/.config/kilo`. */
99
+ export declare function kiloFile(env: Env, home: string): string;
100
+ /**
101
+ * Kilo Code's CLI, a fork of opencode: its global config gets the same
102
+ * `phantom` provider opencode does, with the key as `{env:PHANTOM_API_KEY}`,
103
+ * and `phantom/<model>` as the model. Kilo resolves `{env:...}` only in the
104
+ * global file, which is the one written here.
105
+ */
106
+ export declare function kiloProvider(ctx: SetupContext, off: boolean): ProviderPlan;
107
+ /** Kimi Code's folder: `$KIMI_CODE_HOME`, else `~/.kimi-code`. */
108
+ export declare function kimiDir(env: Env, home: string): string;
109
+ /**
110
+ * Kimi Code CLI: `config.toml` in its folder gets a `phantom` provider at
111
+ * `/coding-agent/v1` that reads its key from PHANTOM_API_KEY
112
+ * (`api_key_env`), a `phantom/<model>` model, and that model as
113
+ * `default_model`. Each run starts from the file without phantom's lines, so
114
+ * a new `--model` replaces the old one.
115
+ */
116
+ export declare function kimiProvider(ctx: SetupContext, off: boolean): ProviderPlan;
117
+ /**
118
+ * Factory's Droid: `~/.factory/settings.json` gets a custom model at
119
+ * `/coding-agent/v1` (chat completions) with the key as `${PHANTOM_API_KEY}`,
120
+ * which Droid expands, and that model as `model`. Droid names a custom
121
+ * model by its place in `customModels`, so phantom's goes last, or stays
122
+ * where it was, and the user's own keep their names.
123
+ */
124
+ export declare function droidProvider(ctx: SetupContext, off: boolean): ProviderPlan;
125
+ /**
126
+ * Mistral Vibe: `~/.vibe/config.toml` gets a `phantom` provider at
127
+ * `/coding-agent/v1` that reads its key from PHANTOM_API_KEY
128
+ * (`api_key_env_var`), a model on it, and that model as `active_model`.
129
+ * Providers and models are lists of tables (`[[providers]]`), so phantom's
130
+ * go at the end as marked lines, which `--provider off` takes out again.
131
+ */
132
+ export declare function vibeProvider(ctx: SetupContext, off: boolean): ProviderPlan;
133
+ /**
134
+ * Zed's agent panel: `settings.json` in Zed's config folder gets an OpenAI
135
+ * compatible provider named `phantom` at `/coding-agent/v1`, and its model
136
+ * as the agent's default. Zed reads the key for a provider named `phantom`
137
+ * from PHANTOM_API_KEY by itself, so no key goes in the file.
138
+ */
139
+ export declare function zedProvider(ctx: SetupContext, off: boolean): ProviderPlan;
140
+ /**
141
+ * The agents `phantom setup` knows, in the order setup runs them. Adding an agent
142
+ * is one entry here and its name in {@link SetupAgent}: help, errors and
143
+ * `--agent` read their names from this list.
144
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
145
+ */
146
+ export declare const SETUP_AGENTS: Record<SetupAgent, SetupAgentSpec>;
147
+ export declare const SETUP_NAMES: SetupAgent[];
148
+ /** `a, b or c`. */
149
+ export declare function orList(items: string[]): string;
@@ -4,7 +4,8 @@ import { existsSync } from 'node:fs';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { die } from "../core/errors.mjs";
6
6
  import { resolveApiKey } from "../keys/saved.mjs";
7
- import { SETUP_MODEL, agentBaseUrl, readText, configHome, onPath, phantomCommand, offResult, unreadable, SETUP_MARK, SETUP_CONTEXT_WINDOW, } from "./shared.mjs";
7
+ import { SETUP_MODEL, agentBaseUrl, readText, configHome, onPath, phantomCommand, offResult, unreadable, SETUP_MARK, SETUP_CONTEXT_WINDOW, claudeModelName, } from "./shared.mjs";
8
+ import { readJsonWas, restoreJsonChanges, trackJsonChanges } from "./was.mjs";
8
9
  import { jsonObject, jsonEdit, tomlSet, tomlRemoveOurs, yamlSetTop, yamlAddModel, yamlRemoveOurs } from "./editors.mjs";
9
10
  /** The most output a model call may ask for, for agents that need a number. */
10
11
  const SETUP_OUTPUT_TOKENS = 32_000;
@@ -13,6 +14,22 @@ function unlessEmpty(file, after) {
13
14
  const left = jsonObject(file, after);
14
15
  return Object.keys(left).every((k) => k === '$schema') ? '' : after;
15
16
  }
17
+ /**
18
+ * The edit that writes `changes` to a JSON settings file, with a record of what the keys in `tracked` held
19
+ * before ({@link trackJsonChanges}), so `--provider off` can put those values back.
20
+ */
21
+ function jsonOn(env, file, text, changes, tracked = changes.map(([p]) => p)) {
22
+ const was = trackJsonChanges(jsonObject(file, text), readJsonWas(env, file), changes, tracked);
23
+ return { file, after: jsonEdit(file, text, changes), was };
24
+ }
25
+ /**
26
+ * The text of a JSON settings file after `--provider off`: `removals` (what the agent's own off step finds that
27
+ * looks like phantom's) with each recorded key put back ({@link restoreJsonChanges}).
28
+ */
29
+ function jsonOffText(env, file, text, removals, tidy = []) {
30
+ const record = readJsonWas(env, file);
31
+ return jsonEdit(file, text, restoreJsonChanges(jsonObject(file, text), record, removals, tidy));
32
+ }
16
33
  // ── Manual Provider Helper ───────────────────────────────────────────────────
17
34
  /** An agent whose model settings live on its own settings screen: setup prints the steps. */
18
35
  export function manualProvider(where, steps, note) {
@@ -68,18 +85,12 @@ export function claudePlan(env, opts) {
68
85
  const ours = typeof settings.apiKeyHelper === 'string' && /(?:pai|phantom).* key show$/.test(settings.apiKeyHelper);
69
86
  const vars = { ...(settings.env ?? {}) };
70
87
  if (opts.off) {
71
- const changes = [];
72
- if (ours) {
73
- changes.push([['apiKeyHelper'], undefined]);
74
- const mine = ['ANTHROPIC_BASE_URL', 'ENABLE_TOOL_SEARCH', 'ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY', ...(vars.ANTHROPIC_API_KEY === '' ? ['ANTHROPIC_API_KEY'] : [])];
75
- if (Object.keys(vars).every((k) => mine.includes(k)))
76
- changes.push([['env'], undefined]);
77
- else
78
- for (const k of mine)
79
- changes.push([['env', k], undefined]);
80
- }
88
+ const mine = ['ANTHROPIC_BASE_URL', 'ENABLE_TOOL_SEARCH', 'ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY', ...(vars.ANTHROPIC_API_KEY === '' ? ['ANTHROPIC_API_KEY'] : [])];
89
+ // Without a record (setup from an older phantom) every key phantom writes is removed; with one,
90
+ // each key goes back to what the user had.
91
+ const removals = [[['apiKeyHelper'], undefined], ...mine.filter((k) => k in vars).map((k) => [['env', k], undefined])];
81
92
  return {
82
- edits: text === null || !ours ? [] : [{ file, after: jsonEdit(file, text, changes) }],
93
+ edits: text === null || !ours ? [] : [{ file, after: jsonOffText(env, file, text, removals, [['env']]), was: null }],
83
94
  result: { settings: file, on: false, warnings: ours ? [] : ['Claude Code was not set to Phantom AI by phantom; nothing changed'] },
84
95
  };
85
96
  }
@@ -96,17 +107,18 @@ export function claudePlan(env, opts) {
96
107
  ENABLE_TOOL_SEARCH: 'true',
97
108
  CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: '1',
98
109
  // phantom-1 unless a model is named, as Codex gets: it runs free until there is credit.
99
- ANTHROPIC_MODEL: opts.model ?? 'claude-code/phantom-1',
100
- // Claude Code's background calls (titles, summaries) and its Explore agent use the
101
- // haiku model. Through phantom-1 they run on Standard instead of Claude Haiku.
102
- ANTHROPIC_DEFAULT_HAIKU_MODEL: 'claude-code/phantom-1',
110
+ ANTHROPIC_MODEL: claudeModelName(opts.model ?? SETUP_MODEL),
111
+ // Claude Code's background calls (titles, summaries) and its Explore agent, which reads the
112
+ // user's code, use the haiku model. It follows the chosen model, so a zero data retention
113
+ // choice (phantom-1:zdr) covers them too. Through phantom-1 they run on Standard instead of Claude Haiku.
114
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: claudeModelName(opts.model ?? SETUP_MODEL),
103
115
  };
104
116
  const changes = [[['apiKeyHelper'], `${phantomCommand(opts.onPath ?? onPath)} key show`], ...Object.entries(set).map(([k, v]) => [['env', k], v])];
105
117
  // A token outranks apiKeyHelper, and would send a non-Phantom key.
106
118
  const warnings = env.ANTHROPIC_AUTH_TOKEN ? ['ANTHROPIC_AUTH_TOKEN is set in this shell and overrides the Phantom key; unset it before running claude'] : [];
107
119
  if (opts.model?.replace(/^claude-code\//, '') === 'auto')
108
120
  warnings.push('auto runs what the key\'s route policy picks; set one with: phantom route set --models a,b');
109
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: baseUrl, model: set.ANTHROPIC_MODEL ?? vars.ANTHROPIC_MODEL, warnings } };
121
+ return { edits: [jsonOn(env, file, text, changes)], result: { settings: file, on: true, base_url: baseUrl, model: set.ANTHROPIC_MODEL ?? vars.ANTHROPIC_MODEL, warnings } };
110
122
  }
111
123
  // ── Copilot ──────────────────────────────────────────────────────────────────
112
124
  /** GitHub Copilot CLI's folder: `$COPILOT_HOME`, else `~/.copilot`. */
@@ -148,9 +160,7 @@ export function opencodeProvider(ctx, off) {
148
160
  const changes = [Object.keys(config.provider ?? {}).length === 1 ? [['provider'], undefined] : [['provider', 'phantom'], undefined]];
149
161
  if (typeof config.model === 'string' && config.model.startsWith('phantom/'))
150
162
  changes.push([['model'], undefined]);
151
- const left = jsonObject(file, ours ? jsonEdit(file, text, changes) : text);
152
- const empty = Object.keys(left).every((k) => k === '$schema');
153
- return offResult('opencode', file, text, ours ? (empty ? '' : jsonEdit(file, text, changes)) : text);
163
+ return offResult('opencode', file, text, ours ? unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)) : text, true);
154
164
  }
155
165
  const base = agentBaseUrl(ctx.env, 'coding-agent');
156
166
  const model = ctx.model ?? SETUP_MODEL;
@@ -163,7 +173,7 @@ export function opencodeProvider(ctx, off) {
163
173
  ...(ctx.model ? [[['model'], `phantom/${ctx.model}`]] : []),
164
174
  ];
165
175
  return {
166
- edits: [{ file, after: jsonEdit(file, text, changes) }],
176
+ edits: [jsonOn(ctx.env, file, text, changes, [['model']])],
167
177
  result: { settings: file, on: true, base_url: base, ...(ctx.model ? { model: `phantom/${ctx.model}` } : {}), warnings: ctx.model ? [] : [`Pick phantom/${model} with /models in opencode`] },
168
178
  };
169
179
  }
@@ -293,7 +303,7 @@ export function clineProvider(ctx, off) {
293
303
  const changes = [[['providers', 'openai-compatible'], undefined]];
294
304
  if (data.lastUsedProvider === 'openai-compatible')
295
305
  changes.push([['lastUsedProvider'], undefined]);
296
- return offResult('Cline', file, text, ours ? jsonEdit(file, text, changes) : text);
306
+ return offResult('Cline', file, text, ours ? jsonOffText(ctx.env, file, text, changes) : text, true);
297
307
  }
298
308
  if (current && !ours)
299
309
  unreadable(file, `already has an OpenAI Compatible provider at ${current.settings?.baseUrl ?? 'another address'}, which phantom leaves alone`);
@@ -312,7 +322,7 @@ export function clineProvider(ctx, off) {
312
322
  [['providers', 'openai-compatible'], entry],
313
323
  ];
314
324
  return {
315
- edits: [{ file, after: jsonEdit(file, text, changes), mode: 0o600 }],
325
+ edits: [{ ...jsonOn(ctx.env, file, text, changes, [['lastUsedProvider']]), mode: 0o600 }],
316
326
  result: {
317
327
  settings: file,
318
328
  on: true,
@@ -342,7 +352,9 @@ export function geminiProvider(ctx, off) {
342
352
  if (off) {
343
353
  const ours = typeof settings.model?.name === 'string' && settings.model.name.startsWith('phantom-');
344
354
  const alone = Object.keys(settings.model ?? {}).length === 1;
345
- return offResult('Gemini CLI', file, text, ours ? jsonEdit(file, text, [[alone ? ['model'] : ['model', 'name'], undefined]]) : text);
355
+ const removals = ours ? [[alone ? ['model'] : ['model', 'name'], undefined]] : [];
356
+ // With a record the sign-in choice goes back too; without one (older setup) it stays, as before.
357
+ return offResult('Gemini CLI', file, text, text === null ? null : jsonOffText(ctx.env, file, text, removals), true);
346
358
  }
347
359
  const model = ctx.model ?? SETUP_MODEL;
348
360
  const changes = [
@@ -350,7 +362,7 @@ export function geminiProvider(ctx, off) {
350
362
  [['model', 'name'], model],
351
363
  ];
352
364
  return {
353
- edits: [{ file, after: jsonEdit(file, text, changes) }],
365
+ edits: [jsonOn(ctx.env, file, text, changes)],
354
366
  result: {
355
367
  settings: file,
356
368
  on: true,
@@ -386,7 +398,7 @@ export function crushProvider(ctx, off) {
386
398
  else
387
399
  for (const k of mine)
388
400
  changes.push([['models', k], undefined]);
389
- return offResult('Crush', file, text, unlessEmpty(file, jsonEdit(file, text, changes)));
401
+ return offResult('Crush', file, text, unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)), true);
390
402
  }
391
403
  const base = agentBaseUrl(ctx.env, 'coding-agent');
392
404
  const model = ctx.model ?? SETUP_MODEL;
@@ -404,7 +416,7 @@ export function crushProvider(ctx, off) {
404
416
  ],
405
417
  ...sizes.map((size) => [['models', size], { provider: 'phantom', model }]),
406
418
  ];
407
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: base, model, warnings: [] } };
419
+ return { edits: [jsonOn(ctx.env, file, text, changes, sizes.map((size) => ['models', size]))], result: { settings: file, on: true, base_url: base, model, warnings: [] } };
408
420
  }
409
421
  // ── Qwen Code ────────────────────────────────────────────────────────────────
410
422
  /** Qwen Code's folder: `$QWEN_HOME`, else `~/.qwen`. */
@@ -439,7 +451,7 @@ export function qwenProvider(ctx, off) {
439
451
  changes.push(Object.keys(config.modelProviders ?? {}).length === 1 ? [['modelProviders'], undefined] : [['modelProviders', 'openai'], undefined]);
440
452
  if (mineIds.includes(config.model?.name))
441
453
  changes.push(Object.keys(config.model ?? {}).length === 1 ? [['model'], undefined] : [['model', 'name'], undefined]);
442
- return offResult('Qwen Code', file, text, unlessEmpty(file, jsonEdit(file, text, changes)));
454
+ return offResult('Qwen Code', file, text, unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)), true);
443
455
  }
444
456
  const model = ctx.model ?? SETUP_MODEL;
445
457
  const entry = { id: model, name: `Phantom AI ${model}`, baseUrl: base, envKey: 'PHANTOM_API_KEY', generationConfig: { contextWindowSize: SETUP_CONTEXT_WINDOW } };
@@ -448,7 +460,8 @@ export function qwenProvider(ctx, off) {
448
460
  [['security', 'auth', 'selectedType'], 'openai'],
449
461
  [['model', 'name'], model],
450
462
  ];
451
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: base, model, warnings: [] } };
463
+ const tracked = [['security', 'auth', 'selectedType'], ['model', 'name']];
464
+ return { edits: [jsonOn(ctx.env, file, text, changes, tracked)], result: { settings: file, on: true, base_url: base, model, warnings: [] } };
452
465
  }
453
466
  // ── Kilo Code ────────────────────────────────────────────────────────────────
454
467
  /** Kilo Code's config file: `kilo.jsonc` (or `kilo.json`) in `$XDG_CONFIG_HOME/kilo`, else `~/.config/kilo`. */
@@ -472,7 +485,7 @@ export function kiloProvider(ctx, off) {
472
485
  const changes = [Object.keys(config.provider).length === 1 ? [['provider'], undefined] : [['provider', 'phantom'], undefined]];
473
486
  if (typeof config.model === 'string' && config.model.startsWith('phantom/'))
474
487
  changes.push([['model'], undefined]);
475
- return offResult('Kilo Code', file, text, unlessEmpty(file, jsonEdit(file, text, changes)));
488
+ return offResult('Kilo Code', file, text, unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)), true);
476
489
  }
477
490
  const base = agentBaseUrl(ctx.env, 'coding-agent');
478
491
  const model = ctx.model ?? SETUP_MODEL;
@@ -490,7 +503,7 @@ export function kiloProvider(ctx, off) {
490
503
  ],
491
504
  [['model'], `phantom/${model}`],
492
505
  ];
493
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: base, model: `phantom/${model}`, warnings: [] } };
506
+ return { edits: [jsonOn(ctx.env, file, text, changes, [['model']])], result: { settings: file, on: true, base_url: base, model: `phantom/${model}`, warnings: [] } };
494
507
  }
495
508
  // ── Kimi Code ────────────────────────────────────────────────────────────────
496
509
  /** Kimi Code's folder: `$KIMI_CODE_HOME`, else `~/.kimi-code`. */
@@ -548,7 +561,7 @@ export function droidProvider(ctx, off) {
548
561
  const changes = [[['customModels'], rest.length ? rest : undefined]];
549
562
  if (mine(config.model))
550
563
  changes.push([['model'], undefined]);
551
- return offResult('Droid', file, text, unlessEmpty(file, jsonEdit(file, text, changes)));
564
+ return offResult('Droid', file, text, unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)), true);
552
565
  }
553
566
  const model = ctx.model ?? SETUP_MODEL;
554
567
  const entry = { model, displayName: DROID_NAME, baseUrl: base, apiKey: '${PHANTOM_API_KEY}', provider: 'generic-chat-completion-api', maxOutputTokens: SETUP_OUTPUT_TOKENS };
@@ -560,7 +573,7 @@ export function droidProvider(ctx, off) {
560
573
  [['customModels'], next],
561
574
  [['model'], id],
562
575
  ];
563
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: base, model: id, warnings: [] } };
576
+ return { edits: [jsonOn(ctx.env, file, text, changes, [['model']])], result: { settings: file, on: true, base_url: base, model: id, warnings: [] } };
564
577
  }
565
578
  // ── Mistral Vibe ─────────────────────────────────────────────────────────────
566
579
  /**
@@ -612,7 +625,7 @@ export function zedProvider(ctx, off) {
612
625
  const changes = [[['language_models', 'openai_compatible', 'phantom'], undefined]];
613
626
  if (config.agent?.default_model?.provider === 'phantom')
614
627
  changes.push([['agent', 'default_model'], undefined]);
615
- return offResult('Zed', file, text, jsonEdit(file, text, changes));
628
+ return offResult('Zed', file, text, jsonOffText(ctx.env, file, text, changes, [['language_models', 'openai_compatible']]), true);
616
629
  }
617
630
  const base = agentBaseUrl(ctx.env, 'coding-agent');
618
631
  const model = ctx.model ?? SETUP_MODEL;
@@ -624,7 +637,7 @@ export function zedProvider(ctx, off) {
624
637
  [['agent', 'default_model'], { provider: 'phantom', model }],
625
638
  ];
626
639
  return {
627
- edits: [{ file, after: jsonEdit(file, text, changes) }],
640
+ edits: [jsonOn(ctx.env, file, text, changes, [['agent', 'default_model']])],
628
641
  result: { settings: file, on: true, base_url: base, model, warnings: ['Zed reads PHANTOM_API_KEY from your login shell; quit and reopen Zed'] },
629
642
  };
630
643
  }