@phantomcodes/cli 1.4.3 → 1.4.5

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.
@@ -109,7 +109,7 @@ If phantom can't save a new or rotated key on this computer (a locked Keychain o
109
109
 
110
110
  Phantom has three models of its own. `phantom models` shows what each can do (chat, images in, embeddings, rerank, images, video, speech, transcription) and the model behind each job:
111
111
 
112
- - `phantom-1` does every job. For each chat request it picks a tier: economy, standard or frontier.
112
+ - `phantom-1` does every job. Chat starts each task on the standard tier and moves hard steps to frontier: a failed try, or an image.
113
113
  - `phantom-1:free` is chat on free models at $0, with no card.
114
114
  - `phantom-1:zdr` is chat (with images) on providers that keep none of your data.
115
115
 
@@ -224,14 +224,18 @@ export const COMMANDS = [
224
224
  --provider off takes phantom's settings out and
225
225
  puts back what they replaced
226
226
  setup --restore [--agent <name>] put back the files setup changed, from the
227
- .phantom.bak copies it kept`,
227
+ .phantom.bak copies it kept. A file you
228
+ edited since keeps your edits: only
229
+ Phantom's own lines come out`,
228
230
  },
229
231
  {
230
232
  name: 'verify', advanced: true, handler: verifyCommand, keyless: ['--receipt'],
231
233
  group: 'More', summary: 'check a signed receipt',
232
234
  help: ` verify --model <id> make one small call and check that its signed
233
235
  receipt names the model you asked for (costs a
234
- fraction of a cent)
236
+ fraction of a cent). For phantom-1, phantom-1:free,
237
+ phantom-1:zdr or auto it checks the receipt's
238
+ requested model, since the model that ran varies
235
239
  verify --receipt <receipt> check a receipt you already have`,
236
240
  },
237
241
  ];
@@ -107,9 +107,9 @@ 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: "short, easy requests";
111
- readonly standard: "everyday coding";
112
- readonly frontier: "the hardest work";
110
+ readonly economy: "phantom-1:free only; paid calls skip it";
111
+ readonly standard: "where every task starts";
112
+ readonly frontier: "hard steps: a failed try, an image";
113
113
  };
114
114
  /** `phantom lineup`: the model phantom-1 runs in each tier, whether it's the default or your pick, and its fallback. */
115
115
  export declare function lineupScreen(l: LineupView, style?: ScreenStyle): string;
@@ -229,9 +229,9 @@ 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: 'short, easy requests',
233
- standard: 'everyday coding',
234
- frontier: 'the hardest work',
232
+ economy: 'phantom-1:free only; paid calls skip it',
233
+ standard: 'where every task starts',
234
+ frontier: 'hard steps: a failed try, an image',
235
235
  };
236
236
  /** `phantom lineup`: the model phantom-1 runs in each tier, whether it's the default or your pick, and its fallback. */
237
237
  export function lineupScreen(l, style = {}) {
@@ -332,7 +332,7 @@ export function keySavedScreen(name, style = {}) {
332
332
  }
333
333
  /** What each of Phantom's own models is for, in a few words. */
334
334
  const MODEL_ABOUT = {
335
- 'phantom-1': 'every job; chat picks economy, standard or frontier for each request',
335
+ 'phantom-1': 'every job; chat starts each task on standard and moves hard steps to frontier',
336
336
  'phantom-1:free': `chat on free models at $0, no card; ${FREE_REQUESTS_A_DAY} requests a day, ${FREE_AGENT_REQUESTS_A_DAY} from an agent`,
337
337
  'phantom-1:zdr': 'chat on providers that keep none of your data, at their prices',
338
338
  };
@@ -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.3";
2
+ export declare const VERSION = "1.4.5";
@@ -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.3';
2
+ export const VERSION = '1.4.5';
@@ -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
  }
@@ -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.3",
3
+ "version": "1.4.5",
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",
@@ -102,7 +102,7 @@ phantom lineup set --frontier <model> --economy-fallback <model>
102
102
  phantom lineup reset
103
103
  ```
104
104
 
105
- phantom-1 sorts each request into a tier: economy, standard or frontier. 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 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.
106
106
 
107
107
  ## See what was spent
108
108