@phantomcodes/cli 1.6.3 → 1.7.1

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 (140) hide show
  1. package/LICENSE +1 -2
  2. package/README.md +139 -118
  3. package/bin/phantom.mjs +37 -2
  4. package/dist/agents/command.d.mts +8 -27
  5. package/dist/agents/command.mjs +323 -59
  6. package/dist/agents/login.d.mts +3 -0
  7. package/dist/agents/login.mjs +97 -0
  8. package/dist/agents/opencode-check.d.mts +15 -0
  9. package/dist/agents/opencode-check.mjs +193 -0
  10. package/dist/agents/phantom-key.d.mts +7 -0
  11. package/dist/agents/phantom-key.mjs +40 -0
  12. package/dist/agents/proxy.d.mts +26 -28
  13. package/dist/agents/proxy.mjs +225 -33
  14. package/dist/chatgpt/command.d.mts +2 -0
  15. package/dist/chatgpt/command.mjs +119 -0
  16. package/dist/chatgpt/session.d.mts +87 -0
  17. package/dist/chatgpt/session.mjs +253 -0
  18. package/dist/cli/accounts.d.mts +21 -0
  19. package/dist/cli/accounts.mjs +96 -0
  20. package/dist/cli/app.d.mts +4 -24
  21. package/dist/cli/app.mjs +224 -139
  22. package/dist/cli/commands.d.mts +1 -16
  23. package/dist/cli/commands.mjs +144 -239
  24. package/dist/cli/help.d.mts +0 -19
  25. package/dist/cli/help.mjs +30 -55
  26. package/dist/cli/run.mjs +35 -79
  27. package/dist/cli/start.d.mts +2 -31
  28. package/dist/cli/start.mjs +13 -116
  29. package/dist/core/brand.d.mts +0 -7
  30. package/dist/core/brand.mjs +0 -8
  31. package/dist/core/errors.d.mts +0 -16
  32. package/dist/core/errors.mjs +0 -16
  33. package/dist/core/helpers.d.mts +0 -46
  34. package/dist/core/helpers.mjs +1 -64
  35. package/dist/core/node-trust.d.mts +0 -5
  36. package/dist/core/node-trust.mjs +0 -6
  37. package/dist/core/pick.d.mts +7 -55
  38. package/dist/core/pick.mjs +49 -106
  39. package/dist/core/request.d.mts +0 -46
  40. package/dist/core/request.mjs +1 -60
  41. package/dist/core/secrets.d.mts +0 -4
  42. package/dist/core/secrets.mjs +0 -10
  43. package/dist/core/state.d.mts +3 -1
  44. package/dist/core/state.mjs +147 -4
  45. package/dist/core/style.d.mts +0 -27
  46. package/dist/core/style.mjs +0 -20
  47. package/dist/core/version.d.mts +1 -2
  48. package/dist/core/version.mjs +1 -2
  49. package/dist/local/accounts.d.mts +25 -0
  50. package/dist/local/accounts.mjs +40 -0
  51. package/dist/local/agent-headers.d.mts +7 -0
  52. package/dist/local/agent-headers.mjs +44 -0
  53. package/dist/local/chatgpt-plan.d.mts +147 -0
  54. package/dist/local/chatgpt-plan.mjs +384 -0
  55. package/dist/local/command.d.mts +24 -0
  56. package/dist/local/command.mjs +211 -0
  57. package/dist/local/config.d.mts +49 -0
  58. package/dist/local/config.mjs +168 -0
  59. package/dist/local/decide.d.mts +37 -0
  60. package/dist/local/decide.mjs +201 -0
  61. package/dist/local/failure-signs.d.mts +4 -0
  62. package/dist/local/failure-signs.mjs +99 -0
  63. package/dist/local/keys.d.mts +32 -0
  64. package/dist/local/keys.mjs +239 -0
  65. package/dist/local/models.d.mts +53 -0
  66. package/dist/local/models.mjs +117 -0
  67. package/dist/local/replay.d.mts +59 -0
  68. package/dist/local/replay.mjs +143 -0
  69. package/dist/local/report.d.mts +43 -0
  70. package/dist/local/report.mjs +153 -0
  71. package/dist/local/request-log.d.mts +53 -0
  72. package/dist/local/request-log.mjs +69 -0
  73. package/dist/local/retry-after.d.mts +3 -0
  74. package/dist/local/retry-after.mjs +28 -0
  75. package/dist/local/rust-router.d.mts +39 -0
  76. package/dist/local/rust-router.mjs +54 -0
  77. package/dist/local/server.d.mts +27 -0
  78. package/dist/local/server.mjs +449 -0
  79. package/dist/local/status-line.d.mts +17 -0
  80. package/dist/local/status-line.mjs +81 -0
  81. package/dist/local/tiers.d.mts +3 -0
  82. package/dist/local/tiers.mjs +137 -0
  83. package/dist/local/traces.d.mts +69 -0
  84. package/dist/local/traces.mjs +341 -0
  85. package/dist/phantom.d.mts +0 -37
  86. package/dist/phantom.mjs +0 -31
  87. package/package.json +15 -9
  88. package/skills/phantom-ai/SKILL.md +28 -97
  89. package/dist/cli/screens.d.mts +0 -177
  90. package/dist/cli/screens.mjs +0 -398
  91. package/dist/core/free.d.mts +0 -13
  92. package/dist/core/free.mjs +0 -14
  93. package/dist/core/motion.d.mts +0 -47
  94. package/dist/core/motion.mjs +0 -156
  95. package/dist/core/shapes.d.mts +0 -13
  96. package/dist/core/shapes.mjs +0 -1
  97. package/dist/keys/command.d.mts +0 -16
  98. package/dist/keys/command.mjs +0 -143
  99. package/dist/keys/saved.d.mts +0 -96
  100. package/dist/keys/saved.mjs +0 -169
  101. package/dist/models/choice.d.mts +0 -7
  102. package/dist/models/choice.mjs +0 -27
  103. package/dist/models/command.d.mts +0 -8
  104. package/dist/models/command.mjs +0 -66
  105. package/dist/models/list.d.mts +0 -39
  106. package/dist/models/list.mjs +0 -39
  107. package/dist/receipts/command.d.mts +0 -7
  108. package/dist/receipts/command.mjs +0 -41
  109. package/dist/receipts/receipts.d.mts +0 -76
  110. package/dist/receipts/receipts.mjs +0 -118
  111. package/dist/setup/agents.d.mts +0 -149
  112. package/dist/setup/agents.mjs +0 -886
  113. package/dist/setup/apply.d.mts +0 -85
  114. package/dist/setup/apply.mjs +0 -301
  115. package/dist/setup/command.d.mts +0 -12
  116. package/dist/setup/command.mjs +0 -307
  117. package/dist/setup/editors.d.mts +0 -108
  118. package/dist/setup/editors.mjs +0 -500
  119. package/dist/setup/legacy.d.mts +0 -13
  120. package/dist/setup/legacy.mjs +0 -36
  121. package/dist/setup/plan.d.mts +0 -104
  122. package/dist/setup/plan.mjs +0 -132
  123. package/dist/setup/screen.d.mts +0 -30
  124. package/dist/setup/screen.mjs +0 -260
  125. package/dist/setup/shared.d.mts +0 -141
  126. package/dist/setup/shared.mjs +0 -88
  127. package/dist/setup/was.d.mts +0 -42
  128. package/dist/setup/was.mjs +0 -91
  129. package/dist/spend/command.d.mts +0 -5
  130. package/dist/spend/command.mjs +0 -235
  131. package/dist/spend/lineup.d.mts +0 -61
  132. package/dist/spend/lineup.mjs +0 -39
  133. package/dist/spend/reason.d.mts +0 -5
  134. package/dist/spend/reason.mjs +0 -60
  135. package/dist/spend/report.d.mts +0 -105
  136. package/dist/spend/report.mjs +0 -68
  137. package/dist/spend/routing.d.mts +0 -74
  138. package/dist/spend/routing.mjs +0 -57
  139. package/dist/workspace/command.d.mts +0 -59
  140. package/dist/workspace/command.mjs +0 -871
