@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,71 @@
1
+ import { type Env } from '../core/state.mts';
2
+ import type { ProviderResult } from './shared.mts';
3
+ import { type SetupPlan, type SetupResult, type SetupOptions } from './plan.mts';
4
+ /** Hides keys in text that is shown: `sk-phantom-****`, and an Anthropic key the user had in a file setup replaced: `sk-ant-****`. */
5
+ export declare function maskKeys(text: string): string;
6
+ /**
7
+ * A line diff of two texts: unchanged lines start with two spaces, removed
8
+ * lines with `- ` and added lines with `+ `. Unchanged lines more than two
9
+ * away from a change are left out, and each gap shows as ` ...`.
10
+ */
11
+ export declare function lineDiff(before: string | null, after: string | null): string;
12
+ /** Whether setup has written anything on this computer that undo could put back: it keeps a record of each file. */
13
+ export declare function isSetUp(env: Env): boolean;
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
18
+ * plan read it is left alone and listed in `skipped`.
19
+ */
20
+ export declare function applySetup(env: Env, plan: SetupPlan): SetupResult;
21
+ /**
22
+ * Points Claude Code at Phantom AI, or removes phantom's settings with `off`.
23
+ * Uses the same backups and restore safeguards as {@link applySetup}.
24
+ * The return value remains the provider result for existing callers.
25
+ * @deprecated Use {@link setupAgents} or {@link planSetup} and {@link applySetup}. This helper remains for settings-only callers.
26
+ */
27
+ export declare function claudeProvider(env: Env, opts?: {
28
+ off?: boolean;
29
+ model?: string;
30
+ onPath?: (bin: string) => boolean;
31
+ }): ProviderResult;
32
+ /** A plan as `--dry-run` reports it: each file that would change, with its diff, and nothing written. */
33
+ export declare function previewSetup(plan: SetupPlan): SetupResult;
34
+ /**
35
+ * Installs the phantom-ai skill for one agent, or for every agent found
36
+ * (see {@link SETUP_AGENTS}), and with `provider` sets that up
37
+ * too, without asking: {@link planSetup}, then {@link applySetup}.
38
+ * @throws {@link CliError} when no agent is found, the agent is unknown, or `provider` is set without an agent that supports it.
39
+ */
40
+ export declare function setupAgents(env: Env, opts?: SetupOptions): SetupResult;
41
+ /** What {@link restoreSetup} did. */
42
+ export type RestoreResult = {
43
+ /** Files put back from their copy, or removed because phantom created them. */
44
+ restored: Array<{
45
+ /** The file. */
46
+ file: string;
47
+ /** The copy it came from. null when phantom created the file, so it was removed. */
48
+ from: string | null;
49
+ }>;
50
+ /** Files left alone, and why. */
51
+ skipped: Array<{
52
+ /** The file. */
53
+ file: string;
54
+ /** Why. */
55
+ reason: string;
56
+ }>;
57
+ /** True with `--dry-run`: nothing was written. */
58
+ dry_run?: boolean;
59
+ };
60
+ /**
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.
66
+ * @param opts `agent` limits it to one agent's files (`shell` for the startup file).
67
+ */
68
+ export declare function restoreSetup(env: Env, opts?: {
69
+ agent?: string;
70
+ dryRun?: boolean;
71
+ }): RestoreResult;
@@ -6,10 +6,11 @@ import { stateDir } from "../core/state.mjs";
6
6
  import { readText } from "./shared.mjs";
7
7
  import { jsonText } from "./editors.mjs";
8
8
  import { claudePlan, SETUP_AGENTS } from "./agents.mjs";
9
+ import { writeJsonWas } from "./was.mjs";
9
10
  import { planSetup } from "./plan.mjs";
10
- /** Hides Phantom AI keys in text that is shown: `sk-phantom-****`. */
11
+ /** Hides keys in text that is shown: `sk-phantom-****`, and an Anthropic key the user had in a file setup replaced: `sk-ant-****`. */
11
12
  export function maskKeys(text) {
12
- return text.replace(/sk-phantom-[A-Za-z0-9_-]+/g, 'sk-phantom-****');
13
+ return text.replace(/sk-phantom-[A-Za-z0-9_-]+/g, 'sk-phantom-****').replace(/sk-ant-[A-Za-z0-9_-]+/g, 'sk-ant-****');
13
14
  }
