@phantomcodes/cli 1.4.0 → 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 (69) hide show
  1. package/README.md +13 -16
  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/app.mjs +0 -2
  8. package/dist/cli/commands.d.mts +19 -0
  9. package/dist/cli/commands.mjs +1 -11
  10. package/dist/cli/help.d.mts +26 -0
  11. package/dist/cli/help.mjs +1 -1
  12. package/dist/cli/run.d.mts +2 -0
  13. package/dist/cli/screens.d.mts +171 -0
  14. package/dist/cli/screens.mjs +0 -31
  15. package/dist/cli/start.d.mts +34 -0
  16. package/dist/cli/start.mjs +0 -1
  17. package/dist/core/brand.d.mts +12 -0
  18. package/dist/core/errors.d.mts +27 -0
  19. package/dist/core/free.d.mts +13 -0
  20. package/dist/core/helpers.d.mts +75 -0
  21. package/dist/core/helpers.mjs +28 -3
  22. package/dist/core/motion.d.mts +47 -0
  23. package/dist/core/node-trust.d.mts +12 -0
  24. package/dist/core/pick.d.mts +86 -0
  25. package/dist/core/request.d.mts +64 -0
  26. package/dist/core/request.mjs +79 -30
  27. package/dist/core/secrets.d.mts +33 -0
  28. package/dist/core/shapes.d.mts +13 -0
  29. package/dist/core/state.d.mts +3 -0
  30. package/dist/core/style.d.mts +49 -0
  31. package/dist/core/version.d.mts +2 -0
  32. package/dist/core/version.mjs +1 -1
  33. package/dist/keys/command.d.mts +16 -0
  34. package/dist/keys/saved.d.mts +88 -0
  35. package/dist/models/choice.d.mts +7 -0
  36. package/dist/models/choice.mjs +1 -1
  37. package/dist/models/command.d.mts +8 -0
  38. package/dist/models/list.d.mts +39 -0
  39. package/dist/phantom.d.mts +45 -0
  40. package/dist/phantom.mjs +0 -1
  41. package/dist/receipts/command.d.mts +7 -0
  42. package/dist/receipts/receipts.d.mts +67 -0
  43. package/dist/receipts/receipts.mjs +15 -11
  44. package/dist/setup/agents.d.mts +149 -0
  45. package/dist/setup/agents.mjs +48 -35
  46. package/dist/setup/apply.d.mts +71 -0
  47. package/dist/setup/apply.mjs +7 -2
  48. package/dist/setup/command.d.mts +12 -0
  49. package/dist/setup/editors.d.mts +101 -0
  50. package/dist/setup/editors.mjs +4 -2
  51. package/dist/setup/legacy.d.mts +13 -0
  52. package/dist/setup/plan.d.mts +104 -0
  53. package/dist/setup/plan.mjs +5 -3
  54. package/dist/setup/screen.d.mts +30 -0
  55. package/dist/setup/shared.d.mts +141 -0
  56. package/dist/setup/shared.mjs +8 -2
  57. package/dist/setup/was.d.mts +42 -0
  58. package/dist/setup/was.mjs +91 -0
  59. package/dist/spend/command.d.mts +5 -0
  60. package/dist/spend/lineup.d.mts +54 -0
  61. package/dist/spend/lineup.mjs +3 -2
  62. package/dist/spend/report.d.mts +105 -0
  63. package/dist/spend/report.mjs +0 -2
  64. package/dist/spend/routing.d.mts +72 -0
  65. package/dist/workspace/command.d.mts +46 -0
  66. package/dist/workspace/command.mjs +83 -37
  67. package/package.json +2 -2
  68. package/skills/phantom-ai/SKILL.md +1 -15
  69. package/dist/plan/command.mjs +0 -91
@@ -4,7 +4,8 @@ import { existsSync } from 'node:fs';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { die } from "../core/errors.mjs";
6
6
  import { resolveApiKey } from "../keys/saved.mjs";
7
- import { SETUP_MODEL, agentBaseUrl, readText, configHome, onPath, phantomCommand, offResult, unreadable, SETUP_MARK, SETUP_CONTEXT_WINDOW, } from "./shared.mjs";
7
+ import { SETUP_MODEL, agentBaseUrl, readText, configHome, onPath, phantomCommand, offResult, unreadable, SETUP_MARK, SETUP_CONTEXT_WINDOW, claudeModelName, } from "./shared.mjs";
8
+ import { readJsonWas, restoreJsonChanges, trackJsonChanges } from "./was.mjs";
8
9
  import { jsonObject, jsonEdit, tomlSet, tomlRemoveOurs, yamlSetTop, yamlAddModel, yamlRemoveOurs } from "./editors.mjs";
