@phantomcodes/cli 1.4.4 → 1.5.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.
package/README.md CHANGED
@@ -28,7 +28,7 @@ It also installs the `phantom-ai` skill, a file that teaches the agent the phant
28
28
  - `phantom setup --dry-run` shows the changes and writes nothing.
29
29
  - `--no-shell`, or unticking "Your shell" in the checklist, leaves your shell startup file alone. Setup then prints the lines to add yourself.
30
30
  - `--limit 20` caps what the key can spend each month, and `--limit none` removes the cap. At a terminal, setup asks once when the key has no cap.
31
- - `phantom setup --restore` puts back each file setup changed, from the copies it kept.
31
+ - `phantom setup --restore` puts back each file setup changed, from the copies it kept. A file you edited after setup keeps your edits: restore takes out only Phantom's own lines and keys, and leaves the copy beside the file. It exits 1 only when a file could not be undone.
32
32
  - `phantom setup --provider off` takes Phantom out of an agent and keeps the rest of its settings. In JSON settings files (Claude Code, Qwen Code, Gemini CLI and others), setup records each value it replaces and puts it back.
33
33
 
34
34
  Claude Code's background calls (titles, summaries and its Explore agent) run on the model you chose with `phantom models`, so picking `phantom-1:zdr` covers them too.
@@ -127,7 +127,7 @@ Your key's lineup sets the model phantom-1 runs in each tier, and a fallback mod
127
127
 
128
128
  ```bash
129
129
  phantom lineup --table
130
- phantom lineup set --frontier <model> --economy-fallback <model>
130
+ phantom lineup set --frontier <model> --standard-fallback <model>
131
131
  phantom lineup reset
132
132
  ```
133
133
 
@@ -179,10 +179,9 @@ export const COMMANDS = [
179
179
  group: 'Routing', summary: 'the model phantom-1 runs in each tier',
180
180
  help: ` lineup [get] the model phantom-1 runs in each tier, and the
181
181
  models you can pick from
182
- lineup set --economy <model> pick the model for a tier; "default" puts the
183
- [--standard <model>] tier back to its default
184
- [--frontier <model>]
185
- [--economy-fallback <model>] [--standard-fallback <model>]
182
+ lineup set --standard <model> pick the model for a tier; "default" puts the
183
+ [--frontier <model>] tier back to its default
184
+ [--standard-fallback <model>]
186
185
  [--frontier-fallback <model>]
187
186
  the model to try when a tier's model fails
188
187
  lineup reset every tier back to its default`,
@@ -224,14 +223,18 @@ export const COMMANDS = [
224
223
  --provider off takes phantom's settings out and
225
224
  puts back what they replaced
226
225
  setup --restore [--agent <name>] put back the files setup changed, from the
227
- .phantom.bak copies it kept`,
226
+ .phantom.bak copies it kept. A file you
227
+ edited since keeps your edits: only
228
+ Phantom's own lines come out`,
228
229
  },
229
230
  {
230
231
  name: 'verify', advanced: true, handler: verifyCommand, keyless: ['--receipt'],
231
232
  group: 'More', summary: 'check a signed receipt',
232
233
  help: ` verify --model <id> make one small call and check that its signed
233
234
  receipt names the model you asked for (costs a
234
- fraction of a cent)
235
+ fraction of a cent). For phantom-1, phantom-1:free,
236
+ phantom-1:zdr or auto it checks the receipt's
237
+ requested model, since the model that ran varies
235
238
  verify --receipt <receipt> check a receipt you already have`,
236
239
  },
237
240
  ];
package/dist/cli/run.mjs CHANGED
@@ -23,6 +23,8 @@ import { LEGACY_SETUP_HINT, legacySetupFound } from "../setup/legacy.mjs";
23
23
  */
24
24
  /** Retired flags, accepted so the command can say what replaced them, and never suggested for a typo. */
25
25
  const RETIRED_FLAGS = ['pay', 'mpp'];
26
+ /** Retired flags of one command: it refuses them with its own message, so they get past the unknown-flag check. */
27
+ const RETIRED_COMMAND_FLAGS = { lineup: ['economy', 'economy-fallback'] };
26
28
  /** The flags every command takes, and the retired ones. */
27
29
  const EVERY_COMMAND_FLAGS = ['table', 'json', 'help', 'all', 'version', 'mcp', ...RETIRED_FLAGS];
28
30
  /**
@@ -34,7 +36,7 @@ const EVERY_COMMAND_FLAGS = ['table', 'json', 'help', 'all', 'version', 'mcp', .
34
36
  */
35
37
  function flagsOf(command, subcommand) {
36
38
  const helps = [command.help, COMMANDS.find((c) => c.name === subcommand)?.help ?? ''].join('\n');
37
- return new Set([...[...helps.matchAll(/--([a-z][a-z0-9-]*)/g)].map((m) => m[1]), ...EVERY_COMMAND_FLAGS]);
39
+ return new Set([...[...helps.matchAll(/--([a-z][a-z0-9-]*)/g)].map((m) => m[1]), ...EVERY_COMMAND_FLAGS, ...(RETIRED_COMMAND_FLAGS[command.name] ?? [])]);
38
40
  }