@@ -1,500 +0,0 @@
1
- import path from 'node:path';
2
- import os from 'node:os';
3
- import { isDeepStrictEqual } from 'node:util';
4
- import { applyEdits, format as formatJsonc, modify as modifyJsonc, parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
5
- import { parse as parseTomlText } from 'smol-toml';
6
- import { KEYCHAIN_SERVICE, KEYCHAIN_POINTER, keychainOn } from "../core/secrets.mjs";
7
- import { keyPath } from "../keys/saved.mjs";
8
- import { SETUP_MARK, SETUP_WAS, setupMarked, stripMark, unwas, unreadable, onPath, phantomCommand, configHome } from "./shared.mjs";
9
- // ── JSON & JSONC ─────────────────────────────────────────────────────────────
10
- /**
11
- * A JSON or JSONC file's object, `{}` when it does not exist. Comments and
12
- * trailing commas are fine: jsonc-parser reads them, as in Vercel's setup.
13
- */
14
- export function jsonObject(file, text) {
15
- if (text === null || text.trim() === '')
16
- return {};
17
- const errors = [];
18
- const v = parseJsonc(text, errors, { allowTrailingComma: true });
19
- if (errors.length)
20
- unreadable(file, `is not valid JSON (${printParseErrorCode(errors[0].error)} at offset ${errors[0].offset})`);
21
- if (!v || typeof v !== 'object' || Array.isArray(v))
22
- unreadable(file, 'does not hold a JSON object');
23
- return v;
24
- }
25
- export function jsonText(v) {
26
- return JSON.stringify(v, null, 2) + '\n';
27
- }
28
- const isPlainObject = (v) => Boolean(v) && typeof v === 'object' && !Array.isArray(v);
29
- /** The value at a path of keys, or undefined. */
30
- export function jsonGet(obj, p) {
31
- return p.reduce((n, k) => (isPlainObject(n) ? n[k] : undefined), obj);
32
- }
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) {
35
- let n = obj;
36
- for (const k of p.slice(0, -1)) {
37
- if (!isPlainObject(n[k]))
38
- n[k] = {};
39
- n = n[k];
40
- }
41
- if (value === undefined)
42
- delete n[p[p.length - 1]];
43
- else
44
- n[p[p.length - 1]] = value;
45
- }
46
- /** The indent and line ending a JSON file already uses, for the lines an edit adds. */
47
- function jsonFormatting(text) {
48
- const indent = /\n([ \t]+)\S/.exec(text)?.[1] ?? ' ';
49
- return { insertSpaces: !indent.startsWith('\t'), tabSize: indent.startsWith('\t') ? 1 : indent.length, eol: text.includes('\r\n') ? '\r\n' : '\n' };
50
- }
51
- /**
52
- * Applies `changes` to a JSON or JSONC file's text with jsonc-parser's
53
- * `modify` and `applyEdits`, as Vercel's setup does, so comments, key order
54
- * and formatting stay as they were. Only the text an edit inserts is
55
- * formatted, in the file's own indent (none in a one-line file), so removing
56
- * what was added gives back the same bytes. A new file is written in full. If
57
- * the edited text doesn't read back as expected, the file is written in full
58
- * instead, as Vercel's does.
59
- * @throws {@link CliError} `setup_unreadable` when the file is not valid JSON or JSONC.
60
- * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
61
- */
62
- export function jsonEdit(file, text, changes) {
63
- const expected = jsonObject(file, text);
64
- const todo = changes.filter(([p, v]) => !isDeepStrictEqual(jsonGet(expected, p), v));
65
- for (const [p, v] of todo)
66
- jsonSet(expected, p, v);
67
- if (text === null || text.trim() === '')
68
- return jsonText(expected);
69
- if (!todo.length)
70
- return text;
71
- const formatting = text.trim().includes('\n') ? jsonFormatting(text) : null;
72
- let out = text;
73
- try {
74
- for (const [p, v] of todo) {
75
- const edits = modifyJsonc(out, p, v, {});
76
- out = applyEdits(out, edits);
77
- if (formatting && v !== undefined && edits.length === 1)
78
- out = applyEdits(out, formatJsonc(out, { offset: edits[0].offset, length: edits[0].content.length }, formatting));
79
- }
80
- if (isDeepStrictEqual(jsonObject(file, out), expected))
81
- return out;
82
- }
83
- catch {
84
- // Written in full below.
85
- }
86
- return jsonText(expected);
87
- }
88
- // ── YAML ─────────────────────────────────────────────────────────────────────
89
- // YAML, line by line: one entry at the top of Continue's `models:` list, and
90
- // top-level keys such as Goose's GOOSE_PROVIDER and Aider's `model`.
91
- /**
92
- * Sets a top-level `key: value` in a YAML file, marked `# phantom setup`. A line
93
- * it replaces stays as a comment, so `--provider off` can put it back.
94
- * @throws {@link CliError} `setup_unreadable` when the file indents with tabs, or the key holds more than one line.
95
- * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
96
- */
97
- export function yamlSetTop(file, text, key, value) {
98
- const base = text ?? '';
99
- if (/^ *\t/m.test(base))
100
- unreadable(file, 'indents with tabs, which YAML does not allow');
101
- const lines = base === '' ? [] : base.replace(/\n$/, '').split('\n');
102
- const mine = `${key}: ${value} ${SETUP_MARK}`;
103
- const at = lines.findIndex((l) => l.startsWith(`${key}:`));
104
- if (at !== -1) {
105
- if (lines[at].replace(/\s+#.*$/, '') === `${key}: ${value}`)
106
- return base;
107
- if (/^\S+:\s*(#.*)?$/.test(lines[at]) || /^\s/.test(lines[at + 1] ?? ''))
108
- unreadable(file, `holds ${key} over several lines; set it by hand`);
109
- lines.splice(at, 1, ...(setupMarked(lines[at]) ? [] : [SETUP_WAS + lines[at]]), mine);
110
- }
111
- else
112
- lines.push(mine);
113
- return lines.join('\n') + '\n';
114
- }
115
- /**
116
- * Adds `item` (lines, unindented, the first starting with `- `) first in the
117
- * top-level `models:` list of a YAML file, each line marked `# phantom setup`.
118
- * Starts the list when there is none, and the file with `head` when it is
119
- * empty. An entry phantom added before is replaced.
120
- * @throws {@link CliError} `setup_unreadable` when the file indents with tabs or writes the list on one line.
121
- * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
122
- */
123
- export function yamlAddModel(file, text, item, head = []) {
124
- const base = yamlRemoveOurs(file, text ?? '');
125
- const lines = base === '' ? [] : base.replace(/\n$/, '').split('\n');
126
- const at = lines.findIndex((l) => /^models\s*:/.test(l));
127
- if (at !== -1 && !/^models\s*:\s*(#.*)?$/.test(lines[at]))
128
- unreadable(file, 'writes models: on one line, which phantom does not edit; add the model by hand');
129
- let indent = ' ';
130
- for (let n = at + 1; at !== -1 && n < lines.length; n++) {
131
- if (lines[n].trim() === '' || lines[n].trim().startsWith('#'))
132
- continue;
133
- const m = /^(\s*)-/.exec(lines[n]);
134
- if (m)
135
- indent = m[1];
136
- break;
137
- }
138
- const mark = (l) => `${l} ${SETUP_MARK}`;
139
- const entry = item.map((l, k) => mark(indent + (k === 0 ? l : ' ' + l)));
140
- if (at !== -1)
141
- lines.splice(at + 1, 0, ...entry);
142
- else {
143
- if (lines.length === 0)
144
- lines.push(...head.map(mark));
145
- else if (lines[lines.length - 1].trim() !== '')
146
- lines.push('');
147
- lines.push('models:', ...entry);
148
- }
149
- return lines.join('\n') + '\n';
150
- }
151
- /**
152
- * 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.
153
- * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
154
- */
155
- export function yamlRemoveOurs(file, text) {
156
- if (/^ *\t/m.test(text))
157
- unreadable(file, 'indents with tabs, which YAML does not allow');
158
- const kept = text
159
- .split('\n')
160
- .filter((l) => !setupMarked(l))
161
- .map(unwas);
162
- const left = kept.filter((l) => l.trim() !== '');
163
- const empty = left.length === 0 || (left.length === 1 && /^models\s*:\s*$/.test(left[0]));
164
- return empty && kept.length < text.split('\n').length ? '' : kept.join('\n');
165
- }
166
- // ── TOML ─────────────────────────────────────────────────────────────────────
167
- // TOML. smol-toml, the parser Vercel's `ai-gateway setup` uses, checks each
168
- // file before an edit and after it. The edit itself goes line by line, so
169
- // comments and every table phantom does not touch stay as they were.
170
- const TOML_HEADER = /^\s*\[(\[)?\s*([^\]]*?)\s*\]\]?\s*(?:#.*)?$/;
171
- /** Parses TOML text, or refuses the file as one setup can't edit. */
172
- function readToml(file, text) {
173
- try {
174
- return parseTomlText(text);
175
- }
176
- catch (err) {
177
- unreadable(file, `is not valid TOML (${err.message.split('\n')[0]})`);
178
- }
179
- }
180
- /** TOML data as text with sorted keys, to compare two parses. */
181
- function tomlCanonical(v) {
182
- return JSON.stringify(v, (_, x) => x && typeof x === 'object' && !Array.isArray(x) && !(x instanceof Date) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x);
183
- }
184
- /** A table name as written in a header, with the spaces around its dots taken out. */
185
- function tomlHeaderName(name) {
186
- return name
187
- .split('.')
188
- .map((s) => s.trim())
189
- .join('.');
190
- }
191
- function tomlName(p) {
192
- return p.map((k) => (/^[A-Za-z0-9_-]+$/.test(k) ? k : JSON.stringify(k))).join('.');
193
- }
194
- /** True when any line has text. */
195
- function hasText(lines) {
196
- return lines.some((l) => l.trim() !== '');
197
- }
198
- /** The lines as file text, ending in a newline. */
199
- function linesText(lines, crlf) {
200
- const out = [...lines];
201
- if (out.length && out[out.length - 1] !== '')
202
- out.push('');
203
- return out.join(crlf ? '\r\n' : '\n');
204
- }
205
- /**
206
- * Sets `key` in `table` ([] is the top of the file) to `value`, written as
207
- * TOML, and marks the line with `# phantom setup`. A line it replaces stays as a
208
- * comment, so `--provider off` can put it back. A missing table is added at
209
- * the end of the file. The result must parse to the old file with this one
210
- * key changed.
211
- * @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.
212
- * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
213
- */
214
- export function tomlSet(file, text, table, key, value) {
215
- const crlf = text.includes('\r\n');
216
- const expected = hasText(text.split('\n')) ? readToml(file, text) : {};
217
- let node = expected;
218
- for (const part of table) {
219
- const next = node[part] ?? (node[part] = {});
220
- if (!next || typeof next !== 'object' || Array.isArray(next))
221
- unreadable(file, `has ${tomlName(table)} as something other than a table; set it by hand`);
222
- node = next;
223
- }
224
- const parsedValue = parseTomlText(`v = ${value}`).v;
225
- if (tomlCanonical(node[key]) === tomlCanonical(parsedValue))
226
- return text;
227
- node[key] = parsedValue;
228
- const lines = hasText(text.split('\n')) ? text.replace(/\r\n/g, '\n').split('\n') : [];
229
- const mine = `${tomlName([key])} = ${value} ${SETUP_MARK}`;
230
- const name = tomlName(table);
231
- const headers = lines.map((l, i) => ({ i, m: TOML_HEADER.exec(l) })).filter((h) => h.m && !lines[h.i].trim().startsWith('#'));
232
- const own = headers.find((h) => !h.m[1] && tomlHeaderName(h.m[2]) === name);
233
- let start = -1;
234
- let end = lines.length;
235
- if (table.length === 0) {
236
- start = 0;
237
- end = headers[0]?.i ?? lines.length;
238
- }
239
- else if (own) {
240
- start = own.i + 1;
241
- end = headers.find((h) => h.i > own.i)?.i ?? lines.length;
242
- }
243
- if (start === -1) {
244
- while (lines.length && lines[lines.length - 1].trim() === '')
245
- lines.pop();
246
- if (lines.length)
247
- lines.push('');
248
- lines.push(`[${name}] ${SETUP_MARK}`, mine);
249
- }
250
- else {
251
- const assignment = new RegExp(`^\\s*${RegExp.escape(key)}\\s*=`);
252
- const at = lines.slice(start, end).findIndex((l) => assignment.test(l));
253
- if (at !== -1) {
254
- const old = lines[start + at];
255
- lines.splice(start + at, 1, ...(setupMarked(old) ? [] : [SETUP_WAS + old]), mine);
256
- }
257
- else {
258
- let last = -1;
259
- for (let i = start; i < end; i++)
260
- if (lines[i].trim() !== '' && !lines[i].trim().startsWith('#'))
261
- last = i;
262
- if (last !== -1)
263
- lines.splice(last + 1, 0, mine);
264
- else if (table.length)
265
- lines.splice(start, 0, mine);
266
- else if (headers.length) {
267
- // Nothing at the top yet: go above the first table and the comments on it.
268
- let i = headers[0].i;
269
- while (i > 0 && lines[i - 1].trim().startsWith('#'))
270
- i--;
271
- lines.splice(i, 0, mine, '');
272
- }
273
- else {
274
- while (lines.length && lines[lines.length - 1].trim() === '')
275
- lines.pop();
276
- lines.push(mine);
277
- }
278
- }
279
- }
280
- const result = linesText(lines, crlf);
281
- let after = '';
282
- try {
283
- after = tomlCanonical(parseTomlText(result));
284
- }
285
- catch {
286
- // Checked below.
287
- }
288
- if (after !== tomlCanonical(expected))
289
- unreadable(file, `sets ${tomlName([...table, key])} in a way phantom can't edit line by line (an inline table, a dotted key or a value over several lines); set it by hand`);
290
- return result;
291
- }
292
- /**
293
- * Removes what {@link tomlSet} wrote: each line marked `# phantom setup`, and a
294
- * table phantom added once nothing else is left in it. Lines it replaced come back.
295
- * @throws {@link CliError} `setup_unreadable` when the file is not valid TOML, before or after.
296
- * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
297
- */
298
- export function tomlRemoveOurs(file, text) {
299
- const crlf = text.includes('\r\n');
300
- if (hasText(text.split('\n')))
301
- readToml(file, text);
302
- const lines = text.replace(/\r\n/g, '\n').split('\n');
303
- const marked = (i) => !lines[i].trim().startsWith('#') && setupMarked(lines[i]);
304
- const headers = lines.map((l, i) => (TOML_HEADER.test(l) && !l.trim().startsWith('#') ? i : -1)).filter((i) => i !== -1);
305
- const drop = new Set();
306
- for (let i = 0; i < lines.length; i++)
307
- if (marked(i) && !headers.includes(i))
308
- drop.add(i);
309
- for (const [k, h] of headers.entries()) {
310
- if (!marked(h))
311
- continue;
312
- const next = headers[k + 1] ?? lines.length;
313
- let keysLeft = false;
314
- for (let i = h + 1; i < next; i++)
315
- if (!drop.has(i) && lines[i].trim() !== '' && !lines[i].trim().startsWith('#'))
316
- keysLeft = true;
317
- if (keysLeft) {
318
- lines[h] = stripMark(lines[h]);
319
- continue;
320
- }
321
- drop.add(h);
322
- if (h > 0 && lines[h - 1].trim() === '')
323
- drop.add(h - 1);
324
- }
325
- const kept = lines.filter((_, i) => !drop.has(i)).map(unwas);
326
- const result = hasText(kept) ? linesText(kept, crlf) : '';
327
- if (result)
328
- readToml(file, result);
329
- return result;
330
- }
331
- // ── Shell Block ──────────────────────────────────────────────────────────────
332
- const BLOCK_BEGIN = '# >>> phantom setup >>>';
333
- const BLOCK_END = '# <<< phantom setup <<<';
334
- /** The block markers pai, this CLI's old name, wrote. Setup still finds that block. */
335
- const LEGACY_BLOCK = ['# >>> pai setup >>>', '# <<< pai setup <<<'];
336
- /**
337
- * The shell startup file the key block goes in, by $SHELL, as Vercel's
338
- * `ai-gateway setup` picks it: `~/.zshrc` (or `$ZDOTDIR/.zshrc`),
339
- * `~/.bash_profile` on macOS and `~/.bashrc` elsewhere, fish's `config.fish`
340
- * (under `$XDG_CONFIG_HOME`), or `~/.profile` for any other shell. With no
341
- * $SHELL, zsh on macOS and bash elsewhere.
342
- * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
343
- */
344
- export function shellRcFile(env, home = env.HOME || os.homedir()) {
345
- const shell = path.basename(env.SHELL || (process.platform === 'darwin' ? 'zsh' : 'bash'));
346
- if (shell === 'zsh')
347
- return path.join(env.ZDOTDIR || home, '.zshrc');
348
- // Terminal windows on macOS start bash as a login shell, which reads ~/.bash_profile.
349
- if (shell === 'bash')
350
- return path.join(home, process.platform === 'darwin' ? '.bash_profile' : '.bashrc');
351
- if (shell === 'fish')
352
- return path.join(configHome(env, home), 'fish', 'config.fish');
353
- return path.join(home, '.profile');
354
- }
355
- /**
356
- * The block phantom adds to a shell startup file. When the shell starts it sets
357
- * PHANTOM_API_KEY, unless it is set already: on macOS straight from the
358
- * Keychain item the login key points to, and otherwise (or with
359
- * PHANTOM_KEY_NAME set) by running `phantom key show`. The key itself is never
360
- * written here. Each agent's own variables follow, set only when there is a key.
361
- * @param fish Fish syntax instead of sh, bash and zsh.
362
- * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
363
- */
364
- export function shellBlock(env, fish, state, onPathFn = onPath) {
365
- const home = env.HOME || os.homedir();
366
- const login = keyPath(env);
367
- const pointer = login.startsWith(home + path.sep) ? `$HOME/${path.relative(home, login)}` : login;
368
- const show = `${phantomCommand(onPathFn)} key show 2>/dev/null`;
369
- const fromKeychain = `/usr/bin/security find-generic-password -s ${KEYCHAIN_SERVICE} -a "$__phantom_id" -w 2>/dev/null | /usr/bin/base64 -D 2>/dev/null`;
370
- const pointerId = `sed -n 's/^${KEYCHAIN_POINTER}//p' "${pointer}" 2>/dev/null`;
371
- const keychain = keychainOn(env);
372
- const own = state.agents.flatMap((a) => state.lines.get(a) ?? []);
373
- const head = [
374
- BLOCK_BEGIN,
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.',
377
- `# agents: ${state.agents.join(' ')}`,
378
- '# Undo: phantom setup --restore',
379
- ];
380
- if (fish) {
381
- return [
382
- ...head,
383
- 'if test -z "$PHANTOM_API_KEY"',
384
- ...(keychain
385
- ? [
386
- ' set -l __phantom_id',
387
- ` test -z "$PHANTOM_KEY_NAME"; and set __phantom_id (${pointerId})`,
388
- ' if test -n "$__phantom_id"',
389
- ` set -gx PHANTOM_API_KEY (${fromKeychain})`,
390
- ' else',
391
- ` set -gx PHANTOM_API_KEY (${show})`,
392
- ' end',
393
- ]
394
- : [` set -gx PHANTOM_API_KEY (${show})`]),
395
- 'end',
396
- 'if test -n "$PHANTOM_API_KEY"',
397
- ...own,
398
- 'else',
399
- ' set -e PHANTOM_API_KEY',
400
- 'end',
401
- BLOCK_END,
402
- ].join('\n');
403
- }
404
- return [
405
- ...head,
406
- 'if [ -z "${PHANTOM_API_KEY:-}" ]; then',
407
- ...(keychain
408
- ? [
409
- ' __phantom_id=""',
410
- ` if [ -z "\${PHANTOM_KEY_NAME:-}" ]; then __phantom_id=$(${pointerId}); fi`,
411
- ' if [ -n "$__phantom_id" ]; then',
412
- ` PHANTOM_API_KEY=$(${fromKeychain})`,
413
- ' else',
414
- ` PHANTOM_API_KEY=$(${show})`,
415
- ' fi',
416
- ' unset __phantom_id',
417
- ]
418
- : [` PHANTOM_API_KEY=$(${show})`]),
419
- 'fi',
420
- 'if [ -n "${PHANTOM_API_KEY:-}" ]; then',
421
- ' export PHANTOM_API_KEY',
422
- ...own,
423
- 'else',
424
- ' unset PHANTOM_API_KEY',
425
- 'fi',
426
- BLOCK_END,
427
- ].join('\n');
428
- }
429
- /** One agent's variables as block lines, each ending with `# for <agent>`. */
430
- function shellLines(fish, agent, vars) {
431
- return Object.entries(vars).map(([k, v]) => (fish ? ` set -gx ${k} ${JSON.stringify(v)} # for ${agent}` : ` export ${k}=${JSON.stringify(v)} # for ${agent}`));
432
- }
433
- /** Where the phantom block sits in a startup file, and what it holds. null when there is none. */
434
- function findBlock(file, lines) {
435
- const marks = [[BLOCK_BEGIN, BLOCK_END], LEGACY_BLOCK].find(([b, e]) => lines.includes(b) || lines.includes(e));
436
- if (!marks)
437
- return null;
438
- const [begin, finish] = marks;
439
- const start = lines.indexOf(begin);
440
- const end = lines.indexOf(finish);
441
- if (start === -1 || end < start || lines.indexOf(begin, start + 1) !== -1)
442
- unreadable(file, 'has a phantom setup block without its matching end line');
443
- const inside = lines.slice(start, end);
444
- const agents = (inside.find((l) => l.startsWith('# agents:')) ?? '').slice('# agents:'.length).trim().split(/\s+/).filter(Boolean);
445
- const own = new Map();
446
- for (const l of inside) {
447
- const m = /# for ([a-z]+)$/.exec(l);
448
- if (m)
449
- own.set(m[1], [...(own.get(m[1]) ?? []), l]);
450
- }
451
- return { start, end, state: { agents, lines: own } };
452
- }
453
- /**
454
- * The startup file's text with the whole phantom block taken out, whichever
455
- * agents it lists. Text outside the block stays as it was. Unchanged when
456
- * there is no block.
457
- * @throws {@link CliError} `setup_unreadable` when the block has no matching end line.
458
- */
459
- export function withoutShellBlock(env, file, text) {
460
- const found = findBlock(file, text.split('\n'));
461
- if (!found)
462
- return text;
463
- return withShellBlock(env, file, text, new Map(), found.state.agents) ?? '';
464
- }
465
- /**
466
- * The startup file's text with the phantom block updated: agents in `on` added
467
- * with fresh lines, agents in `off` dropped. The block goes away when no agent
468
- * is left. Text outside the block stays as it was.
469
- */
470
- export function withShellBlock(env, file, text, on, off, onPathFn) {
471
- const fish = file.endsWith('.fish');
472
- const lines = text === null ? [] : text.split('\n');
473
- const found = findBlock(file, lines);
474
- const state = found ? found.state : { agents: [], lines: new Map() };
475
- for (const a of off) {
476
- state.agents = state.agents.filter((x) => x !== a);
477
- state.lines.delete(a);
478
- }
479
- for (const [a, vars] of on) {
480
- if (!state.agents.includes(a))
481
- state.agents.push(a);
482
- state.lines.set(a, shellLines(fish, a, vars));
483
- }
484
- const block = state.agents.length ? shellBlock(env, fish, state, onPathFn).split('\n') : [];
485
- if (found) {
486
- let from = found.start;
487
- if (!block.length && from > 0 && lines[from - 1] === '')
488
- from--;
489
- lines.splice(from, found.end + 1 - from, ...block);
490
- }
491
- else if (block.length) {
492
- while (lines.length && lines[lines.length - 1] === '')
493
- lines.pop();
494
- if (lines.length)
495
- lines.push('');
496
- lines.push(...block, '');
497
- }
498
- const result = lines.join('\n');
499
- return text === null && result === '' ? null : result;
500
- }
@@ -1,13 +0,0 @@
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;
@@ -1,36 +0,0 @@
1
- import os from 'node:os';
2
- import path from 'node:path';
3
- import { readText } from "./shared.mjs";
4
- import { jsonObject, shellRcFile } from "./editors.mjs";
5
- import { claudeDir } from "./agents.mjs";
6
- /**
7
- * What phantom prints, once per run in a terminal, while an agent setup that
8
- * pai (this CLI's old name) wrote still runs `pai`. Once pai is gone, that
9
- * setup can't get a key until `phantom setup` rewrites it.
10
- */
11
- export const LEGACY_SETUP_HINT = 'Your agent setup still runs pai, the old name of this CLI. Run phantom setup to switch it to phantom.';
12
- /**
13
- * True when an agent setup still runs `pai`: Claude Code's `apiKeyHelper`
14
- * calls it, or the shell startup file holds the block pai setup wrote.
15
- * `phantom setup` finds and rewrites both.
16
- */
17
- export function legacySetupFound(env) {
18
- const home = env.HOME || os.homedir();
19
- const file = path.join(claudeDir(env, home), 'settings.json');
20
- try {
21
- // JSONC, as setup reads it: Claude Code allows comments and trailing commas.
22
- const helper = jsonObject(file, readText(file)).apiKeyHelper;
23
- if (typeof helper === 'string' && /\bpai\b.* key show$/.test(helper))
24
- return true;
25
- }
26
- catch {
27
- // Not valid JSON: phantom setup reports that file itself.
28
- }
29
- try {
30
- return readText(shellRcFile(env, home))?.split('\n').includes('# >>> pai setup >>>') ?? false;
31
- }
32
- catch {
33
- // Unreadable (a folder, or no permission): the hint is optional, so skip it.
34
- return false;
35
- }
36
- }
@@ -1,104 +0,0 @@
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;