@phantomcodes/cli 1.4.1 → 1.4.3

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 +99 -133
  2. package/dist/agents/command.d.mts +36 -0
  3. package/dist/agents/command.mjs +22 -10
  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 +2 -2
  8. package/dist/cli/commands.d.mts +23 -0
  9. package/dist/cli/commands.mjs +106 -54
  10. package/dist/cli/help.d.mts +26 -0
  11. package/dist/cli/help.mjs +10 -6
  12. package/dist/cli/run.d.mts +2 -0
  13. package/dist/cli/screens.d.mts +171 -0
  14. package/dist/cli/screens.mjs +3 -3
  15. package/dist/cli/start.d.mts +34 -0
  16. package/dist/core/brand.d.mts +12 -0
  17. package/dist/core/errors.d.mts +27 -0
  18. package/dist/core/free.d.mts +13 -0
  19. package/dist/core/helpers.d.mts +75 -0
  20. package/dist/core/helpers.mjs +27 -2
  21. package/dist/core/motion.d.mts +47 -0
  22. package/dist/core/node-trust.d.mts +12 -0
  23. package/dist/core/pick.d.mts +86 -0
  24. package/dist/core/request.d.mts +64 -0
  25. package/dist/core/request.mjs +78 -29
  26. package/dist/core/secrets.d.mts +33 -0
  27. package/dist/core/shapes.d.mts +13 -0
  28. package/dist/core/state.d.mts +3 -0
  29. package/dist/core/style.d.mts +49 -0
  30. package/dist/core/version.d.mts +2 -0
  31. package/dist/core/version.mjs +1 -1
  32. package/dist/keys/command.d.mts +16 -0
  33. package/dist/keys/saved.d.mts +90 -0
  34. package/dist/keys/saved.mjs +6 -2
  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/receipts/command.d.mts +7 -0
  41. package/dist/receipts/receipts.d.mts +67 -0
  42. package/dist/receipts/receipts.mjs +15 -11
  43. package/dist/setup/agents.d.mts +149 -0
  44. package/dist/setup/agents.mjs +50 -37
  45. package/dist/setup/apply.d.mts +71 -0
  46. package/dist/setup/apply.mjs +7 -2
  47. package/dist/setup/command.d.mts +12 -0
  48. package/dist/setup/command.mjs +32 -5
  49. package/dist/setup/editors.d.mts +101 -0
  50. package/dist/setup/editors.mjs +6 -4
  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/screen.mjs +2 -2
  56. package/dist/setup/shared.d.mts +141 -0
  57. package/dist/setup/shared.mjs +8 -2
  58. package/dist/setup/was.d.mts +42 -0
  59. package/dist/setup/was.mjs +91 -0
  60. package/dist/spend/command.d.mts +5 -0
  61. package/dist/spend/lineup.d.mts +54 -0
  62. package/dist/spend/lineup.mjs +3 -2
  63. package/dist/spend/report.d.mts +105 -0
  64. package/dist/spend/report.mjs +2 -2
  65. package/dist/spend/routing.d.mts +72 -0
  66. package/dist/workspace/command.d.mts +59 -0
  67. package/dist/workspace/command.mjs +106 -52
  68. package/package.json +7 -7
  69. package/skills/phantom-ai/SKILL.md +40 -66
@@ -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
  }
@@ -280,7 +290,7 @@ export function aiderProvider(ctx, off) {
280
290
  * Compatible provider at `/coding-agent/v1` and is made the one Cline uses.
281
291
  * Cline reads its key only from this file, with no variable or command to
282
292
  * point it at, so this is the one config phantom writes the key into. After
283
- * `phantom rotate`, run setup again to update it.
293
+ * `phantom keys rotate`, run setup again to update it.
284
294
  */
285
295
  export function clineProvider(ctx, off) {
286
296
  const file = path.join(ctx.home, '.cline', 'data', 'settings', 'providers.json');
@@ -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,13 +322,13 @@ 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,
319
329
  base_url: base,
320
330
  model,
321
- warnings: ['Cline keeps the key in this file (mode 600); run phantom setup --agent cline --provider again after phantom rotate', 'In the editor extension, pick OpenAI Compatible under Settings, API Provider'],
331
+ warnings: ['Cline keeps the key in this file (mode 600); run phantom setup --agent cline --provider again after phantom keys rotate', 'In the editor extension, pick OpenAI Compatible under Settings, API Provider'],
322
332
  },
323
333
  };
324
334
  }
@@ -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>;
@@ -5,8 +5,9 @@ import { die } from "../core/errors.mjs";
5
5
  import { out, pickIo } from "../core/helpers.mjs";
6
6
  import { BackToMenu, checklist, choose } from "../core/pick.mjs";
7
7
  import { request } from "../core/request.mjs";
8
- import { resolveApiKey } from "../keys/saved.mjs";
9
- import { workspaceLogin } from "../workspace/command.mjs";
8
+ import { PhantomApiError } from "../core/errors.mjs";
9
+ import { keyHash, resolveApiKey } from "../keys/saved.mjs";
10
+ import { savedWorkspace, wire, workspaceLogin } from "../workspace/command.mjs";
10
11
  import { SETUP_AGENTS, SETUP_NAMES } from "./agents.mjs";