14
15
  /**
15
16
  * A line diff of two texts: unchanged lines start with two spaces, removed
@@ -119,6 +120,8 @@ export function applySetup(env, plan) {
119
120
  if (f.mode)
120
121
  chmodSync(f.file, f.mode);
121
122
  }
123
+ if (f.was !== undefined)
124
+ writeJsonWas(env, f.file, f.after === null ? null : f.was);
122
125
  files.push({ agent: f.agent, file: f.file, action: f.action, ...(backup ? { backup } : {}), ...(f.skill ? {} : { diff: maskKeys(lineDiff(f.before, f.after)) }) });
123
126
  }
124
127
  if (plan.files.some((f) => !f.skill))
@@ -191,6 +194,8 @@ export function restoreSetup(env, opts = {}) {
191
194
  rmSync(entry.backup);
192
195
  }
193
196
  delete backups[file];
197
+ // The file is back as it was before setup, so what setup recorded about its keys no longer applies.
198
+ writeJsonWas(env, file, null);
194
199
  }
195
200
  restored.push({ file, from: entry.backup });
196
201
  }
@@ -0,0 +1,12 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import { type CommandInput } from '../core/helpers.mts';
3
+ import { type ScreenOptions } from './screen.mts';
4
+ /** `--table` output for `setup`, and what a terminal shows: see {@link setupScreen}. */
5
+ export declare function tableSetup(d: unknown, opts?: ScreenOptions): string;
6
+ /** `--table` output for `setup --restore`, and what a terminal shows: a ✓ per file put back, a ✗ per file left alone. */
7
+ export declare function tableRestore(d: unknown, opts?: {
8
+ env?: Env;
9
+ color?: boolean;
10
+ }): string;
11
+ /** `phantom setup`: plans, previews, asks, applies or restores agent setup. Plain setup with no key yet signs in first when it runs in a terminal. Run by `run()`. */
12
+ export declare function setupCommand(input: CommandInput): Promise<number>;
@@ -0,0 +1,101 @@
1
+ import type { Env } from '../core/state.mts';
2
+ /**
3
+ * A JSON or JSONC file's object, `{}` when it does not exist. Comments and
4
+ * trailing commas are fine: jsonc-parser reads them, as in Vercel's setup.
5
+ */
6
+ export declare function jsonObject(file: string, text: string | null): Record<string, unknown>;
7
+ export declare function jsonText(v: unknown): string;
8
+ /**
9
+ * One change to a JSON file: the path of keys to a value, and the value. undefined removes it.
10
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
11
+ */
12
+ export type JsonChange = [path: string[], value: unknown];
13
+ /** The value at a path of keys, or undefined. */
14
+ export declare function jsonGet(obj: unknown, p: string[]): unknown;
15
+ /** Sets the value at a path of keys, making the objects on the way. undefined removes it. */
16
+ export declare function jsonSet(obj: Record<string, unknown>, p: string[], value: unknown): void;
17
+ /**
18
+ * Applies `changes` to a JSON or JSONC file's text with jsonc-parser's
19
+ * `modify` and `applyEdits`, as Vercel's setup does, so comments, key order
20
+ * and formatting stay as they were. Only the text an edit inserts is
21
+ * formatted, in the file's own indent (none in a one-line file), so removing
22
+ * what was added gives back the same bytes. A new file is written in full. If
23
+ * the edited text doesn't read back as expected, the file is written in full
24
+ * instead, as Vercel's does.
25
+ * @throws {@link CliError} `setup_unreadable` when the file is not valid JSON or JSONC.
26
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
27
+ */
28
+ export declare function jsonEdit(file: string, text: string | null, changes: JsonChange[]): string;
29
+ /**
30
+ * Sets a top-level `key: value` in a YAML file, marked `# phantom setup`. A line
31
+ * it replaces stays as a comment, so `--provider off` can put it back.
32
+ * @throws {@link CliError} `setup_unreadable` when the file indents with tabs, or the key holds more than one line.
33
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
34
+ */
35
+ export declare function yamlSetTop(file: string, text: string | null, key: string, value: string): string;
36
+ /**
37
+ * Adds `item` (lines, unindented, the first starting with `- `) first in the
38
+ * top-level `models:` list of a YAML file, each line marked `# phantom setup`.
39
+ * Starts the list when there is none, and the file with `head` when it is
40
+ * empty. An entry phantom added before is replaced.
41
+ * @throws {@link CliError} `setup_unreadable` when the file indents with tabs or writes the list on one line.
42
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
43
+ */
44
+ export declare function yamlAddModel(file: string, text: string | null, item: string[], head?: string[]): string;
45
+ /**
46
+ * Removes each YAML line marked `# phantom setup`, and puts back the lines they replaced. Returns '' when that leaves nothing but an empty `models:`, as in a file phantom started.
47
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
48
+ */
49
+ export declare function yamlRemoveOurs(file: string, text: string): string;
50
+ /**
51
+ * Sets `key` in `table` ([] is the top of the file) to `value`, written as
52
+ * TOML, and marks the line with `# phantom setup`. A line it replaces stays as a
53
+ * comment, so `--provider off` can put it back. A missing table is added at
54
+ * the end of the file. The result must parse to the old file with this one
55
+ * key changed.
56
+ * @throws {@link CliError} `setup_unreadable` when the file is not valid TOML, or sets the key in a way a line edit can't change, such as an inline table or a dotted key.
57
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
58
+ */
59
+ export declare function tomlSet(file: string, text: string, table: string[], key: string, value: string): string;
60
+ /**
61
+ * Removes what {@link tomlSet} wrote: each line marked `# phantom setup`, and a
62
+ * table phantom added once nothing else is left in it. Lines it replaced come back.
63
+ * @throws {@link CliError} `setup_unreadable` when the file is not valid TOML, before or after.
64
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
65
+ */
66
+ export declare function tomlRemoveOurs(file: string, text: string): string;
67
+ /**
68
+ * The shell startup file the key block goes in, by $SHELL, as Vercel's
69
+ * `ai-gateway setup` picks it: `~/.zshrc` (or `$ZDOTDIR/.zshrc`),
70
+ * `~/.bash_profile` on macOS and `~/.bashrc` elsewhere, fish's `config.fish`
71
+ * (under `$XDG_CONFIG_HOME`), or `~/.profile` for any other shell. With no
72
+ * $SHELL, zsh on macOS and bash elsewhere.
73
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
74
+ */
75
+ export declare function shellRcFile(env: Env, home?: string): string;
76
+ /**
77
+ * The parts of a phantom block that change: which agents use it, and each agent's own lines.
78
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
79
+ */
80
+ export type ShellBlockState = {
81
+ /** The agents that read the key from the environment, in the order they were set up. */
82
+ agents: string[];
83
+ /** Each agent's own lines, from {@link SetupAgentSpec.shellEnv}. */
84
+ lines: Map<string, string[]>;
85
+ };
86
+ /**
87
+ * The block phantom adds to a shell startup file. When the shell starts it sets
88
+ * PHANTOM_API_KEY, unless it is set already: on macOS straight from the
89
+ * Keychain item the login key points to, and otherwise (or with
90
+ * PHANTOM_KEY_NAME set) by running `phantom key show`. The key itself is never
91
+ * written here. Each agent's own variables follow, set only when there is a key.
92
+ * @param fish Fish syntax instead of sh, bash and zsh.
93
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
94
+ */
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 phantom block updated: agents in `on` added
98
+ * with fresh lines, agents in `off` dropped. The block goes away when no agent
99
+ * is left. Text outside the block stays as it was.
100
+ */
101
+ export declare function withShellBlock(env: Env, file: string, text: string | null, on: Map<string, Record<string, string>>, off: string[], onPathFn?: (bin: string) => boolean): string | null;
@@ -26,10 +26,12 @@ export function jsonText(v) {
26
26
  return JSON.stringify(v, null, 2) + '\n';
27
27
  }