9
10
  /** The most output a model call may ask for, for agents that need a number. */
10
11
  const SETUP_OUTPUT_TOKENS = 32_000;
@@ -13,6 +14,22 @@ function unlessEmpty(file, after) {
13
14
  const left = jsonObject(file, after);
14
15
  return Object.keys(left).every((k) => k === '$schema') ? '' : after;
15
16
  }
17
+ /**
18
+ * The edit that writes `changes` to a JSON settings file, with a record of what the keys in `tracked` held
19
+ * before ({@link trackJsonChanges}), so `--provider off` can put those values back.
20
+ */
21
+ function jsonOn(env, file, text, changes, tracked = changes.map(([p]) => p)) {
22
+ const was = trackJsonChanges(jsonObject(file, text), readJsonWas(env, file), changes, tracked);
23
+ return { file, after: jsonEdit(file, text, changes), was };
24
+ }
25
+ /**
26
+ * The text of a JSON settings file after `--provider off`: `removals` (what the agent's own off step finds that
27
+ * looks like phantom's) with each recorded key put back ({@link restoreJsonChanges}).
28
+ */
29
+ function jsonOffText(env, file, text, removals, tidy = []) {
30
+ const record = readJsonWas(env, file);
31
+ return jsonEdit(file, text, restoreJsonChanges(jsonObject(file, text), record, removals, tidy));
32
+ }
16
33
  // ── Manual Provider Helper ───────────────────────────────────────────────────
17
34
  /** An agent whose model settings live on its own settings screen: setup prints the steps. */
