@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,9 +1,6 @@
1
1
  import { PhantomApiError, die } from "./errors.mjs";
2
- /** The Phantom AI API address phantom calls when PHANTOM_BASE_URL is unset. */
3
2
  export const DEFAULT_BASE_URL = 'https://phantom.codes/v1';
4
- /** How long {@link request} waits for the whole answer, in milliseconds, before it gives up. */
5
3
  export const REQUEST_TIMEOUT_MS = 30_000;
6
- /** Reads an answer's body as text and parses it only when it is JSON. A web page or an empty body never throws. */
7
4
  export async function readAnswer(res) {
8
5
  const text = await res.text();
9
6
  if (text.trim() === '')
@@ -15,10 +12,6 @@ export async function readAnswer(res) {
15
12
  return { json: {}, kind: 'text' };
16
13
  }
17
14
  }
18
- /**
19
- * The error for a failed answer. A JSON body goes through {@link apiError}. A web page or an empty body, such as a
20
- * 502 from a proxy in front of Phantom AI, gets a sentence a person can act on instead of `Unexpected token '<'`.
21
- */
22
15
  export function answerError(status, answer) {
23
16
  if (answer.kind === 'json')
24
17
  return apiError(status, answer.json);
@@ -28,12 +21,7 @@ export function answerError(status, answer) {
28
21
  const what = answer.kind === 'empty' ? 'an empty answer' : 'an error page instead of data';
29
22
  return new PhantomApiError(status, String(status), `Phantom AI sent ${what} (HTTP ${status}). Check PHANTOM_BASE_URL, and try again in a minute.`);
30
23
  }
31
- /** The error codes node gives when a connection never reached Phantom AI. */
32
24
  const UNREACHABLE = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_SOCKET']);
33
- /**
34
- * A sentence for node's `fetch failed`, which says nothing about why. Offline, a DNS failure and a refused
35
- * connection read as "check that you are online"; a certificate problem says so. Returns null for any other error.
36
- */
37
25
  export function explainNetworkError(err, host = 'Phantom AI') {
38
26
  if (!(err instanceof TypeError) || err.message !== 'fetch failed')
39
27
  return null;
@@ -46,14 +34,6 @@ export function explainNetworkError(err, host = 'Phantom AI') {
46
34
  return `phantom could not reach ${host}. Check that you are online, then try again.`;
47
35
  return `phantom could not reach ${host} (${cause.message}). Check that you are online, then try again.`;
48
36
  }
49
- /**
50
- * One HTTP call with the limits every call to Phantom AI shares. It gives up after `timeoutMs`, counting the
51
- * body as well as the headers, because a server can send headers and then stall. It reads the body as text,
52
- * and turns a failed connection into a sentence. It returns the answer whatever the status; the caller
53
- * decides what a status means.
54
- * @param label What the call is, for the timeout message, such as `GET /key/balance`.
55
- * @throws {@link CliError} `request_timeout` when no full answer arrives in time, `network_error` when the connection fails.
56
- */
57
37
  export async function fetchAnswer(url, init, label, timeoutMs = REQUEST_TIMEOUT_MS) {
58
38
  const signal = AbortSignal.timeout(Math.max(1, timeoutMs));
59
39
  try {
@@ -70,19 +50,6 @@ export async function fetchAnswer(url, init, label, timeoutMs = REQUEST_TIMEOUT_
70
50
  throw err;
71
51
  }
72
52
  }
73
- /**
74
- * Calls the Phantom AI API with the key as a Bearer token and returns the
75
- * JSON answer. Every client function in phantom goes through it.
76
- * @param method The HTTP method.
77
- * @param path The path after the base URL, such as `/key/balance`.
78
- * @param apiKey The key sent in the Authorization header.
79
- * @param body Sent as JSON when given.
80
- * @param baseUrl The API base. Defaults to PHANTOM_BASE_URL, then {@link DEFAULT_BASE_URL}. Must be https ({@link httpsOnly}).
81
- * @param headers Extra headers to send.
82
- * @param timeoutMs How long to wait for the answer. Defaults to {@link REQUEST_TIMEOUT_MS}.
83
- * @throws {@link PhantomApiError} when the API answers with an error status.
84
- * @throws {@link CliError} with code `request_timeout` when no answer arrives in time.
85
- */
86
53
  export async function request(method, path, apiKey, body, baseUrl, headers = {}, timeoutMs = REQUEST_TIMEOUT_MS) {
87
54
  const { res, answer } = await fetchAnswer(`${apiBase(baseUrl)}${path}`, {
88
55
  method,
@@ -102,10 +69,6 @@ export function apiBase(baseUrl) {
102
69
  (typeof process !== 'undefined' && process.env.PHANTOM_BASE_URL) ||
103
70
  DEFAULT_BASE_URL);
104
71
  }
105
- /**
106
- * The API base must be https. The key goes to it on every call, so plain http
107
- * is refused, localhost included.
108
- */
109
72
  export function httpsOnly(baseUrl) {
110
73
  let protocol = '';
111
74
  try {
@@ -119,15 +82,8 @@ export function httpsOnly(baseUrl) {
119
82
  }
120
83
  return baseUrl;
121
84
  }
122
- /**
123
- * Sentences for the bare code words some routes answer with (`{ "error": "invalid_key" }`), which say
124
- * nothing about what to do. The code stays on the error for scripts.
125
- */
126
85
  const CODE_SENTENCES = {
127
- invalid_key: 'Phantom AI does not accept this key. It may be mistyped, revoked or expired. Check the key, or run phantom login to sign in again.',
128
- access_denied: 'The sign-in was declined in the browser. Run phantom login to try again.',
129
- expired_token: 'The sign-in code expired. Run phantom login again.',
130
- invalid_grant: 'The sign-in code was not accepted. Run phantom login again.',
86
+ invalid_key: 'Phantom AI does not accept this key. It may be mistyped, revoked or expired. Check the key in PHANTOM_API_KEY.',
131
87
  };
132
88
  export function apiError(status, json) {
133
89
  json = json && typeof json === 'object' ? json : {};
@@ -140,15 +96,11 @@ export function apiError(status, json) {
140
96
  msg = typeof e.message === 'string' ? e.message : msg;
141
97
  }
142
98
  else if (typeof err === 'string') {
143
- // Some routes answer { error: <words> }; a detail, when one is sent, reads better.
144
99
  const detail = json.detail;
145
100
  msg = typeof detail === 'string' && detail ? detail : (CODE_SENTENCES[err] ?? err);
146
- // A code word such as `invalid_key` is the code. A sentence is the message only: its code is made from
147
- // the status, so the dim detail line under the message doesn't repeat it.
148
101
  code = /^[a-z][a-z0-9_]*$/.test(err) ? err : `http_${status}`;
149
102
  }
150
103
  else if (typeof json.detail === 'string') {
151
- // The purchase routes answer errors as { detail }, some with a { code }.
152
104
  msg = json.detail;
153
105
  const c = json.code;
154
106
  if (typeof c === 'string' && c)
@@ -156,14 +108,3 @@ export function apiError(status, json) {
156
108
  }
157
109
  return new PhantomApiError(status, code, msg);
158
110
  }
159
- /**
160
- * Credit left, credit spent and expiry of a key (GET /key/balance).
161
- * @throws {@link CliError} with code `balance_unreadable` when the answer has no numbers, such as a sign-in page that came back with status 200.
162
- */
163
- export async function getBalance(apiKey, baseUrl) {
164
- const balance = await request('GET', '/key/balance', apiKey, undefined, baseUrl);
165
- if (!balance || !Number.isFinite(balance.credit_balance_usd) || !Number.isFinite(balance.credit_spent_usd)) {
166
- die('The balance answer had no credit numbers. Check PHANTOM_BASE_URL, and that the address answers with the Phantom AI API.', 'balance_unreadable');
167
- }
168
- return balance;
169
- }
@@ -16,13 +16,9 @@ import { type Env } from './state.mts';
16
16
  */
17
17
  export declare const KEYCHAIN_SERVICE = "pai";
18
18
  export declare const KEYCHAIN_POINTER = "pai-keychain:";
19
- /** Reads and writes phantom's items in the macOS login Keychain through /usr/bin/security, under the service name `pai`, the CLI's old name. */
20
19
  export declare const keychain: {
21
- /** The secret saved under `id`, or null when there is none or the Keychain can't be read. */
22
20
  get(id: string): string | null;
23
- /** Saves `value` under `id`, replacing what was there. Returns false when the Keychain refuses, as it does when locked. */
24
21
  set(id: string, label: string, value: string): boolean;
25
- /** Removes the item saved under `id`, if any. */
26
22
  delete(id: string): void;
27
23
  };
28
24
  export declare function keychainOn(env: Env): boolean;
@@ -19,31 +19,22 @@ import { makePrivateFolder, stateDir } from "./state.mjs";
19
19
  * it is read, and replaced with a pointer only after the Keychain returns it
20
20
  * intact.
21
21
  */
22
- // The Keychain service and pointer keep pai, the CLI's old name, so keys saved
23
- // before the rename still read.
24
22
  export const KEYCHAIN_SERVICE = 'pai';
25
23
  export const KEYCHAIN_POINTER = 'pai-keychain:';
26
- /** Reads and writes phantom's items in the macOS login Keychain through /usr/bin/security, under the service name `pai`, the CLI's old name. */
27
24
  export const keychain = {
28
- /** The secret saved under `id`, or null when there is none or the Keychain can't be read. */
29
25
  get(id) {
30
26
  const r = spawnSync('/usr/bin/security', ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', id, '-w'], { encoding: 'utf-8' });
31
27
  return r.status === 0 ? Buffer.from(r.stdout.trim(), 'base64').toString('utf-8') : null;
32
28
  },
33
- /** Saves `value` under `id`, replacing what was there. Returns false when the Keychain refuses, as it does when locked. */
34
29
  set(id, label, value) {
35
- // Sent on stdin rather than as an argument, so the secret never shows in
36
- // the process list. Base64 keeps it one unquoted word.
37
30
  const cmd = `add-generic-password -U -s ${KEYCHAIN_SERVICE} -a ${id} -l "phantom ${label}" -w ${Buffer.from(value, 'utf-8').toString('base64')}\n`;
38
31
  return spawnSync('/usr/bin/security', ['-i'], { input: cmd, stdio: ['pipe', 'ignore', 'ignore'] }).status === 0;
39
32
  },
40
- /** Removes the item saved under `id`, if any. */
41
33
  delete(id) {
42
34
  spawnSync('/usr/bin/security', ['delete-generic-password', '-s', KEYCHAIN_SERVICE, '-a', id], { stdio: 'ignore' });
43
35
  },
44
36
  };
45
37
  export function keychainOn(env) {
46
- // PAI_KEYCHAIN is the old name, from when this CLI was pai.
47
38
  const flag = env.PHANTOM_KEYCHAIN ?? env.PAI_KEYCHAIN ?? process.env.PHANTOM_KEYCHAIN ?? process.env.PAI_KEYCHAIN;
48
39
  return flag === '1' || (process.platform === 'darwin' && flag !== '0');
49
40
  }
@@ -54,7 +45,6 @@ function keychainId(file) {
54
45
  return raw.startsWith(KEYCHAIN_POINTER) ? raw.slice(KEYCHAIN_POINTER.length) : null;
55
46
  }
56
47
  export function writeSecret(env, file, value, opts = {}) {
57
- // A folder an older install made at 755 is tightened too, not only a new one.
58
48
  makePrivateFolder(env, path.dirname(file));
59
49
  let contents = value;
60
50
  if (keychainOn(env)) {
@@ -1,6 +1,7 @@
1
- /** Environment variables, as `process.env` holds them. */
2
1
  export type Env = Record<string, string | undefined>;
2
+ export type MoveStep = 'prepare-link' | 'rename' | 'link';
3
3
  export declare function stateDir(env: Env): string;
4
+ export declare function moveOldStateFolder(env: Env, config?: string, beforeStep?: (step: MoveStep) => void): string | null;
4
5
  /**
5
6
  * Makes `folder` exist and be private to this user (mode 700), and the same for each folder between
6
7
  * the state folder and it, such as `keys/`. Folders made before 1.4.2 were mode 755, and `mkdir`'s
@@ -10,3 +11,4 @@ export declare function stateDir(env: Env): string;
10
11
  * `folder` outside the state folder is left as it is.
11
12
  */
12
13
  export declare function makePrivateFolder(env: Env, folder: string): void;
14
+ export declare function writePrivate(env: Env, file: string, text: string): void;
@@ -1,10 +1,147 @@
1
+ // docs: The CLI's state folder (~/.config/phantom, or PHANTOM_STATE_DIR): which folder holds phantom's settings right now (`stateDir`), moving an older phantom's ~/.config/phantom-key there when that is plainly safe (`moveOldStateFolder`), and writing private files in it (mode 600 in mode 700 folders)
1
2
  import path from 'node:path';
2
3
  import os from 'node:os';
3
- import { chmodSync, mkdirSync } from 'node:fs';
4
- // Kept at the name the CLI was first published under, so saved keys and
5
- // wallets survive the rename.
4
+ import { chmodSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
5
+ const STATE_NAME = 'phantom';
6
+ const OLD_STATE_NAME = 'phantom-key';
7
+ const PHANTOM_ENTRIES = new Set(['local.json', 'chatgpt', 'local', 'key', 'keys', 'model', 'wallets', 'workspace', 'setup-json-was.json', 'setup-backups.json']);
8
+ const isPhantoms = (name) => PHANTOM_ENTRIES.has(name) || /^pending-[0-9a-f]+\.json$/.test(name);
9
+ const LINK_IN_WAITING = '.phantom-key-link';
10
+ const NOTICE_FILE = 'state-folder-notice';
6
11
  export function stateDir(env) {
7
- return env.PHANTOM_STATE_DIR || path.join(os.homedir(), '.config', 'phantom-key');
12
+ return env.PHANTOM_STATE_DIR || stateFolderIn(path.join(os.homedir(), '.config'));
13
+ }
14
+ function stateFolderIn(config) {
15
+ try {
16
+ return planFor(config).use;
17
+ }
18
+ catch {
19
+ return path.join(config, STATE_NAME);
20
+ }
21
+ }
22
+ export function moveOldStateFolder(env, config = path.join(os.homedir(), '.config'), beforeStep = () => { }) {
23
+ if (env.PHANTOM_STATE_DIR)
24
+ return null;
25
+ let failure;
26
+ for (let look = 0; look < 5; look++) {
27
+ try {
28
+ const plan = planFor(config);
29
+ if (plan.step === 'none')
30
+ return plan.notice ? sayOnce(plan.use, plan.notice) : null;
31
+ takeStep(plan, config, beforeStep);
32
+ }
33
+ catch (err) {
34
+ failure = err;
35
+ }
36
+ }
37
+ const { old, current } = foldersIn(config);
38
+ const use = stateFolderIn(config);
39
+ const why = failure.code ?? failure.message;
40
+ return sayOnce(use, `phantom: could not move ${old} to ${current} (${why}), so phantom keeps its settings in ${use} for now.`);
41
+ }
42
+ function foldersIn(config) {
43
+ return { old: path.join(config, OLD_STATE_NAME), current: path.join(config, STATE_NAME), waiting: path.join(config, LINK_IN_WAITING) };
44
+ }
45
+ function kindAt(p) {
46
+ try {
47
+ const found = lstatSync(p);
48
+ return found.isSymbolicLink() ? 'link' : found.isDirectory() ? 'folder' : 'file';
49
+ }
50
+ catch (err) {
51
+ const code = err.code;
52
+ if (code === 'ENOENT' || code === 'ENOTDIR')
53
+ return 'missing';
54
+ throw err;
55
+ }
56
+ }
57
+ function leadsToFolder(p) {
58
+ try {
59
+ return statSync(p).isDirectory();
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ function namesIn(folder) {
66
+ try {
67
+ return readdirSync(folder);
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ function someOf(names) {
74
+ return names.length > 3 ? `${names.slice(0, 3).join(', ')} and ${names.length - 3} more` : names.join(', ');
75
+ }
76
+ function planFor(config) {
77
+ const { old, current, waiting } = foldersIn(config);
78
+ const keepOld = (why, fix) => ({ step: 'none', use: old, notice: `phantom: ${why}, so phantom keeps its settings in ${old} and moves nothing. ${fix}` });
79
+ const oldKind = kindAt(old);
80
+ const newKind = kindAt(current);
81
+ if (oldKind === 'link') {
82
+ const target = readlinkSync(old);
83
+ if (path.resolve(config, target) === current) {
84
+ return { step: kindAt(waiting) === 'link' ? 'link' : 'none', use: current };
85
+ }
86
+ return keepOld(`${old} is a link to ${target}`, `To use ${current} instead, remove just the link with \`rm ${old}\` (no -r and no slash at the end: those delete what it points to), then \`ln -s ${target} ${current}\`.`);
87
+ }
88
+ if (oldKind !== 'folder') {
89
+ if (oldKind === 'missing' && kindAt(waiting) === 'link')
90
+ return { step: 'link', use: current };
91
+ if (newKind === 'missing' || leadsToFolder(current))
92
+ return { step: 'none', use: current };
93
+ return keepOld(`${current} is not a folder`, 'Move or rename it, and phantom will use that name.');
94
+ }
95
+ if (newKind === 'missing')
96
+ return { step: 'move', use: old };
97
+ if (newKind === 'link') {
98
+ return keepOld(`${current} is a link to ${readlinkSync(current)}`, `To move them, remove just that link with \`rm ${current}\` (no -r and no slash at the end: those delete what it points to), and run phantom again.`);
99
+ }
100
+ const inNew = namesIn(current);
101
+ if (inNew === null)
102
+ return keepOld(`${current} is not a folder phantom can read`, 'Move or rename it, then run phantom again.');
103
+ if (inNew.some(isPhantoms)) {
104
+ const oldToo = (namesIn(old) ?? []).some(isPhantoms);
105
+ const notice = `phantom: ${old} is no longer read. phantom keeps its settings in ${current}. Copy anything you still need from the old folder, then delete it.`;
106
+ return oldToo ? { step: 'none', use: current, notice } : { step: 'none', use: current };
107
+ }
108
+ if (inNew.length === 0)
109
+ return { step: 'move', use: old };
110
+ return keepOld(`${current} holds files that are not phantom's (${someOf(inNew)})`, `Those files belong to another tool: move them somewhere that tool can find them, remove the empty folder with \`rmdir ${current}\`, and run phantom again.`);
111
+ }
112
+ function takeStep(plan, config, beforeStep) {
113
+ const { old, current, waiting } = foldersIn(config);
114
+ if (plan.step === 'move') {
115
+ beforeStep('prepare-link');
116
+ try {
117
+ symlinkSync(STATE_NAME, waiting);
118
+ }
119
+ catch (err) {
120
+ if (err.code !== 'EEXIST')
121
+ throw err;
122
+ }
123
+ beforeStep('rename');
124
+ // Takes the place of an empty ~/.config/phantom, and fails if anything was written into it since phantom looked.
125
+ renameSync(old, current);
126
+ }
127
+ chmodSync(current, 0o700);
128
+ beforeStep('link');
129
+ renameSync(waiting, old);
130
+ }
131
+ function sayOnce(folder, notice) {
132
+ const record = path.join(folder, NOTICE_FILE);
133
+ try {
134
+ if (readFileSync(record, 'utf8') === notice)
135
+ return null;
136
+ }
137
+ catch {
138
+ }
139
+ try {
140
+ writeFileSync(record, notice, { mode: 0o600 });
141
+ }
142
+ catch {
143
+ }
144
+ return notice;
8
145
  }
9
146
  /**
10
147
  * Makes `folder` exist and be private to this user (mode 700), and the same for each folder between
@@ -27,3 +164,9 @@ export function makePrivateFolder(env, folder) {
27
164
  chmodSync(current, 0o700);
28
165
  }
29
166
  }
167
+ export function writePrivate(env, file, text) {
168
+ makePrivateFolder(env, path.dirname(file));
169
+ const temp = `${file}.${process.pid}.tmp`;
170
+ writeFileSync(temp, text, { mode: 0o600 });
171
+ renameSync(temp, file);
172
+ }
@@ -5,45 +5,18 @@ import type { Env } from './state.mts';
5
5
  * anywhere, and `FORCE_COLOR=0` turns it off.
6
6
  */
7
7
  export declare function colorOn(env: Env, isTTY: boolean | undefined): boolean;
8
- /** The styles a screen uses. Each wraps text in its color, or returns it as is when color is off. */
9
8
  export type Paint = {
10
- /** Phantom's lime (#3ee6a8, `--lime` on the site), for marks such as ◆ and ✓. */
11
9
  lime: (s: string) => string;
12
10
  bold: (s: string) => string;
13
- /** Bright white, for the ghost's body. */
14
11
  white: (s: string) => string;
15
- /** Night text on a lime block, like the site's lime tags (`Meet phantom-1`). */
16
12
  pill: (s: string) => string;
17
- /** Paths, counts and other detail the eye can skip. */
18
13
  dim: (s: string) => string;
19
- /** Phantom's cyan (#00d1ff, `--cyan` on the site), for actions and commands people can type. */
20
14
  cyan: (s: string) => string;
21
- /** Lines a file gains. */
22
15
  green: (s: string) => string;
23
- /** Lines a file loses, and agents setup skipped. */
24
16
  red: (s: string) => string;
25
- /** Warnings and steps to do by hand. */
26
17
  yellow: (s: string) => string;
27
18
  };
28
- /**
29
- * The styles for one screen. Lime and cyan use 24-bit color when the terminal says it
30
- * has it (`COLORTERM=truecolor`), and the nearest of the 256 standard colors otherwise.
31
- */
32
19
  export declare function paint(env: Env, on: boolean): Paint;
33
- /** `text` without color codes, to measure how wide it prints. */
34
20
  export declare const unstyled: (text: string) => string;
35
- /**
36
- * One line of a screen, fitted to a terminal `columns` wide: a longer line
37
- * breaks at spaces, and each piece after the first starts under the text it
38
- * continues. That is the second column for a table row or a help entry
39
- * (text after a run of two spaces), the words after a mark such as `✓ ` or
40
- * `→ `, or else the line's own indent. A word longer than the room, such as
41
- * a URL, stays whole. Color codes don't count toward the width.
42
- */
43
21
  export declare function fitLine(line: string, columns: number): string;
44
- /**
45
- * Text fitted to `columns` with {@link fitLine}, line by line. JSON (text
46
- * that starts with `{` or `[`) and anything drawn in place come back as they
47
- * are, since a break there would change what they mean.
48
- */
49
22
  export declare function fitText(text: string, columns: number): string;
@@ -12,10 +12,6 @@ export function colorOn(env, isTTY) {
12
12
  }
13
13
  const wrap = (open, close) => (s) => `\x1b[${open}m${s}\x1b[${close}m`;
14
14
  const plain = (s) => s;
15
- /**
16
- * The styles for one screen. Lime and cyan use 24-bit color when the terminal says it
17
- * has it (`COLORTERM=truecolor`), and the nearest of the 256 standard colors otherwise.
18
- */
19
15
  export function paint(env, on) {
20
16
  if (!on)
21
17
  return { lime: plain, bold: plain, white: plain, pill: plain, dim: plain, cyan: plain, green: plain, red: plain, yellow: plain };
@@ -32,16 +28,7 @@ export function paint(env, on) {
32
28
  yellow: wrap('33', '39'),
33
29
  };
34
30
  }
35
- /** `text` without color codes, to measure how wide it prints. */
36
31
  export const unstyled = (text) => text.replace(/\x1b\[[0-9;]*m/g, '');
37
- /**
38
- * One line of a screen, fitted to a terminal `columns` wide: a longer line
39
- * breaks at spaces, and each piece after the first starts under the text it
40
- * continues. That is the second column for a table row or a help entry
41
- * (text after a run of two spaces), the words after a mark such as `✓ ` or
42
- * `→ `, or else the line's own indent. A word longer than the room, such as
43
- * a URL, stays whole. Color codes don't count toward the width.
44
- */
45
32
  export function fitLine(line, columns) {
46
33
  const seen = unstyled(line);
47
34
  if (seen.length <= columns)
@@ -53,7 +40,6 @@ export function fitLine(line, columns) {
53
40
  const rows = [];
54
41
  let row = '';
55
42
  let width = 0;
56
- // A command stays on one line to copy: `phantom` keeps the word after it, and a flag the word before.
57
43
  const words = [];
58
44
  for (const word of line.split(' ')) {
59
45
  const last = words.length ? unstyled(words[words.length - 1]) : '';
@@ -81,13 +67,7 @@ export function fitLine(line, columns) {
81
67
  });
82
68
  return [...rows, row.trimEnd()].join('\n');
83
69
  }
84
- /** Moves the cursor or redraws: text drawn in place (a menu, a spinner), which must not be wrapped. */
85
70
  const DRAWN = /\r|\x1b\[[0-9;?]*[A-HJKSTfhlsu]/;
86
- /**
87
- * Text fitted to `columns` with {@link fitLine}, line by line. JSON (text
88
- * that starts with `{` or `[`) and anything drawn in place come back as they
89
- * are, since a break there would change what they mean.
90
- */
91
71
  export function fitText(text, columns) {
92
72
  if (!columns || DRAWN.test(text) || /^\s*[{[]/.test(text))
93
73
  return text;
@@ -1,2 +1 @@
1
- /** This release of phantom. `npm version` keeps it equal to the version in package.json. */
2
- export declare const VERSION = "1.6.3";
1
+ export declare const VERSION = "1.7.1";
@@ -1,2 +1 @@
1
- /** This release of phantom. `npm version` keeps it equal to the version in package.json. */
2
- export const VERSION = '1.6.3';
1
+ export const VERSION = '1.7.1';
@@ -0,0 +1,25 @@
1
+ type KindBase = {
2
+ label: string;
3
+ modelRule: (model: string) => string | null;
4
+ setupName: string;
5
+ notice?: string;
6
+ };
7
+ export type KeyKind = KindBase & {
8
+ chatUrl: string;
9
+ auth: (key: string) => Record<string, string>;
10
+ keyEnv: string;
11
+ };
12
+ type PlanKind = KindBase & {
13
+ responsesUrl: string;
14
+ };
15
+ export declare const ACCOUNT_KINDS: {
16
+ gateway: KeyKind;
17
+ 'zai-coding-plan': KeyKind;
18
+ 'chatgpt-plan': PlanKind;
19
+ };
20
+ export type AccountKindName = keyof typeof ACCOUNT_KINDS;
21
+ export type KeyKindName = Exclude<AccountKindName, 'chatgpt-plan'>;
22
+ export declare function modelProblem(kind: AccountKindName, model: string): string | null;
23
+ export declare const kindNamed: (name: string) => "gateway" | "zai-coding-plan" | "chatgpt-plan" | undefined;
24
+ export declare function isAccountKind(name: unknown): name is AccountKindName;
25
+ export {};
@@ -0,0 +1,40 @@
1
+ // docs: The kinds of account phantom-1 on this computer can send a request to, one entry each: where its endpoint is and how a request signs in (a key, read by keys.mts, or the ChatGPT sign-in), how it names a model, the name `phantom config` gives it, and what to say at startup. Adding a kind is one entry here
2
+ import { OPENAI } from "../chatgpt/session.mjs";
3
+ import { shown } from "./keys.mjs";
4
+ export const ACCOUNT_KINDS = {
5
+ /** Vercel AI Gateway: https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-chat-completions */
6
+ gateway: {
7
+ label: 'Vercel AI Gateway',
8
+ chatUrl: 'https://ai-gateway.vercel.sh/v1/chat/completions',
9
+ auth: (key) => ({ authorization: `Bearer ${key}` }),
10
+ modelRule: (model) => (/^[a-z0-9-]+\/\S+$/i.test(model) ? null : 'a Gateway model id names its maker, such as anthropic/claude-haiku-5.5'),
11
+ setupName: 'gateway',
12
+ keyEnv: 'AI_GATEWAY_API_KEY',
13
+ },
14
+ /** Z.ai's GLM Coding Plan: https://docs.z.ai/devpack/tool/others and https://docs.z.ai/api-reference/introduction */
15
+ 'zai-coding-plan': {
16
+ label: 'Z.ai GLM Coding Plan',
17
+ chatUrl: 'https://api.z.ai/api/coding/paas/v4/chat/completions',
18
+ auth: (key) => ({ authorization: `Bearer ${key}` }),
19
+ modelRule: (model) => (/^glm-[a-z0-9.-]+$/i.test(model) ? null : 'a Z.ai model id is a GLM model code, such as glm-5.4'),
20
+ setupName: 'zai',
21
+ keyEnv: 'ZAI_API_KEY',
22
+ notice: 'Z.ai limits the coding plan to supported tools, and this is not one. Your account, your risk.',
23
+ },
24
+ /** The ChatGPT plan: https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference */
25
+ 'chatgpt-plan': {
26
+ label: 'ChatGPT plan',
27
+ responsesUrl: OPENAI.responses,
28
+ modelRule: (model) => (/^[a-z0-9][a-z0-9._-]*$/i.test(model) ? null : 'a ChatGPT plan model is a slug with no maker, such as gpt-6.1-sol'),
29
+ setupName: 'chatgpt',
30
+ },
31
+ };
32
+ export function modelProblem(kind, model) {
33
+ if (shown(model) !== model)
34
+ return 'that looks like a key, not a model id';
35
+ return ACCOUNT_KINDS[kind].modelRule(model);
36
+ }
37
+ export const kindNamed = (name) => Object.keys(ACCOUNT_KINDS).find((kind) => ACCOUNT_KINDS[kind].setupName === name);
38
+ export function isAccountKind(name) {
39
+ return typeof name === 'string' && Object.hasOwn(ACCOUNT_KINDS, name);
40
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * True when a coding agent's helper sent the request: a side job such as
3
+ * Claude Code's Explore agent, not the person's main task. Follows
4
+ * Switchyard's `parse_sub_agent` and `claude_lineage`.
5
+ */
6
+ export declare function isHelperAgent(headers: Headers): boolean;
7
+ export declare function agentSession(headers: Headers): string | null;
@@ -0,0 +1,44 @@
1
+ // docs: A copy of web/lib/agent-headers.ts for phantom-1 on this computer: whether one of a coding agent's helper agents sent the request, and which session it belongs to. Keeps nothing. The CLI can't import from web/, so change both together
2
+ /**
3
+ * Codex's helper kinds that carry delegated work. Other kinds (`compact`,
4
+ * `memory_consolidation`) are upkeep and route as usual. The list matches
5
+ * `SUBAGENT_WORK_KINDS` in Switchyard's `crates/protocol/src/metadata.rs` at
6
+ * the pinned commit.
7
+ */
8
+ const CODEX_HELPER_KINDS = ['collab_spawn', 'thread_spawn', 'review'];
9
+ /**
10
+ * True when a coding agent's helper sent the request: a side job such as
11
+ * Claude Code's Explore agent, not the person's main task. Follows
12
+ * Switchyard's `parse_sub_agent` and `claude_lineage`.
13
+ */
14
+ export function isHelperAgent(headers) {
15
+ // Claude Code sends this only from helper agents, never from the main agent.
16
+ if (headers.get('x-claude-code-agent-id')?.trim())
17
+ return true;
18
+ // OpenCode names the session that started a subagent only on that subagent's requests. Seen from
19
+ // OpenCode 2.4.3's explore agent; OpenCode's docs don't describe its headers.
20
+ if (headers.get('x-opencode-parent-session-id')?.trim())
21
+ return true;
22
+ const codex = codexTurn(headers);
23
+ // Codex names the helper's kind in its turn metadata, or in x-openai-subagent.
24
+ const kind = text(codex.subagent_kind) ?? text(headers.get('x-openai-subagent'));
25
+ if (kind)
26
+ return CODEX_HELPER_KINDS.includes(kind);
27
+ const parent = text(codex.parent_thread_id) ?? text(headers.get('x-codex-parent-thread-id'));
28
+ return codex.thread_source === 'subagent' && parent !== null;
29
+ }
30
+ export function agentSession(headers) {
31
+ return text(headers.get('x-phantom-session')) ?? text(headers.get('x-claude-code-session-id')) ?? text(headers.get('x-opencode-session'));
32
+ }
33
+ function codexTurn(headers) {
34
+ try {
35
+ const value = JSON.parse(headers.get('x-codex-turn-metadata') ?? '');
36
+ return value && typeof value === 'object' ? value : {};
37
+ }
38
+ catch {
39
+ return {};
40
+ }
41
+ }
42
+ function text(value) {
43
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
44
+ }