11
12
  import { planSetup } from "./plan.mjs";
12
13
  import { applySetup, previewSetup, restoreSetup } from "./apply.mjs";
@@ -75,7 +76,7 @@ export async function setupCommand(input) {
75
76
  if (model === true)
76
77
  die('--model requires a model id, such as auto or claude-sonnet-5');
77
78
  if (flags['mcp'])
78
- die('--mcp has been removed. Phantom inference runs directly through phantom claude, phantom codex, or phantom pi.');
79
+ die('--mcp has been removed. Start your agent on Phantom AI with phantom claude, phantom codex or phantom pi.');
79
80
  const dryRun = Boolean(flags['dry-run']);
80
81
  if (flags['restore']) {
81
82
  // At a terminal, undo shows what it will put back, and asks, the way setup asks before it changes anything.
@@ -237,6 +238,28 @@ function capFlag(value) {
237
238
  die('--limit takes dollars a month above zero, such as 20, or none', 'setup_limit');
238
239
  return usd;
239
240
  }
241
+ /**
242
+ * Sets the key's monthly cap. The key alone may only tighten its caps (the
243
+ * server answers 403 to a raise or a removal), so that change goes through the
244
+ * workspace this computer is signed in to, whose credential may set any cap.
245
+ * False when the key alone may not make the change and no workspace is saved.
246
+ */
247
+ async function setMonthlyCap(input, apiKey, cap) {
248
+ const body = cap === null ? { budget_usd: null } : { budget_usd: cap, period_days: null };
249
+ try {
250
+ await request('PATCH', '/key/budget', apiKey, body, input.baseUrl);
251
+ return true;
252
+ }
253
+ catch (err) {
254
+ if (!(err instanceof PhantomApiError) || err.status !== 403)
255
+ throw err;
256
+ }
257
+ const workspace = savedWorkspace(input);
258
+ if (!workspace)
259
+ return false;
260
+ await wire(workspace.base_url, 'PATCH', `/workspaces/${encodeURIComponent(workspace.workspace_id)}/keys/${keyHash(apiKey)}`, body, workspace.management_credential);
261
+ return true;
262
+ }
240
263
  /**
241
264
  * After setup has written its files: the key's monthly spend cap (PATCH
242
265
  * /key/budget, a calendar month). `--limit` sets it; without one, setup at a
@@ -254,7 +277,7 @@ async function capAfter(input, code, limit, pick) {
254
277
  return code;
255
278
  io.stderr('\n');
256
279
  const answer = await choose(pick, 'Cap what this key can spend each month?', [
257
- { label: 'No cap', hint: 'free use is never charged', value: 0 },
280
+ { label: 'No cap', hint: 'it can spend the whole workspace balance; free models cost nothing', value: 0 },
258
281
  { label: '$10 a month', value: 10 },
259
282
  { label: '$25 a month', value: 25 },
260
283
  { label: '$50 a month', value: 50 },
@@ -263,8 +286,12 @@ async function capAfter(input, code, limit, pick) {
263
286
  return code;
264
287
  cap = answer;
265
288
  }
266
- await request('PATCH', '/key/budget', apiKey, cap === null ? { budget_usd: null } : { budget_usd: cap, period_days: null }, baseUrl);
267
289
  const p = paint(env, colorOn(env, io.isTTY));
290
+ if (!(await setMonthlyCap(input, apiKey, cap))) {
291
+ io.stderr(` ${p.yellow('!')} The key's cap is unchanged. The key alone can only lower its cap; raising or removing it needs its workspace.\n` +
292
+ ` Run ${p.cyan('phantom login')}, then ${p.cyan(`phantom setup --limit ${cap === null ? 'none' : cap}`)} again, or change it in Edit controls on phantom.codes/keys.\n`);
293
+ return 1;
294
+ }
268
295
  io.stderr(cap === null
269
296
  ? ` ${p.lime('✓')} This key has no monthly cap now.\n`
270
297
  : ` ${p.lime('✓')} This key can spend at most $${cap} a month. Change it any time: ${p.cyan('phantom setup --limit <USD|none>')}\n`);
@@ -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]))
@@ -370,8 +372,8 @@ export function shellBlock(env, fish, state, onPathFn = onPath) {
370
372
  const own = state.agents.flatMap((a) => state.lines.get(a) ?? []);
371
373
  const head = [
372
374
  BLOCK_BEGIN,
373
- '# Written by phantom setup. Sets PHANTOM_API_KEY to the key phantom uses when the',
374
- '# shell starts, for coding agents that read it. The key is not stored here.',
375
+ '# Written by phantom setup. A new shell gets PHANTOM_API_KEY from phantom,',
376
+ '# for the coding agents that read it. The key itself is not in this file.',
375
377
  `# agents: ${state.agents.join(' ')}`,
376
378
  '# Undo: phantom setup --restore',
377
379
  ];
@@ -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;