18
35
  export function manualProvider(where, steps, note) {
@@ -68,18 +85,12 @@ export function claudePlan(env, opts) {
68
85
  const ours = typeof settings.apiKeyHelper === 'string' && /(?:pai|phantom).* key show$/.test(settings.apiKeyHelper);
69
86
  const vars = { ...(settings.env ?? {}) };
70
87
  if (opts.off) {
71
- const changes = [];
72
- if (ours) {
73
- changes.push([['apiKeyHelper'], undefined]);
74
- const mine = ['ANTHROPIC_BASE_URL', 'ENABLE_TOOL_SEARCH', 'ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY', ...(vars.ANTHROPIC_API_KEY === '' ? ['ANTHROPIC_API_KEY'] : [])];
75
- if (Object.keys(vars).every((k) => mine.includes(k)))
76
- changes.push([['env'], undefined]);
77
- else
78
- for (const k of mine)
79
- changes.push([['env', k], undefined]);
80
- }
88
+ const mine = ['ANTHROPIC_BASE_URL', 'ENABLE_TOOL_SEARCH', 'ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY', ...(vars.ANTHROPIC_API_KEY === '' ? ['ANTHROPIC_API_KEY'] : [])];
89
+ // Without a record (setup from an older phantom) every key phantom writes is removed; with one,
90
+ // each key goes back to what the user had.
91
+ const removals = [[['apiKeyHelper'], undefined], ...mine.filter((k) => k in vars).map((k) => [['env', k], undefined])];
81
92
  return {
82
- edits: text === null || !ours ? [] : [{ file, after: jsonEdit(file, text, changes) }],
93
+ edits: text === null || !ours ? [] : [{ file, after: jsonOffText(env, file, text, removals, [['env']]), was: null }],
83
94
  result: { settings: file, on: false, warnings: ours ? [] : ['Claude Code was not set to Phantom AI by phantom; nothing changed'] },
84
95
  };
85
96
  }
@@ -96,17 +107,18 @@ export function claudePlan(env, opts) {
96
107
  ENABLE_TOOL_SEARCH: 'true',
97
108
  CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: '1',
98
109
  // phantom-1 unless a model is named, as Codex gets: it runs free until there is credit.
99
- ANTHROPIC_MODEL: opts.model ?? 'claude-code/phantom-1',
100
- // Claude Code's background calls (titles, summaries) and its Explore agent use the
101
- // haiku model. Through phantom-1 they run on Standard instead of Claude Haiku.
102
- ANTHROPIC_DEFAULT_HAIKU_MODEL: 'claude-code/phantom-1',
110
+ ANTHROPIC_MODEL: claudeModelName(opts.model ?? SETUP_MODEL),
111
+ // Claude Code's background calls (titles, summaries) and its Explore agent, which reads the
112
+ // user's code, use the haiku model. It follows the chosen model, so a zero data retention
113
+ // choice (phantom-1:zdr) covers them too. Through phantom-1 they run on Standard instead of Claude Haiku.
114
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: claudeModelName(opts.model ?? SETUP_MODEL),
103
115
  };
104
116
  const changes = [[['apiKeyHelper'], `${phantomCommand(opts.onPath ?? onPath)} key show`], ...Object.entries(set).map(([k, v]) => [['env', k], v])];
105
117
  // A token outranks apiKeyHelper, and would send a non-Phantom key.
106
118
  const warnings = env.ANTHROPIC_AUTH_TOKEN ? ['ANTHROPIC_AUTH_TOKEN is set in this shell and overrides the Phantom key; unset it before running claude'] : [];
107
119
  if (opts.model?.replace(/^claude-code\//, '') === 'auto')
108
120
  warnings.push('auto runs what the key\'s route policy picks; set one with: phantom route set --models a,b');
109
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: baseUrl, model: set.ANTHROPIC_MODEL ?? vars.ANTHROPIC_MODEL, warnings } };
121
+ return { edits: [jsonOn(env, file, text, changes)], result: { settings: file, on: true, base_url: baseUrl, model: set.ANTHROPIC_MODEL ?? vars.ANTHROPIC_MODEL, warnings } };
110
122
  }
111
123
  // ── Copilot ──────────────────────────────────────────────────────────────────
112
124
  /** GitHub Copilot CLI's folder: `$COPILOT_HOME`, else `~/.copilot`. */
@@ -148,9 +160,7 @@ export function opencodeProvider(ctx, off) {
148
160
  const changes = [Object.keys(config.provider ?? {}).length === 1 ? [['provider'], undefined] : [['provider', 'phantom'], undefined]];
149
161
  if (typeof config.model === 'string' && config.model.startsWith('phantom/'))
150
162
  changes.push([['model'], undefined]);
151
- const left = jsonObject(file, ours ? jsonEdit(file, text, changes) : text);
152
- const empty = Object.keys(left).every((k) => k === '$schema');
153
- return offResult('opencode', file, text, ours ? (empty ? '' : jsonEdit(file, text, changes)) : text);
163
+ return offResult('opencode', file, text, ours ? unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)) : text, true);
154
164
  }
155
165
  const base = agentBaseUrl(ctx.env, 'coding-agent');
156
166
  const model = ctx.model ?? SETUP_MODEL;
@@ -163,7 +173,7 @@ export function opencodeProvider(ctx, off) {
163
173
  ...(ctx.model ? [[['model'], `phantom/${ctx.model}`]] : []),
164
174
  ];
165
175
  return {
166
- edits: [{ file, after: jsonEdit(file, text, changes) }],
176
+ edits: [jsonOn(ctx.env, file, text, changes, [['model']])],
167
177
  result: { settings: file, on: true, base_url: base, ...(ctx.model ? { model: `phantom/${ctx.model}` } : {}), warnings: ctx.model ? [] : [`Pick phantom/${model} with /models in opencode`] },
168
178
  };
169
179
  }
@@ -293,7 +303,7 @@ export function clineProvider(ctx, off) {
293
303
  const changes = [[['providers', 'openai-compatible'], undefined]];
294
304
  if (data.lastUsedProvider === 'openai-compatible')
295
305
  changes.push([['lastUsedProvider'], undefined]);
296
- return offResult('Cline', file, text, ours ? jsonEdit(file, text, changes) : text);
306
+ return offResult('Cline', file, text, ours ? jsonOffText(ctx.env, file, text, changes) : text, true);
297
307
  }
298
308
  if (current && !ours)
299
309
  unreadable(file, `already has an OpenAI Compatible provider at ${current.settings?.baseUrl ?? 'another address'}, which phantom leaves alone`);
@@ -312,7 +322,7 @@ export function clineProvider(ctx, off) {
312
322
  [['providers', 'openai-compatible'], entry],
313
323
  ];