28
28
  const isPlainObject = (v) => Boolean(v) && typeof v === 'object' && !Array.isArray(v);
29
- function jsonGet(obj, p) {
29
+ /** The value at a path of keys, or undefined. */
30
+ export function jsonGet(obj, p) {
30
31
  return p.reduce((n, k) => (isPlainObject(n) ? n[k] : undefined), obj);
31
32
  }
32
- function jsonSet(obj, p, value) {
33
+ /** Sets the value at a path of keys, making the objects on the way. undefined removes it. */
34
+ export function jsonSet(obj, p, value) {
33
35
  let n = obj;
34
36
  for (const k of p.slice(0, -1)) {
35
37
  if (!isPlainObject(n[k]))
@@ -0,0 +1,13 @@
1
+ import type { Env } from '../core/state.mts';
2
+ /**
3
+ * What phantom prints, once per run in a terminal, while an agent setup that
4
+ * pai (this CLI's old name) wrote still runs `pai`. Once pai is gone, that
5
+ * setup can't get a key until `phantom setup` rewrites it.
6
+ */
7
+ export declare const LEGACY_SETUP_HINT = "Your agent setup still runs pai, the old name of this CLI. Run phantom setup to switch it to phantom.";
8
+ /**
9
+ * True when an agent setup still runs `pai`: Claude Code's `apiKeyHelper`
10
+ * calls it, or the shell startup file holds the block pai setup wrote.
11
+ * `phantom setup` finds and rewrites both.
12
+ */
13
+ export declare function legacySetupFound(env: Env): boolean;
@@ -0,0 +1,104 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import { type SetupAgent, type ProviderResult } from './shared.mts';
3
+ import type { JsonWas } from './was.mts';
4
+ /** One file setup changes, with its text before and after. */
5
+ export type SetupFile = {
6
+ /** The agent it is for, or `shell` for the startup file. */
7
+ agent: SetupAgent | 'shell';
8
+ /** The file. */
9
+ file: string;
10
+ /** `create`, `update` or `remove`. */
11
+ action: 'create' | 'update' | 'remove';
12
+ /** Its text now. null when it does not exist. */
13
+ before: string | null;
14
+ /** Its text after. null removes it. */
15
+ after: string | null;
16
+ /** True for the skill: phantom's own file, so it gets no backup and no diff. */
17
+ skill?: boolean;
18
+ /** The file's mode, for a file that holds a key. */
19
+ mode?: number;
20
+ /** The record of JSON keys setup wrote, to save once the file is written. null forgets it. */
21
+ was?: JsonWas | null;
22
+ };
23
+ /** What {@link planSetup} works out, for {@link applySetup} to write. */
24
+ export type SetupPlan = {
25
+ /** One entry per agent, as {@link SetupResult} reports it. */
26
+ agents: SetupResult['agents'];
27
+ /** The files to change. */
28
+ files: SetupFile[];
29
+ /** What was left out, and why. */
30
+ skipped: Array<{
31
+ /** The agent, or `shell` for the startup file. */
32
+ agent: SetupAgent | 'shell';
33
+ /** Why. */
34
+ reason: string;
35
+ }>;
36
+ /** Things to tell the user. */
37
+ notes: string[];
38
+ };
39
+ /** What {@link setupAgents} did. */
40
+ export type SetupResult = {
41
+ /** One entry per agent set up. */
42
+ agents: Array<{
43
+ /** The agent. */
44
+ agent: SetupAgent;
45
+ /** The path of the skill. null for an agent without skills. */
46
+ skill: string | null;
47
+ /** What `--provider` (or plain `phantom setup`) changed in the agent's settings, for an agent that supports it. */
48
+ provider?: ProviderResult;
49
+ }>;
50
+ /** Each file written, or with `--dry-run` each file that would be. */
51
+ files: Array<{
52
+ /** The agent it is for, or `shell`. */
53
+ agent: SetupAgent | 'shell';
54
+ /** The file. */
55
+ file: string;
56
+ /** `create`, `update` or `remove`. */
57
+ action: SetupFile['action'];
58
+ /** The copy of the file from before phantom changed it. */
59
+ backup?: string;
60
+ /** The change as a line diff, with keys masked. Left out for the skill. */
61
+ diff?: string;
62
+ }>;
63
+ /** What was left alone, and why, such as a config file that does not parse. */
64
+ skipped?: SetupPlan['skipped'];
65
+ /** Things to know, such as setting up without a key. */
66
+ notes?: string[];
67
+ /** True with `--dry-run`: nothing was written. */
68
+ dry_run?: boolean;
69
+ /** False when the user said no at the prompt: nothing was written. */
70
+ applied?: boolean;
71
+ /** False when only part of setup could run (no key yet, so the agents weren't pointed at Phantom AI). */
72
+ complete?: boolean;
73
+ };
74
+ /** Options for {@link planSetup} and {@link setupAgents}. */
75
+ export type SetupOptions = {
76
+ /** One agent, or `all` (the default): every agent whose folder is found. */
77
+ agent?: string;
78
+ /** With `all`, only these of the agents found: the ones ticked in setup's checklist. */
79
+ only?: readonly SetupAgent[];
80
+ /** Point the agents' own model calls at Phantom AI, or `off` to undo that. */
81
+ provider?: boolean | 'off';
82
+ /** The model to start each agent on, instead of {@link SETUP_MODEL}. */
83
+ model?: string;
84
+ /**
85
+ * False leaves the shell startup file alone (`--no-shell`, or "Your shell"
86
+ * unticked): setup then lists the lines to add by hand, so agents that read
87
+ * the key from the environment can still find it.
88
+ */
89
+ shell?: boolean;
90
+ /** Plain `phantom setup`: with no key yet, install the skills and say so, rather than refuse. */
91
+ guided?: boolean;
92
+ /** Whether a program is on PATH. Defaults to checking for real. */
93
+ onPath?: (bin: string) => boolean;
94
+ };
95
+ /**
96
+ * Works out what setup would change, and writes nothing: the skill for each
97
+ * agent ({@link SETUP_AGENTS}), each agent's model
98
+ * settings with `provider` ({@link SetupAgentSpec.provider}), and the shell
99
+ * block ({@link shellBlock}) for agents that read the key from the
100
+ * environment. A config file setup can't edit safely is left out and listed
101
+ * in `skipped`.
102
+ * @throws {@link CliError} when no agent is found, the agent is unknown, the model is not a plain id, `provider` is set without an agent that supports it, or there is no key for `provider`.
103
+ */
104
+ export declare function planSetup(env: Env, opts?: SetupOptions): SetupPlan;
@@ -65,19 +65,21 @@ export function planSetup(env, opts = {}) {
65
65
  const files = [];
66
66
  const skipped = [];
67
67
  const agents = [];
68
- const add = (agent, file, after, skill = false, mode) => {
68
+ const add = (agent, file, after, skill = false, mode, was) => {
69
69
  const known = files.find((f) => f.file === file);
70
70
  if (known) {
71
71
  known.after = after;
72
72
  if (mode)
73
73
  known.mode = mode;
74
+ if (was !== undefined)
75
+ known.was = was;
74
76
  known.action = known.before === null ? 'create' : after === null ? 'remove' : 'update';
75
77
  return;
76
78
  }
77
79
  const before = readText(file);
78
80
  if (before === after)
79
81
  return;
80
- files.push({ agent, file, action: before === null ? 'create' : after === null ? 'remove' : 'update', before, after, ...(skill ? { skill } : {}), ...(mode ? { mode } : {}) });
82
+ files.push({ agent, file, action: before === null ? 'create' : after === null ? 'remove' : 'update', before, after, ...(skill ? { skill } : {}), ...(mode ? { mode } : {}), ...(was !== undefined ? { was } : {}) });
81
83
  };
82
84
  const skillText = readFileSync(skillSource(), 'utf-8');
83
85
  const shellOn = new Map();
@@ -92,7 +94,7 @@ export function planSetup(env, opts = {}) {
92
94
  try {
93
95
  const p = spec.provider(ctx, provider === 'off');
94
96
  for (const e of p.edits)
95
- add(agent, e.file, e.after, false, e.mode);
97
+ add(agent, e.file, e.after, false, e.mode, e.was);
96
98
  result = p.result;
97
99
  if (spec.shellEnv) {
98
100
  if (provider === 'off')
@@ -0,0 +1,30 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import type { SetupResult } from './plan.mts';
3
+ /** Which moment the screen shows. */
4
+ export type ScreenMode =
5
+ /** Before "Make these changes?": what setup is about to do. */
6
+ 'ask'
7
+ /** `--dry-run`: what setup would do; nothing was written. */
8
+ | 'dry'
9
+ /** The user said no at the prompt. */
10
+ | 'declined'
11
+ /** The changes are made. */
12
+ | 'done';
13
+ export type ScreenOptions = {
14
+ /** The environment, for the home folder (shown as ~) and the terminal's colors. */
15
+ env?: Env;
16
+ /** Print color, and the ghost. Off unless asked for, so tests and pipes get plain text. */
17
+ color?: boolean;
18
+ /** Show every line each file gains or loses (`--diff`). */
19
+ diff?: boolean;
20
+ /** Which moment to show. Worked out from the result when left out. */
21
+ mode?: ScreenMode;
22
+ /** The terminal's width, so long lines wrap at a word with an indent. 100 when unknown. */
23
+ columns?: number;
24
+ /** Say how to see every line. Off when a picker offers that as a choice instead. */
25
+ hint?: boolean;
26
+ };
27
+ /** `text` broken at spaces into lines of at most `width` characters; a single longer word stays whole. */
28
+ export declare function wrapWords(text: string, width: number): string[];
29
+ /** `phantom setup`'s screen for one result. See {@link ScreenMode} for the moments it shows. */
30
+ export declare function setupScreen(r: SetupResult, opts?: ScreenOptions): string;
@@ -0,0 +1,141 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import type { JsonWas } from './was.mts';
3
+ /** True when `bin` is a program on PATH. */
4
+ export declare function onPath(bin: string): boolean;
5
+ /**
6
+ * `phantom setup` installs the phantom-ai skill where each agent looks for skills,
7
+ * and points each agent's own model calls at Phantom AI. Every agent here
8
+ * reads the same SKILL.md format, so one file serves all of them.
9
+ *
10
+ * Nothing is written straight away. {@link planSetup} works out each file's
11
+ * text before and after, so `phantom setup` can show the change as a diff and ask
12
+ * first, and {@link applySetup} writes it, keeping a copy of each file it
13
+ * edits beside it as `<file>.phantom.bak`. Lines phantom adds to a TOML, YAML or shell
14
+ * file end with `# phantom setup`, so `--provider off` removes exactly those.
15
+ *
16
+ * The key never goes into an agent's config. Claude Code runs `phantom key show`
17
+ * through `apiKeyHelper`. Agents that read an environment variable get
18
+ * PHANTOM_API_KEY from a block phantom adds to the shell's startup file, which
19
+ * reads the key from the macOS Keychain (or `phantom key show`) each time a shell
20
+ * starts ({@link shellBlock}). Cursor and Cline keep their model settings on
21
+ * their own settings screens, so setup prints the steps.
22
+ */
23
+ /**
24
+ * What {@link planSetup} hands each agent's functions in {@link SETUP_AGENTS}.
25
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
26
+ */
27
+ export type SetupContext = {
28
+ /** The environment phantom runs in. */
29
+ env: Env;
30
+ /** The home folder agents are found in. */
31
+ home: string;
32
+ /** Whether a program is on PATH. Defaults to checking for real. */
33
+ onPath?: (bin: string) => boolean;
34
+ /** The model `--model` asked for, if any. */
35
+ model?: string;
36
+ /** The shell startup file the key block goes in ({@link shellRcFile}). */
37
+ shellRc: string;
38
+ };
39
+ /**
40
+ * One file a setup step changes.
41
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
42
+ */
43
+ export type SetupEdit = {
44
+ /** The file. */
45
+ file: string;
46
+ /** Its text after the change. null removes the file. */
47
+ after: string | null;
48
+ /** The file's mode, for a file that holds a key. */
49
+ mode?: number;
50
+ /** What setup recorded about the JSON keys it wrote, for `--provider off` to put back ({@link JsonWas}). null forgets the record. */
51
+ was?: JsonWas | null;
52
+ };
53
+ /**
54
+ * What {@link SetupAgentSpec.provider} returns.
55
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
56
+ */
57
+ export type ProviderPlan = {
58
+ /** The files to write. Empty for an agent set up on its settings screen or by the shell block alone. */
59
+ edits: SetupEdit[];
60
+ /** What to report. */
61
+ result: ProviderResult;
62
+ };
63
+ /** An agent name `phantom setup --agent` takes, other than `all`. */
64
+ export type SetupAgent = 'pi' | 'codex' | 'claude' | 'cursor' | 'opencode' | 'continue' | 'goose' | 'aider' | 'copilot' | 'cline' | 'gemini' | 'crush' | 'qwen' | 'kilo' | 'kimi' | 'droid' | 'vibe' | 'zed' | 'vscode' | 'jetbrains' | 'warp' | 'trae';
65
+ /**
66
+ * One agent `phantom setup` knows: where to find it, where its skill goes, and what else setup can do for it.
67
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
68
+ */
69
+ export type SetupAgentSpec = {
70
+ /** The agent's name in messages, such as `Claude Code`. */
71
+ label: string;
72
+ /** The folder (or file) in the home directory whose presence means the agent is installed. */
73
+ home: string;
74
+ /** Whether the agent is installed, for one found somewhere other than {@link SetupAgentSpec.home}, such as `$CODEX_HOME`. */
75
+ detect?: (env: Env, home: string) => boolean;
76
+ /** The folder in the home directory the skill goes in. Left out for agents without skills. */
77
+ skills?: string;
78
+ /**
79
+ * Points the agent's own model calls at Phantom AI, or with `off` removes
80
+ * what phantom wrote. Throws a {@link CliError} with code `setup_unreadable` for
81
+ * a config file it can't edit safely, and setup skips that agent.
82
+ */
83
+ provider?: (ctx: SetupContext, off: boolean) => ProviderPlan;
84
+ /**
85
+ * Variables the agent reads, set in the shell block next to
86
+ * PHANTOM_API_KEY. A value may use `$PHANTOM_API_KEY`. Present (even empty)
87
+ * for every agent that reads the key from the environment.
88
+ */
89
+ shellEnv?: (ctx: SetupContext) => Record<string, string>;
90
+ };
91
+ /** The model setup starts each agent on when `--model` is not given. */
92
+ export declare const SETUP_MODEL = "phantom-1";
93
+ /** The coding agents Phantom AI serves at their own base path. */
94
+ export type AgentPath = 'codex' | 'claude-code' | 'cursor' | 'coding-agent' | 'gemini-cli';
95
+ /**
96
+ * The address Phantom AI serves a coding agent at, from PHANTOM_BASE_URL
97
+ * without its `/v1`: `/claude-code` (Claude Code adds `/v1` itself),
98
+ * `/gemini-cli` (Gemini CLI adds Google's `/v1beta`), or `/codex/v1`,
99
+ * `/cursor/v1` and `/coding-agent/v1` for the others.
100
+ * @throws {@link CliError} when PHANTOM_BASE_URL is not https ({@link httpsOnly}).
101
+ */
102
+ export declare function agentBaseUrl(env: Env, agent: AgentPath): string;
103
+ /** The end of every line phantom adds to a TOML, YAML or shell file. */
104
+ export declare const SETUP_MARK = "# phantom setup";
105
+ /** The start of a line phantom turned into a comment because it replaced it. `--provider off` puts it back. */
106
+ export declare const SETUP_WAS = "# phantom setup was: ";
107
+ /** True for a line setup added: it ends with {@link SETUP_MARK}, or the mark pai wrote. */
108
+ export declare function setupMarked(line: string): boolean;
109
+ /** The line without the setup mark on its end. */
110
+ export declare function stripMark(line: string): string;
111
+ /** A line setup turned into a comment, put back as it was. Other lines come back unchanged. */
112
+ export declare function unwas(line: string): string;
113
+ /** A file's text, or null when it does not exist. Other read errors pass through. */
114
+ export declare function readText(file: string): string | null;
115
+ /** Refuses a file setup can't edit safely. Setup skips the agent and says why. */
116
+ export declare function unreadable(file: string, why: string): never;
117
+ /** How to run this phantom from outside this shell: `phantom` if it's installed, else this node and script by absolute path. */
118
+ export declare function phantomCommand(onPathFn: (bin: string) => boolean): string;
119
+ /** `$XDG_CONFIG_HOME` when it is an absolute path, else `~/.config`. */
120
+ export declare function configHome(env: Env, home: string): string;
121
+ /** A writer's `off` result for a file it edits by removing its own lines or entries. */
122
+ export declare function offResult(label: string, file: string, text: string | null, after: string | null, forgetJsonWas?: boolean): ProviderPlan;
123
+ /** What {@link claudeProvider} changed, and what each agent's provider step reports. */
124
+ export type ProviderResult = {
125
+ /** The agent's settings file, or the shell startup file for an agent set up by environment variables alone. */
126
+ settings: string;
127
+ /** True when the agent now runs on Phantom AI; false after `--provider off`, and for an agent set up on its settings screen. */
128
+ on: boolean;
129
+ /** The base URL the agent now calls. */
130
+ base_url?: string;
131
+ /** The model the agent now starts with, if phantom set one. */
132
+ model?: string;
133
+ /** Things the user should know, such as an ANTHROPIC_AUTH_TOKEN in the shell that would win over the Phantom key. */
134
+ warnings: string[];
135
+ /** Steps to follow by hand, for an agent whose model settings live on its settings screen. */
136
+ manual?: string[];
137
+ };
138
+ /** A model as Claude Code names it: `phantom-1:zdr` is `claude-code/phantom-1:zdr`, and one that has the prefix keeps one. */
139
+ export declare function claudeModelName(model: string): string;
140
+ /** The context window Phantom AI's catalog gives phantom-1. Goose and Aider size requests by it. */
141
+ export declare const SETUP_CONTEXT_WINDOW = 1000000;
@@ -71,12 +71,18 @@ export function configHome(env, home) {
71
71
  return env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(home, '.config');
72
72
  }
73
73
  /** A writer's `off` result for a file it edits by removing its own lines or entries. */
74
- export function offResult(label, file, text, after) {
74
+ export function offResult(label, file, text, after, forgetJsonWas = false) {
75
75
  const changed = text !== null && after !== text;
76
76
  return {
77
- edits: changed ? [{ file, after: after || null }] : [],
77
+ edits: changed ? [{ file, after: after || null, ...(forgetJsonWas ? { was: null } : {}) }] : [],
78
78
  result: { settings: file, on: false, warnings: changed ? [] : [`${label} was not set to Phantom AI by phantom; nothing changed`] },
79
79
  };
80
80
  }
81
+ /** The prefix Claude Code's `/model` picker needs to keep a model: it drops ids without "claude" in them. The server strips it again. */
82
+ const CLAUDE_CODE_PREFIX = 'claude-code/';
83
+ /** A model as Claude Code names it: `phantom-1:zdr` is `claude-code/phantom-1:zdr`, and one that has the prefix keeps one. */
84
+ export function claudeModelName(model) {
85
+ return CLAUDE_CODE_PREFIX + (model.startsWith(CLAUDE_CODE_PREFIX) ? model.slice(CLAUDE_CODE_PREFIX.length) : model);
86
+ }
81
87
  /** The context window Phantom AI's catalog gives phantom-1. Goose and Aider size requests by it. */
82
88
  export const SETUP_CONTEXT_WINDOW = 1_000_000;
@@ -0,0 +1,42 @@
1
+ import { type Env } from '../core/state.mts';
2
+ import { type JsonChange } from './editors.mts';
3
+ /**
4
+ * What `phantom setup` replaced in a JSON settings file, so `--provider off` can put it back.
5
+ *
6
+ * TOML and YAML files keep this in the file itself: the replaced line stays as a `# phantom setup was:`
7
+ * comment. JSON has no comments, and Claude Code and the other agents read these files strictly, so
8
+ * the record lives in `setup-json-was.json` in the state folder instead (mode 600, because a replaced
9
+ * value can be a key the user had in the file).
10
+ */
11
+ /** One key setup wrote in a JSON file. */
12
+ export type JsonWasEntry = {
13
+ /** The keys from the top of the file down to the value, such as `['env', 'ANTHROPIC_MODEL']`. */
14
+ path: string[];
15
+ /** True when the key held a value before setup wrote it. */
16
+ had: boolean;
17
+ /** The value before setup wrote the key. Missing when `had` is false. */
18
+ was?: unknown;
19
+ /** What setup wrote. Off puts the old value back only while the key still holds this. */
20
+ wrote: unknown;
21
+ };
22
+ /** Every key setup wrote in one file. */
23
+ export type JsonWas = JsonWasEntry[];
24
+ /** What setup recorded for `file`, or an empty list. */
25
+ export declare function readJsonWas(env: Env, file: string): JsonWas;
26
+ /** Saves what setup recorded for `file`. null forgets it. */
27
+ export declare function writeJsonWas(env: Env, file: string, entries: JsonWas | null): void;
28
+ /**
29
+ * The record after setup writes `changes` to a file whose parsed content is `settings`. Each key remembers
30
+ * the value that was there. When setup runs again over its own value, the older record stays, so the
31
+ * user's first value survives any number of runs.
32
+ * @param previous What setup recorded for this file before.
33
+ * @param tracked The paths to record. Other changes are not remembered (a key setup adds to a list, say).
34
+ */
35
+ export declare function trackJsonChanges(settings: Record<string, unknown>, previous: JsonWas, changes: JsonChange[], tracked: string[][]): JsonWas;
36
+ /**
37
+ * The changes for `--provider off`. `removals` are what an agent's own off step would do (it knows which
38
+ * values look like phantom's); this swaps in the record: a key still holding what setup wrote gets its old
39
+ * value back, or goes if setup added it, and a key the user changed since is left alone. A container
40
+ * that a removal of a key setup added leaves empty goes too, and so does each one in `tidy` that ends up empty.
41
+ */
42
+ export declare function restoreJsonChanges(settings: Record<string, unknown>, record: JsonWas, removals: JsonChange[], tidy?: string[][]): JsonChange[];