39
41
  export async function run(argv = process.argv.slice(2), env = process.env, io = {
40
42
  stdout: (s) => process.stdout.write(s),
@@ -111,7 +113,7 @@ export async function run(argv = process.argv.slice(2), env = process.env, io =
111
113
  for (const name of passesArgs ? [] : Object.keys(ownFlags)) {
112
114
  if (known.has(name))
113
115
  continue;
114
- const guess = closestCommand(name, [...known].filter((flag) => !RETIRED_FLAGS.includes(flag)));
116
+ const guess = closestCommand(name, [...known].filter((flag) => !RETIRED_FLAGS.includes(flag) && !(RETIRED_COMMAND_FLAGS[argv[0]] ?? []).includes(flag)));
115
117
  die(`Unknown flag --${name} for phantom ${argv[0]}.${guess ? ` Did you mean --${guess}?` : ''} See phantom ${argv[0]} --help.`, 'unknown_flag');
116
118
  }
117
119
  // A person at a terminal reads each command's screen; a pipe (scripts, agents) or --json gets JSON.
@@ -92,11 +92,11 @@ export type LineupView = {
92
92
  lineup: (Record<string, string | undefined> & {
93
93
  fallbacks?: Record<string, string | undefined>;
94
94
  }) | null;
95
- tiers: Record<'economy' | 'standard' | 'frontier', {
95
+ tiers: Record<'standard' | 'frontier', {
96
96
  model: string;
97
97
  name: string;
98
98
  }>;
99
- choices?: Record<'economy' | 'standard' | 'frontier', Array<{
99
+ choices?: Record<'standard' | 'frontier', Array<{
100
100
  model: string;
101
101
  name: string;
102
102
  input_per_m: number | null;
@@ -107,7 +107,6 @@ export type LineupView = {
107
107
  };
108
108
  /** What each tier is for, in a few words. */
109
109
  export declare const TIER_ABOUT: {
110
- readonly economy: "phantom-1:free only; paid calls skip it";
111
110
  readonly standard: "where every task starts";
112
111
  readonly frontier: "hard steps: a failed try, an image";
113
112
  };
@@ -229,7 +229,6 @@ export function routeTestScreen(t, style = {}) {
229
229
  }
230
230
  /** What each tier is for, in a few words. */
231
231
  export const TIER_ABOUT = {
232
- economy: 'phantom-1:free only; paid calls skip it',
233
232
  standard: 'where every task starts',
234
233
  frontier: 'hard steps: a failed try, an image',
235
234
  };
@@ -238,7 +237,7 @@ export function lineupScreen(l, style = {}) {
238
237
  const p = paint(style.env ?? {}, Boolean(style.color));
239
238
  const w = ruleWidth(style);
240
239
  const lines = ['', ...caption(p, w, 'LINEUP', p.dim('the model phantom-1 runs in each tier'))];
241
- for (const tier of ['economy', 'standard', 'frontier']) {
240
+ for (const tier of ['standard', 'frontier']) {
242
241
  const mine = Boolean(l.lineup?.[tier]);
243
242
  const fallback = l.lineup?.fallbacks?.[tier];
244
243
  lines.push(` ${p.bold(tier.toUpperCase().padEnd(10))}${l.tiers[tier].model.padEnd(36)}${mine ? p.lime('your pick') : p.dim('default')}`);
@@ -133,7 +133,9 @@ export function apiError(status, json) {
133
133
  // Some routes answer { error: <words> }; a detail, when one is sent, reads better.
134
134
  const detail = json.detail;
135
135
  msg = typeof detail === 'string' && detail ? detail : err;
136
- code = err;
136
+ // A code word such as `invalid_key` is the code. A sentence is the message only: its code is made from
137
+ // the status, so the dim detail line under the message doesn't repeat it.
138
+ code = /^[a-z][a-z0-9_]*$/.test(err) ? err : `http_${status}`;
137
139
  }
138
140
  else if (typeof json.detail === 'string') {
139
141
  // The purchase routes answer errors as { detail }, some with a { code }.
@@ -1,9 +1,9 @@
1
1
  import path from 'node:path';
2
- import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { chmodSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { randomBytes } from 'node:crypto';
5
5
  import { die } from "./errors.mjs";
6
- import { stateDir } from "./state.mjs";
6
+ import { makePrivateFolder, stateDir } from "./state.mjs";
7
7
  /**
8
8
  * On macOS, saved keys and wallets live in the login Keychain rather than in
9
9
  * files. The file stays, holding only a pointer (`pai-keychain:<id>`), so
@@ -54,7 +54,8 @@ function keychainId(file) {
54
54
  return raw.startsWith(KEYCHAIN_POINTER) ? raw.slice(KEYCHAIN_POINTER.length) : null;
55
55
  }
56
56
  export function writeSecret(env, file, value, opts = {}) {
57
- mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
57
+ // A folder an older install made at 755 is tightened too, not only a new one.
58
+ makePrivateFolder(env, path.dirname(file));
58
59
  let contents = value;
59
60
  if (keychainOn(env)) {
60
61
  const id = keychainId(file) ?? randomBytes(12).toString('hex');
@@ -1,3 +1,12 @@
1
1
  /** Environment variables, as `process.env` holds them. */
2
2
  export type Env = Record<string, string | undefined>;
3
3
  export declare function stateDir(env: Env): string;
4
+ /**
5
+ * Makes `folder` exist and be private to this user (mode 700), and the same for each folder between
6
+ * the state folder and it, such as `keys/`. Folders made before 1.4.2 were mode 755, and `mkdir`'s
7
+ * mode does nothing to a folder that is already there, so it is set here every time a secret is written.
8
+ *
9
+ * Only the CLI's own folders change. The folders above the state folder are the user's, and a
10
+ * `folder` outside the state folder is left as it is.
11
+ */
12
+ export declare function makePrivateFolder(env: Env, folder: string): void;
@@ -1,7 +1,29 @@
1
1
  import path from 'node:path';
2
2
  import os from 'node:os';
3
+ import { chmodSync, mkdirSync } from 'node:fs';
3
4
  // Kept at the name the CLI was first published under, so saved keys and
4
5
  // wallets survive the rename.
5
6
  export function stateDir(env) {
6
7
  return env.PHANTOM_STATE_DIR || path.join(os.homedir(), '.config', 'phantom-key');
7
8
  }
9
+ /**
10
+ * Makes `folder` exist and be private to this user (mode 700), and the same for each folder between
11
+ * the state folder and it, such as `keys/`. Folders made before 1.4.2 were mode 755, and `mkdir`'s
12
+ * mode does nothing to a folder that is already there, so it is set here every time a secret is written.
13
+ *
14
+ * Only the CLI's own folders change. The folders above the state folder are the user's, and a
15
+ * `folder` outside the state folder is left as it is.
16
+ */
17
+ export function makePrivateFolder(env, folder) {
18
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
19
+ const state = path.resolve(stateDir(env));
20
+ const below = path.relative(state, path.resolve(folder));
21
+ if (below.startsWith('..') || path.isAbsolute(below))
22
+ return;
23
+ let current = state;
24
+ chmodSync(current, 0o700);
25
+ for (const part of below.split(path.sep).filter(Boolean)) {
26
+ current = path.join(current, part);
27
+ chmodSync(current, 0o700);
28
+ }
29
+ }
@@ -1,2 +1,2 @@
1
1
  /** This release of phantom. `npm version` keeps it equal to the version in package.json. */
2
- export declare const VERSION = "1.4.4";
2
+ export declare const VERSION = "1.5.0";
@@ -1,2 +1,2 @@
1
1
  /** This release of phantom. `npm version` keeps it equal to the version in package.json. */
2
- export const VERSION = '1.4.4';
2
+ export const VERSION = '1.5.0';
@@ -6,7 +6,7 @@ export type Job = (typeof JOBS)[number][0];
6
6
  export type ChatModel = {
7
7
  /** Model id. */
8
8
  id: string;
9
- /** economy, standard or frontier. */
9
+ /** standard, frontier or free (phantom-1:free's models). */
10
10
  tier: string;
11
11
  /** True when it costs $0. */
12
12
  free: boolean;
@@ -33,7 +33,7 @@ export async function getModels(baseUrl, apiKey = '') {
33
33
  return Boolean(r.jobs.vision) || takesImages.has(r.id);
34
34
  return Boolean(r.jobs[job]);
35
35
  });
36
- const chat = r.models.map((m) => ({ id: m.id, tier: m.tier, free: m.pricing.prompt === 0 && m.pricing.completion === 0 }));
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
37
  return { id: r.id, name: r.name, description: r.description, chat, jobs: r.jobs, can };
38
38
  });
39
39
  }
@@ -40,8 +40,15 @@ export type VerifyModelResult = {
40
40
  model_requested: string;
41
41
  /** The model the receipt says answered. null when there was no readable receipt. */
42
42
  model_served: string | null;
43
- /** True when the signature is valid and the served model matches the one asked for ({@link modelsMatch}). */
43
+ /**
44
+ * True when the signature is valid and the model matches the one asked for.
45
+ * For an ordinary model id, `model_served` is compared ({@link modelsMatch}).
46
+ * For a Phantom router id, the receipt's requested model is compared, because
47
+ * the served model is whatever the router picked.
48
+ */
44
49
  match: boolean;
50
+ /** Which receipt field `match` compared with `model_requested`. */
51
+ compared_with: 'model_served' | 'model_requested';
45
52
  /** True when the receipt's signature matches Phantom AI's published key. */
46
53
  signature_valid: boolean;
47
54
  /** What the call cost, in USD. null without a receipt. */
@@ -65,3 +72,5 @@ export declare function checkReceipt(compact: string, baseUrl?: string, timeoutM
65
72
  export declare function modelsMatch(requested: string, served: string): boolean;
66
73
  /** One small priced call to `model`, then a check of the receipt it returns. */
67
74
  export declare function verifyModel(apiKey: string, model: string, baseUrl?: string, timeoutMs?: number): Promise<VerifyModelResult>;
75
+ /** True when `model` is one of Phantom's routers (`phantom-1`, `phantom-1:free`, `phantom-1:zdr`, `auto`), in any case. */
76
+ export declare function isPhantomRouter(model: string): boolean;
@@ -64,6 +64,7 @@ export async function verifyModel(apiKey, model, baseUrl, timeoutMs = REQUEST_TI
64
64
  model_requested: model,
65
65
  model_served: null,
66
66
  match: false,
67
+ compared_with: isPhantomRouter(model) ? 'model_requested' : 'model_served',
67
68
  signature_valid: false,
68
69
  cost_usd: null,
69
70
  request_id: null,
@@ -73,14 +74,41 @@ export async function verifyModel(apiKey, model, baseUrl, timeoutMs = REQUEST_TI
73
74
  }
74
75
  const check = await checkReceipt(compact, baseUrl, timeoutMs);
75
76
  const r = check.receipt;
77
+ const routerCheck = isPhantomRouter(model) ? checkRouterRequest(model, r?.model_requested) : null;
76
78
  return {
77
79
  model_requested: model,
78
80
  model_served: r?.model_served ?? null,
79
- match: check.valid && r !== null && modelsMatch(model, r.model_served),
81
+ match: check.valid && r !== null && (routerCheck ? routerCheck.match : modelsMatch(model, r.model_served)),
82
+ compared_with: routerCheck?.compared_with ?? 'model_served',
80
83
  signature_valid: check.valid,
81
84
  cost_usd: r ? r.cost_micro_usd / 1_000_000 : null,
82
85
  request_id: r?.request_id ?? null,
83
86
  receipt: compact,
84
- ...(check.reason ? { reason: check.reason } : {}),
87
+ // A failed signature is the first thing to fix, so its reason comes before a router note.
88
+ ...(check.reason ? { reason: check.reason } : routerCheck?.reason ? { reason: routerCheck.reason } : {}),
85
89
  };
86
90
  }
91
+ /** The ids of Phantom's routers: names that pick a model for each request, so no upstream model ever has them as its own id. */
92
+ const PHANTOM_ROUTERS = ['phantom-1', 'phantom-1:free', 'phantom-1:zdr', 'auto'];
93
+ /** True when `model` is one of Phantom's routers (`phantom-1`, `phantom-1:free`, `phantom-1:zdr`, `auto`), in any case. */
94
+ export function isPhantomRouter(model) {
95
+ return PHANTOM_ROUTERS.includes(model.toLowerCase());
96
+ }
97
+ /**
98
+ * Checks a router id against what the receipt says was requested. `model_served`
99
+ * is the model the upstream ran, such as `anthropic/claude-sonnet-5.5`, and
100
+ * never a router id, so it can't be the comparison here. A receipt with no
101
+ * requested model leaves nothing to compare, and says so.
102
+ */
103
+ function checkRouterRequest(router, receiptRequested) {
104
+ if (typeof receiptRequested !== 'string' || !receiptRequested) {
105
+ return {
106
+ match: false,
107
+ compared_with: 'model_served',
108
+ reason: `${router} is a router, so it can't be checked against model_served, which is the model the upstream ran. This receipt names no requested model.`,
109
+ };
110
+ }
111
+ if (receiptRequested.toLowerCase() === router.toLowerCase())
112
+ return { match: true, compared_with: 'model_requested' };
113
+ return { match: false, compared_with: 'model_requested', reason: `The receipt says the request was for '${receiptRequested}', not '${router}'.` };
114
+ }
@@ -12,9 +12,11 @@ export declare function lineDiff(before: string | null, after: string | null): s
12
12
  /** Whether setup has written anything on this computer that undo could put back: it keeps a record of each file. */
13
13
  export declare function isSetUp(env: Env): boolean;
14
14
  /**
15
- * Writes a plan from {@link planSetup}. Before it edits a file it copies it
16
- * to `<file>.phantom.bak`, unless the file is still as phantom last wrote it: then the
17
- * copy from before phantom's first change stays. A file that changed after the
15
+ * Writes a plan from {@link planSetup}. Before it edits a file for the first time it copies it
16
+ * to `<file>.phantom.bak`. That copy stays as it is on every later run, even when the user
17
+ * changed the file in between: a copy made then would already hold phantom's lines.
18
+ * A file the user changed since phantom last wrote it is marked `edited`, so
19
+ * {@link restoreSetup} takes out only phantom's lines. A file that changed after the
18
20
  * plan read it is left alone and listed in `skipped`.
19
21
  */
20
22
  export declare function applySetup(env: Env, plan: SetupPlan): SetupResult;
@@ -40,14 +42,21 @@ export declare function previewSetup(plan: SetupPlan): SetupResult;
40
42
  export declare function setupAgents(env: Env, opts?: SetupOptions): SetupResult;
41
43
  /** What {@link restoreSetup} did. */
42
44
  export type RestoreResult = {
43
- /** Files put back from their copy, or removed because phantom created them. */
45
+ /** Files put back from their copy, removed because phantom created them, or cleaned of phantom's own lines. */
44
46
  restored: Array<{
45
47
  /** The file. */
46
48
  file: string;
47
- /** The copy it came from. null when phantom created the file, so it was removed. */
49
+ /** The copy it came from. null when phantom created the file, so it was removed, or when only phantom's lines were taken out. */
48
50
  from: string | null;
51
+ /**
52
+ * Present when the file had changed since setup, so restore took out only phantom's own lines and keys
53
+ * and left the rest. false means none were left to take out.
54
+ */
55
+ lines_removed?: boolean;
56
+ /** With `lines_removed`: the copy from before setup, which restore left in place in case the user wants it. */
57
+ copy_kept?: string;
49
58
  }>;
50
- /** Files left alone, and why. */
59
+ /** Files that could not be undone, and why. Each one makes the exit code 1. */
51
60
  skipped: Array<{
52
61
  /** The file. */
53
62
  file: string;
@@ -58,11 +67,16 @@ export type RestoreResult = {
58
67
  dry_run?: boolean;
59
68
  };
60
69
  /**
61
- * Puts back the files `phantom setup` changed, from the copies it kept
62
- * (`<file>.phantom.bak`), and removes the files it created. Only a file still as
63
- * phantom wrote it: one changed since (Codex adds `[projects]` tables to its
64
- * config, for example) is left alone and listed, since the copy would undo
65
- * that change too. `--provider off` removes phantom's lines from such a file.
70
+ * Undoes `phantom setup`: puts back the files it changed from the copies it kept
71
+ * (`<file>.phantom.bak`), and removes the files it created.
72
+ *
73
+ * A file that changed since setup (the user edited it, or Codex added `[projects]` tables to its
74
+ * config) would lose those changes if the copy went over it. For such a file restore takes out only
75
+ * phantom's own lines and keys: JSON keys go back to the values setup recorded, TOML and YAML lines
76
+ * marked `# phantom setup` go (a replaced line comes back), and the shell block goes. The copy stays
77
+ * beside the file. A file left with nothing goes, or comes back from its copy.
78
+ * A file whose lines can't be told apart (it no longer parses) is listed in `skipped`, and only
79
+ * then does the exit code say something was left undone.
66
80
  * @param opts `agent` limits it to one agent's files (`shell` for the startup file).
67
81
  */
68
82
  export declare function restoreSetup(env: Env, opts?: {
@@ -4,7 +4,8 @@ import { createHash } from 'node:crypto';
4
4
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from 'node:fs';
5
5
  import { stateDir } from "../core/state.mjs";
6
6
  import { readText } from "./shared.mjs";
7
- import { jsonText } from "./editors.mjs";
7
+ import { CliError } from "../core/errors.mjs";
8
+ import { jsonText, shellRcFile, withoutShellBlock } from "./editors.mjs";
8
9
  import { claudePlan, SETUP_AGENTS } from "./agents.mjs";
9
10
  import { writeJsonWas } from "./was.mjs";
10
11
  import { planSetup } from "./plan.mjs";
@@ -75,9 +76,11 @@ export function isSetUp(env) {
75
76
  }
76
77
  const sha256 = (text) => createHash('sha256').update(text).digest('hex');
77
78
  /**
78
- * Writes a plan from {@link planSetup}. Before it edits a file it copies it
79
- * to `<file>.phantom.bak`, unless the file is still as phantom last wrote it: then the
80
- * copy from before phantom's first change stays. A file that changed after the
79
+ * Writes a plan from {@link planSetup}. Before it edits a file for the first time it copies it
80
+ * to `<file>.phantom.bak`. That copy stays as it is on every later run, even when the user
81
+ * changed the file in between: a copy made then would already hold phantom's lines.
82
+ * A file the user changed since phantom last wrote it is marked `edited`, so
83
+ * {@link restoreSetup} takes out only phantom's lines. A file that changed after the
81
84
  * plan read it is left alone and listed in `skipped`.
82
85
  */
83
86
  export function applySetup(env, plan) {
@@ -92,12 +95,17 @@ export function applySetup(env, plan) {
92
95
  let backup;
93
96
  if (!f.skill) {
94
97
  const prior = backups[f.file];
95
- const keep = Boolean(prior && f.before !== null && prior.sha === sha256(f.before) && (prior.backup === null || existsSync(prior.backup)));
96
- let from = keep ? prior.backup : null;
97
- if (!keep && f.before !== null) {
98
+ // The user changed the file since phantom last wrote it (or deleted it, or the copy is gone).
99
+ const edited = Boolean(prior && (prior.edited || prior.sha !== sha256(f.before ?? '') || (prior.backup !== null && !existsSync(prior.backup))));
100
+ let from;
101
+ if (prior)
102
+ from = prior.backup;
103
+ else if (f.before !== null) {
98
104
  from = `${f.file}.phantom.bak`;
99
105
  writeFileSync(from, f.before, { mode: 0o600 });
100
106
  }
107
+ else
108
+ from = null;
101
109
  if (f.before !== null && (f.agent === 'claude' || f.file.endsWith('settings.json'))) {
102
110
  const standardBak = `${f.file}.bak`;
103
111
  if (!existsSync(standardBak)) {
@@ -105,12 +113,12 @@ export function applySetup(env, plan) {
105
113
  writeFileSync(standardBak, content, { mode: 0o600 });
106
114
  }
107
115
  }
108
- if (from)
116
+ if (from && existsSync(from))
109
117
  backup = from;
110
118
  if (f.after === null && from === null)
111
119
  delete backups[f.file];
112
120
  else
113
- backups[f.file] = { agent: f.agent, backup: from, sha: sha256(f.after ?? '') };
121
+ backups[f.file] = { agent: f.agent, backup: from, sha: sha256(f.after ?? ''), ...(edited ? { edited } : {}) };
114
122
  }
115
123
  if (f.after === null)
116
124
  rmSync(f.file, { force: true });
@@ -163,11 +171,49 @@ export function setupAgents(env, opts = {}) {
163
171
  return applySetup(env, planSetup(env, opts));
164
172
  }
165
173
  /**
166
- * Puts back the files `phantom setup` changed, from the copies it kept
167
- * (`<file>.phantom.bak`), and removes the files it created. Only a file still as
168
- * phantom wrote it: one changed since (Codex adds `[projects]` tables to its
169
- * config, for example) is left alone and listed, since the copy would undo
170
- * that change too. `--provider off` removes phantom's lines from such a file.
174
+ * What a file holds once phantom's own lines and keys are taken out, for a file that changed since setup
175
+ * (or whose copy is gone): the agent's own `--provider off` step, which uses the values setup recorded
176
+ * (`setup-json-was.json`) and the `# phantom setup` marks, and for the shell file the phantom block.
177
+ * `after` is null or empty when nothing is left. `skip` says why the lines can't be taken out.
178
+ */
179
+ function withoutPhantomLines(env, file, agent, now) {
180
+ try {
181
+ if (agent === 'shell') {
182
+ if (now === null)
183
+ return { after: null, changed: false };
184
+ const after = withoutShellBlock(env, file, now);
185
+ return { after, changed: after !== now };
186
+ }
187
+ const provider = SETUP_AGENTS[agent]?.provider;
188
+ if (!provider)
189
+ return { skip: `phantom can't tell which lines in it are its own. Remove the lines ending "# phantom setup" by hand` };
190
+ const home = env.HOME || os.homedir();
191
+ const plan = provider({ env, home, shellRc: shellRcFile(env, home) }, true);
192
+ const edit = plan.edits.find((e) => e.file === file);
193
+ if (edit)
194
+ return { after: edit.after, changed: true };
195
+ // The agent's off step found nothing of phantom's in the file it looks at, and that is this file.
196
+ if (plan.result.settings === file)
197
+ return { after: now, changed: false };
198
+ return { skip: `phantom looks for this agent's settings in ${plan.result.settings} now. Remove the lines ending "# phantom setup" from it by hand` };
199
+ }
200
+ catch (err) {
201
+ if (err instanceof CliError && err.code === 'setup_unreadable')
202
+ return { skip: err.message };
203
+ throw err;
204
+ }
205
+ }
206
+ /**
207
+ * Undoes `phantom setup`: puts back the files it changed from the copies it kept
208
+ * (`<file>.phantom.bak`), and removes the files it created.
209
+ *
210
+ * A file that changed since setup (the user edited it, or Codex added `[projects]` tables to its
211
+ * config) would lose those changes if the copy went over it. For such a file restore takes out only
212
+ * phantom's own lines and keys: JSON keys go back to the values setup recorded, TOML and YAML lines
213
+ * marked `# phantom setup` go (a replaced line comes back), and the shell block goes. The copy stays
214
+ * beside the file. A file left with nothing goes, or comes back from its copy.
215
+ * A file whose lines can't be told apart (it no longer parses) is listed in `skipped`, and only
216
+ * then does the exit code say something was left undone.
171
217
  * @param opts `agent` limits it to one agent's files (`shell` for the startup file).
172
218
  */
173
219
  export function restoreSetup(env, opts = {}) {
@@ -178,26 +224,40 @@ export function restoreSetup(env, opts = {}) {
178
224
  if (opts.agent && opts.agent !== 'all' && entry.agent !== opts.agent)
179
225
  continue;
180
226
  const now = readText(file);
181
- if (sha256(now ?? '') !== entry.sha) {
182
- skipped.push({ file, reason: `changed since phantom wrote it${entry.backup ? `; the copy from before is ${entry.backup}` : ''}. phantom setup --provider off removes only phantom's lines` });
227
+ const copyThere = entry.backup !== null && existsSync(entry.backup);
228
+ const asPhantomWroteIt = !entry.edited && sha256(now ?? '') === entry.sha && (entry.backup === null || copyThere);
229
+ if (asPhantomWroteIt) {
230
+ if (!opts.dryRun) {
231
+ if (entry.backup === null)
232
+ rmSync(file, { force: true });
233
+ else {
234
+ writeFileSync(file, readFileSync(entry.backup));
235
+ rmSync(entry.backup);
236
+ }
237
+ delete backups[file];
238
+ // The file is back as it was before setup, so what setup recorded about its keys no longer applies.
239
+ writeJsonWas(env, file, null);
240
+ }
241
+ restored.push({ file, from: entry.backup });
183
242
  continue;
184
243
  }
185
- if (entry.backup !== null && !existsSync(entry.backup)) {
186
- skipped.push({ file, reason: `its copy ${entry.backup} is gone` });
244
+ const cleaned = withoutPhantomLines(env, file, entry.agent, now);
245
+ if ('skip' in cleaned) {
246
+ skipped.push({ file, reason: cleaned.skip });
187
247
  continue;
188
248
  }
189
249
  if (!opts.dryRun) {
190
- if (entry.backup === null)
191
- rmSync(file, { force: true });
192
- else {
250
+ const empty = cleaned.after === null || cleaned.after.trim() === '';
251
+ if (empty && copyThere)
193
252
  writeFileSync(file, readFileSync(entry.backup));
194
- rmSync(entry.backup);
195
- }
253
+ else if (empty)
254
+ rmSync(file, { force: true });
255
+ else if (cleaned.changed)
256
+ writeFileSync(file, cleaned.after);
196
257
  delete backups[file];
197
- // The file is back as it was before setup, so what setup recorded about its keys no longer applies.
198
258
  writeJsonWas(env, file, null);
199
259
  }
200
- restored.push({ file, from: entry.backup });
260
+ restored.push({ file, from: null, lines_removed: cleaned.changed, ...(copyThere ? { copy_kept: entry.backup } : {}) });
201
261
  }
202
262
  if (!opts.dryRun && restored.length)
203
263
  writeBackups(env, backups);
@@ -30,6 +30,14 @@ export function tableRestore(d, opts = {}) {
30
30
  return 'Nothing to restore.';
31
31
  const lines = [
32
32
  ...r.restored.map((x) => {
33
+ // A file the user changed since setup: only phantom's own lines came out.
34
+ if (x.lines_removed !== undefined) {
35
+ const mark = r.dry_run ? p.dim('·') : p.lime('✓');
36
+ if (!x.lines_removed)
37
+ return ` ${mark} ${short(x.file)} had no Phantom lines left`;
38
+ const kept = x.copy_kept ? ` The copy from before setup is still at ${short(x.copy_kept)}.` : '';
39
+ return ` ${mark} ${r.dry_run ? 'takes' : 'took'} Phantom's lines out of ${short(x.file)}; your own changes stay.${kept}`;
40
+ }
33
41
  const verb = x.from ? (r.dry_run ? 'puts back' : 'put back') : r.dry_run ? 'deletes' : 'removed';
34
42
  const what = x.from ? `${verb} ${short(x.file)} as it was before setup` : `${verb} ${short(x.file)} (phantom made this file)`;
35
43
  return ` ${r.dry_run ? p.dim('·') : p.lime('✓')} ${what}`;
@@ -93,6 +93,13 @@ export type ShellBlockState = {
93
93
  * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
94
94
  */
95
95
  export declare function shellBlock(env: Env, fish: boolean, state: ShellBlockState, onPathFn?: (bin: string) => boolean): string;
96
+ /**
97
+ * The startup file's text with the whole phantom block taken out, whichever
98
+ * agents it lists. Text outside the block stays as it was. Unchanged when
99
+ * there is no block.
100
+ * @throws {@link CliError} `setup_unreadable` when the block has no matching end line.
101
+ */
102
+ export declare function withoutShellBlock(env: Env, file: string, text: string): string;
96
103
  /**
97
104
  * The startup file's text with the phantom block updated: agents in `on` added
98
105
  * with fresh lines, agents in `off` dropped. The block goes away when no agent
@@ -450,6 +450,18 @@ function findBlock(file, lines) {
450
450
  }
451
451
  return { start, end, state: { agents, lines: own } };
452
452
  }
453
+ /**
454
+ * The startup file's text with the whole phantom block taken out, whichever
455
+ * agents it lists. Text outside the block stays as it was. Unchanged when
456
+ * there is no block.
457
+ * @throws {@link CliError} `setup_unreadable` when the block has no matching end line.
458
+ */
459
+ export function withoutShellBlock(env, file, text) {
460
+ const found = findBlock(file, text.split('\n'));
461
+ if (!found)
462
+ return text;
463
+ return withShellBlock(env, file, text, new Map(), found.state.agents) ?? '';
464
+ }
453
465
  /**
454
466
  * The startup file's text with the phantom block updated: agents in `on` added
455
467
  * with fresh lines, agents in `off` dropped. The block goes away when no agent
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
- import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
- import { stateDir } from "../core/state.mjs";
3
+ import { chmodSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { makePrivateFolder, stateDir } from "../core/state.mjs";
5
5
  import { jsonGet, jsonSet } from "./editors.mjs";
6
6
  const recordFile = (env) => path.join(stateDir(env), 'setup-json-was.json');
7
7
  function readAll(env) {
@@ -23,7 +23,7 @@ export function writeJsonWas(env, file, entries) {
23
23
  delete all[file];
24
24
  else
25
25
  all[file] = entries;
26
- mkdirSync(stateDir(env), { recursive: true, mode: 0o700 });
26
+ makePrivateFolder(env, stateDir(env));
27
27
  writeFileSync(recordFile(env), JSON.stringify(all, null, 2) + '\n', { mode: 0o600 });
28
28
  chmodSync(recordFile(env), 0o600);
29
29
  }
@@ -5,7 +5,7 @@ import { flagNum, out, pickIo, showsScreen } from "../core/helpers.mjs";
5
5
  import { colorOn, paint } from "../core/style.mjs";
6
6
  import { choose } from "../core/pick.mjs";
7
7
  import { hideHints, lineupScreen, priceHint, routeScreen, routeTestScreen, TIER_ABOUT } from "../cli/screens.mjs";
8
- import { getLineup, putLineup, resetLineup, LINEUP_TIERS } from "./lineup.mjs";
8
+ import { currentTiersOnly, getLineup, putLineup, resetLineup, LINEUP_TIERS } from "./lineup.mjs";
9
9
  import { getRoute, putRoute, patchRoute, clearRoute, testRoute, parseCondition, SORT_WORDS } from "./routing.mjs";
10
10
  /** `phantom route`: the key's route policy, its rules, and a dry run. Run by `run()`. */
11
11
  export async function routeCommand(input) {
@@ -124,9 +124,14 @@ function applyPick(into, tier, flag, value) {
124
124
  else
125
125
  into[tier] = value;
126
126
  }
127
+ /** Flags from when phantom-1 had an Economy tier. They stop the command before it asks the server anything. */
128
+ const RETIRED_LINEUP_FLAGS = ['economy', 'economy-fallback'];
127
129
  /** `phantom lineup`: the model phantom-1 runs in each tier, and a fallback for each. Run by `run()`. */
128
130
  export async function lineupCommand(input) {
129
131
  const { io, apiKey, subcommand, flags, baseUrl, env } = input;
132
+ const retired = RETIRED_LINEUP_FLAGS.find((name) => flags[name] !== undefined);
133
+ if (retired)
134
+ die(`phantom-1 has two tiers, Standard and Frontier. --${retired} is no longer an option.`, 'lineup_usage');
130
135
  const table = showsScreen(input);
131
136
  const style = { env, color: colorOn(env, io.stdoutIsTTY) };
132
137
  const tableLineup = (d) => lineupScreen(d, style);
@@ -141,12 +146,11 @@ export async function lineupCommand(input) {
141
146
  else if (subcommand === 'set') {
142
147
  // PUT replaces the whole lineup, so start from what the key has now.
143
148
  const read = await getLineup(apiKey, baseUrl);
144
- const current = read.lineup ?? {};
149
+ const current = currentTiersOnly(read.lineup);
145
150
  const { fallbacks: currentFallbacks, ...picks } = current;
146
151
  const fallbacks = { ...currentFallbacks };
147
- const model = { economy: flags['economy'], standard: flags['standard'], frontier: flags['frontier'] };
152
+ const model = { standard: flags['standard'], frontier: flags['frontier'] };
148
153
  const fallback = {
149
- economy: flags['economy-fallback'],
150
154
  standard: flags['standard-fallback'],
151
155
  frontier: flags['frontier-fallback'],
152
156
  };
@@ -159,7 +163,7 @@ export async function lineupCommand(input) {
159
163
  delete fallbacks[tier];
160
164
  }
161
165
  if (LINEUP_TIERS.every((tier) => model[tier] === undefined && fallback[tier] === undefined)) {
162
- die('lineup set needs --economy, --standard or --frontier, or --economy-fallback, --standard-fallback or --frontier-fallback, each with a model id or "default"');
166
+ die('lineup set needs --standard or --frontier, or --standard-fallback or --frontier-fallback, each with a model id or "default"');
163
167
  }
164
168
  const next = Object.keys(fallbacks).length ? { ...picks, fallbacks } : picks;
165
169
  out(await putLineup(apiKey, next, baseUrl), table, tableLineup, io.stdout);
@@ -173,7 +177,7 @@ export async function lineupCommand(input) {
173
177
  return 0;
174
178
  }
175
179
  /** The flags `lineup set` reads; with none of them, at a terminal, it opens the picker instead. */
176
- const LINEUP_FLAGS = ['economy', 'standard', 'frontier', 'economy-fallback', 'standard-fallback', 'frontier-fallback'];
180
+ const LINEUP_FLAGS = ['standard', 'frontier', 'standard-fallback', 'frontier-fallback'];
177
181
  /**
178
182
  * `phantom lineup set` at a terminal: choose a tier, then a model for it from
179
183
  * a list with prices (the default marked), and it saves at once. It loops
@@ -204,7 +208,7 @@ async function lineupPicker(input, pick, show) {
204
208
  const model = await choose({ ...pick, esc: 'back' }, `Which model should ${tier} run?`, options.map((c) => ({ label: c.model, hint: priceHint(c), value: c.model })), Math.max(0, options.findIndex((c) => c.model === now)));
205
209
  if (model === null)
206
210
  continue;
207
- const { fallbacks, ...picks } = read.lineup ?? {};
211
+ const { fallbacks, ...picks } = currentTiersOnly(read.lineup);
208
212
  const chosen = options.find((c) => c.model === model);
209
213
  if (chosen?.default)
210
214
  delete picks[tier];
@@ -4,8 +4,8 @@
4
4
  * (routers/phantom-1/runtime/src/lineup.ts in the Phantom repo), so the CLI
5
5
  * passes model ids through.
6
6
  */
7
- /** The three tiers `phantom-1` picks between, cheapest first. */
8
- export declare const LINEUP_TIERS: readonly ["economy", "standard", "frontier"];
7
+ /** The two tiers paid `phantom-1` picks between, cheapest first. */
8
+ export declare const LINEUP_TIERS: readonly ["standard", "frontier"];
9
9
  /** One of {@link LINEUP_TIERS}. */
10
10
  export type LineupTier = (typeof LINEUP_TIERS)[number];
11
11
  /** A model id for each tier that has one. */
@@ -46,6 +46,12 @@ export type LineupResult = {
46
46
  /** Each tier's choices, default first. Only GET sends them. */
47
47
  choices?: Record<LineupTier, LineupChoice[]>;
48
48
  };
49
+ /**
50
+ * A lineup with only the tiers phantom-1 has now. A server that is older than
51
+ * this CLI may still send an `economy` entry; the newer server answers 400 if
52
+ * a PUT carries one, so it is dropped before anything is sent back.
53
+ */
54
+ export declare function currentTiersOnly(lineup: Lineup | null | undefined): Lineup;
49
55
  /** The key's lineup, the model each tier runs, and each tier's choices (GET /key/lineup). */
50
56
  export declare function getLineup(apiKey: string, baseUrl?: string): Promise<LineupResult>;
51
57
  /** Replaces the key's whole lineup (PUT /key/lineup). The server checks it before saving. */
@@ -5,8 +5,25 @@ import { request } from "../core/request.mjs";
5
5
  * (routers/phantom-1/runtime/src/lineup.ts in the Phantom repo), so the CLI
6
6
  * passes model ids through.
7
7
  */
8
- /** The three tiers `phantom-1` picks between, cheapest first. */
9
- export const LINEUP_TIERS = ['economy', 'standard', 'frontier'];
8
+ /** The two tiers paid `phantom-1` picks between, cheapest first. */
9
+ export const LINEUP_TIERS = ['standard', 'frontier'];
10
+ /**
11
+ * A lineup with only the tiers phantom-1 has now. A server that is older than
12
+ * this CLI may still send an `economy` entry; the newer server answers 400 if
13
+ * a PUT carries one, so it is dropped before anything is sent back.
14
+ */
15
+ export function currentTiersOnly(lineup) {
16
+ const keep = (picks) => {
17
+ const kept = {};
18
+ for (const tier of LINEUP_TIERS)
19
+ if (picks?.[tier])
20
+ kept[tier] = picks[tier];
21
+ return kept;
22
+ };
23
+ const picks = keep(lineup ?? undefined);
24
+ const fallbacks = keep(lineup?.fallbacks);
25
+ return Object.keys(fallbacks).length ? { ...picks, fallbacks } : picks;
26
+ }
10
27
  /** The key's lineup, the model each tier runs, and each tier's choices (GET /key/lineup). */
11
28
  export function getLineup(apiKey, baseUrl) {
12
29
  return request('GET', '/key/lineup', apiKey, undefined, baseUrl);
@@ -6,7 +6,7 @@ import { DEFAULT_BASE_URL, REQUEST_TIMEOUT_MS, answerError, fetchAnswer, httpsOn
6
6
  import { stateDir } from "../core/state.mjs";
7
7
  import { writeSecret, readSecret, removeSecret, keychainOn } from "../core/secrets.mjs";
8
8
  import { keyCommand, loginCommand } from "../keys/command.mjs";
9
- import { die } from "../core/errors.mjs";
9
+ import { die, PhantomApiError } from "../core/errors.mjs";
10
10
  import { limitFlag, openUrl, pickIo, showsScreen } from "../core/helpers.mjs";
11
11
  import { BackToMenu, Cancelled, askText, cancelKeys, choose, keyboard } from "../core/pick.mjs";
12
12
  import { spawnSync } from 'node:child_process';
@@ -31,8 +31,15 @@ export async function wire(url, method, endpoint, body, token, timeoutMs) {
31
31
  },
32
32
  body: body === undefined ? undefined : JSON.stringify(body),
33
33
  }, `${method} ${endpoint}`, timeoutMs);
34
- if (!res.ok)
35
- throw answerError(res.status, answer);
34
+ if (!res.ok) {
35
+ const err = answerError(res.status, answer);
36
+ // A sign-in the server revoked answers 401 with words for a web page or the CLI alike ("run `phantom login`
37
+ // in the CLI, or sign in on /keys"). Here only the CLI is asking, so say it in the CLI's own words.
38
+ if (res.status === 401 && token && err.code === 'http_401') {
39
+ throw new PhantomApiError(401, err.code, 'This sign-in no longer works. Run phantom login to sign in again.');
40
+ }
41
+ throw err;
42
+ }
36
43
  if (answer.kind === 'text')
37
44
  die('Phantom AI sent a web page instead of data. Check PHANTOM_BASE_URL, and try again in a minute.', 'bad_answer');
38
45
  return answer.json;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phantomcodes/cli",
3
- "version": "1.4.4",
3
+ "version": "1.5.0",
4
4
  "description": "Connects Claude Code, Codex, pi and other coding agents to Phantom AI, an OpenAI-compatible API, and manages your keys, credit and spending caps from the terminal.",
5
5
  "keywords": [
6
6
  "phantom",
@@ -98,11 +98,11 @@ phantom models use phantom-1:zdr
98
98
 
99
99
  ```bash
100
100
  phantom lineup --table
101
- phantom lineup set --frontier <model> --economy-fallback <model>
101
+ phantom lineup set --frontier <model> --standard-fallback <model>
102
102
  phantom lineup reset
103
103
  ```
104
104
 
105
- Paid phantom-1 starts each task on the standard tier and moves hard steps to frontier (a failed try, or an image). The economy tier is what phantom-1:free runs; paid calls skip it. The lineup sets the model each tier runs, from the choices `phantom lineup` lists, and a fallback to try when that model fails. `default` in place of a model puts the tier back to its default. `lineup set` keeps the tiers you don't name.
105
+ Paid phantom-1 has two tiers. It starts each task on standard and moves hard steps to frontier (a failed try, or an image). phantom-1:free runs its own free models and has no tier to pick. The lineup sets the model each tier runs, from the choices `phantom lineup` lists, and a fallback to try when that model fails. `default` in place of a model puts the tier back to its default. `lineup set` keeps the tiers you don't name.
106
106
 
107
107
  ## See what was spent
108
108