314
324
  return {
315
- edits: [{ file, after: jsonEdit(file, text, changes), mode: 0o600 }],
325
+ edits: [{ ...jsonOn(ctx.env, file, text, changes, [['lastUsedProvider']]), mode: 0o600 }],
316
326
  result: {
317
327
  settings: file,
318
328
  on: true,
@@ -342,7 +352,9 @@ export function geminiProvider(ctx, off) {
342
352
  if (off) {
343
353
  const ours = typeof settings.model?.name === 'string' && settings.model.name.startsWith('phantom-');
344
354
  const alone = Object.keys(settings.model ?? {}).length === 1;
345
- return offResult('Gemini CLI', file, text, ours ? jsonEdit(file, text, [[alone ? ['model'] : ['model', 'name'], undefined]]) : text);
355
+ const removals = ours ? [[alone ? ['model'] : ['model', 'name'], undefined]] : [];
356
+ // With a record the sign-in choice goes back too; without one (older setup) it stays, as before.
357
+ return offResult('Gemini CLI', file, text, text === null ? null : jsonOffText(ctx.env, file, text, removals), true);
346
358
  }
347
359
  const model = ctx.model ?? SETUP_MODEL;
348
360
  const changes = [
@@ -350,7 +362,7 @@ export function geminiProvider(ctx, off) {
350
362
  [['model', 'name'], model],
351
363
  ];
352
364
  return {
353
- edits: [{ file, after: jsonEdit(file, text, changes) }],
365
+ edits: [jsonOn(ctx.env, file, text, changes)],
354
366
  result: {
355
367
  settings: file,
356
368
  on: true,
@@ -386,7 +398,7 @@ export function crushProvider(ctx, off) {
386
398
  else
387
399
  for (const k of mine)
388
400
  changes.push([['models', k], undefined]);
389
- return offResult('Crush', file, text, unlessEmpty(file, jsonEdit(file, text, changes)));
401
+ return offResult('Crush', file, text, unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)), true);
390
402
  }
391
403
  const base = agentBaseUrl(ctx.env, 'coding-agent');
392
404
  const model = ctx.model ?? SETUP_MODEL;
@@ -404,7 +416,7 @@ export function crushProvider(ctx, off) {
404
416
  ],
405
417
  ...sizes.map((size) => [['models', size], { provider: 'phantom', model }]),
406
418
  ];
407
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: base, model, warnings: [] } };
419
+ return { edits: [jsonOn(ctx.env, file, text, changes, sizes.map((size) => ['models', size]))], result: { settings: file, on: true, base_url: base, model, warnings: [] } };
408
420
  }
409
421
  // ── Qwen Code ────────────────────────────────────────────────────────────────
410
422
  /** Qwen Code's folder: `$QWEN_HOME`, else `~/.qwen`. */
@@ -439,7 +451,7 @@ export function qwenProvider(ctx, off) {
439
451
  changes.push(Object.keys(config.modelProviders ?? {}).length === 1 ? [['modelProviders'], undefined] : [['modelProviders', 'openai'], undefined]);
440
452
  if (mineIds.includes(config.model?.name))
441
453
  changes.push(Object.keys(config.model ?? {}).length === 1 ? [['model'], undefined] : [['model', 'name'], undefined]);
442
- return offResult('Qwen Code', file, text, unlessEmpty(file, jsonEdit(file, text, changes)));
454
+ return offResult('Qwen Code', file, text, unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)), true);
443
455
  }
444
456
  const model = ctx.model ?? SETUP_MODEL;
445
457
  const entry = { id: model, name: `Phantom AI ${model}`, baseUrl: base, envKey: 'PHANTOM_API_KEY', generationConfig: { contextWindowSize: SETUP_CONTEXT_WINDOW } };
@@ -448,7 +460,8 @@ export function qwenProvider(ctx, off) {
448
460
  [['security', 'auth', 'selectedType'], 'openai'],
449
461
  [['model', 'name'], model],
450
462
  ];
451
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: base, model, warnings: [] } };
463
+ const tracked = [['security', 'auth', 'selectedType'], ['model', 'name']];
464
+ return { edits: [jsonOn(ctx.env, file, text, changes, tracked)], result: { settings: file, on: true, base_url: base, model, warnings: [] } };
452
465
  }
453
466
  // ── Kilo Code ────────────────────────────────────────────────────────────────
454
467
  /** Kilo Code's config file: `kilo.jsonc` (or `kilo.json`) in `$XDG_CONFIG_HOME/kilo`, else `~/.config/kilo`. */
@@ -472,7 +485,7 @@ export function kiloProvider(ctx, off) {
472
485
  const changes = [Object.keys(config.provider).length === 1 ? [['provider'], undefined] : [['provider', 'phantom'], undefined]];
473
486
  if (typeof config.model === 'string' && config.model.startsWith('phantom/'))
474
487
  changes.push([['model'], undefined]);
475
- return offResult('Kilo Code', file, text, unlessEmpty(file, jsonEdit(file, text, changes)));
488
+ return offResult('Kilo Code', file, text, unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)), true);
476
489
  }
477
490
  const base = agentBaseUrl(ctx.env, 'coding-agent');
478
491
  const model = ctx.model ?? SETUP_MODEL;
@@ -490,7 +503,7 @@ export function kiloProvider(ctx, off) {
490
503
  ],
491
504
  [['model'], `phantom/${model}`],
492
505
  ];
493
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: base, model: `phantom/${model}`, warnings: [] } };
506
+ return { edits: [jsonOn(ctx.env, file, text, changes, [['model']])], result: { settings: file, on: true, base_url: base, model: `phantom/${model}`, warnings: [] } };
494
507
  }
495
508
  // ── Kimi Code ────────────────────────────────────────────────────────────────
496
509
  /** Kimi Code's folder: `$KIMI_CODE_HOME`, else `~/.kimi-code`. */
@@ -548,7 +561,7 @@ export function droidProvider(ctx, off) {
548
561
  const changes = [[['customModels'], rest.length ? rest : undefined]];
549
562
  if (mine(config.model))
550
563
  changes.push([['model'], undefined]);
551
- return offResult('Droid', file, text, unlessEmpty(file, jsonEdit(file, text, changes)));
564
+ return offResult('Droid', file, text, unlessEmpty(file, jsonOffText(ctx.env, file, text, changes)), true);
552
565
  }
553
566
  const model = ctx.model ?? SETUP_MODEL;
554
567
  const entry = { model, displayName: DROID_NAME, baseUrl: base, apiKey: '${PHANTOM_API_KEY}', provider: 'generic-chat-completion-api', maxOutputTokens: SETUP_OUTPUT_TOKENS };
@@ -560,7 +573,7 @@ export function droidProvider(ctx, off) {
560
573
  [['customModels'], next],
561
574
  [['model'], id],
562
575
  ];
563
- return { edits: [{ file, after: jsonEdit(file, text, changes) }], result: { settings: file, on: true, base_url: base, model: id, warnings: [] } };
576
+ return { edits: [jsonOn(ctx.env, file, text, changes, [['model']])], result: { settings: file, on: true, base_url: base, model: id, warnings: [] } };
564
577
  }
565
578
  // ── Mistral Vibe ─────────────────────────────────────────────────────────────
566
579
  /**
@@ -612,7 +625,7 @@ export function zedProvider(ctx, off) {
612
625
  const changes = [[['language_models', 'openai_compatible', 'phantom'], undefined]];
613
626
  if (config.agent?.default_model?.provider === 'phantom')
614
627
  changes.push([['agent', 'default_model'], undefined]);
615
- return offResult('Zed', file, text, jsonEdit(file, text, changes));
628
+ return offResult('Zed', file, text, jsonOffText(ctx.env, file, text, changes, [['language_models', 'openai_compatible']]), true);
616
629
  }
617
630
  const base = agentBaseUrl(ctx.env, 'coding-agent');
618
631
  const model = ctx.model ?? SETUP_MODEL;
@@ -624,7 +637,7 @@ export function zedProvider(ctx, off) {
624
637
  [['agent', 'default_model'], { provider: 'phantom', model }],
625
638
  ];
626
639
  return {
627
- edits: [{ file, after: jsonEdit(file, text, changes) }],
640
+ edits: [jsonOn(ctx.env, file, text, changes, [['agent', 'default_model']])],
628
641
  result: { settings: file, on: true, base_url: base, model, warnings: ['Zed reads PHANTOM_API_KEY from your login shell; quit and reopen Zed'] },
629
642
  };
630
643
  }
@@ -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')