@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
@@ -0,0 +1,211 @@
1
+ // docs: The commands of phantom-1 on this computer. `phantom config` for scripts: the tier flags (tiers.mts), `show` (what is set up, naming where each key comes from but never printing it, and whether ChatGPT is signed in), `models` (each account's models), `key` (keys.mts) and `chatgpt` (chatgpt/command.mts); at a terminal with nothing else, cli/app.mts opens the settings screen instead. `phantom report` sums up the saved requests and says whether traces are on. `phantom replay` runs the saved traces through the tier decision again (replay.mts). `startRouter` starts phantom-1 on 127.0.0.1 for `phantom pi`, saving one line per request unless local.json turns the log off, and flipping the trial's coin when local.json turns the trial on
2
+ import { existsSync } from 'node:fs';
3
+ import { currentSession, readSession } from "../chatgpt/session.mjs";
4
+ import { chatgptCommand } from "../chatgpt/command.mjs";
5
+ import { die } from "../core/errors.mjs";
6
+ import { out } from "../core/helpers.mjs";
7
+ import { ACCOUNT_KINDS } from "./accounts.mjs";
8
+ import { sessionProblem } from "./chatgpt-plan.mjs";
9
+ import { SENSITIVITIES, TIERS, accountsInUse, describeTier, localConfigPath, readLocalConfig } from "./config.mjs";
10
+ import { MAX_MOVE_UP_TOKENS, flipCoin, phantom1Picker } from "./decide.mjs";
11
+ import { replay, replayText } from "./replay.mjs";
12
+ import { keyRow, keyRowText, keysCommand, noKeyText, resolveKey } from "./keys.mjs";
13
+ import { imageReaderFor, imageReadersFor, listModels } from "./models.mjs";
14
+ import { SETTING_FLAGS, configFromFlags } from "./tiers.mjs";
15
+ import { parseSince, readRequests, reportText, summarize } from "./report.mjs";
16
+ import { requestLog, requestLogPaths } from "./request-log.mjs";
17
+ import { startLocalServer } from "./server.mjs";
18
+ import { traceLog, tracesFolder, tracesSize } from "./traces.mjs";
19
+ import { findRouter, routerLocation, rustRouterVersion } from "./rust-router.mjs";
20
+ const CONFIG_WORDS = ['show', 'models', 'key', 'chatgpt'];
21
+ export async function configCommand(input) {
22
+ const { subcommand, env, io } = input;
23
+ if (subcommand === 'show') {
24
+ out(statusOf(readLocalConfig(env), env), input.table, (s) => statusText(s), io.stdout);
25
+ return 0;
26
+ }
27
+ if (subcommand === 'models')
28
+ return modelsCommand(input);
29
+ if (subcommand === 'key')
30
+ return keysCommand(input);
31
+ if (subcommand === 'chatgpt')
32
+ return chatgptCommand(input);
33
+ if (subcommand)
34
+ die(`phantom config takes ${CONFIG_WORDS.join(', ')}, or the tier flags. See phantom config --help.`, 'config_usage');
35
+ if (SETTING_FLAGS.some((flag) => input.flags[flag] !== undefined))
36
+ return configFromFlags(input);
37
+ return die('phantom config opens its settings screen at a terminal. In a script, set tiers with --standard <account>:<model> (and --frontier, --standard-fallback, --frontier-fallback), or read what is set with phantom config show. See phantom config --help.', 'config_usage');
38
+ }
39
+ export async function reportCommand(input) {
40
+ const since = input.flags['since'];
41
+ if (since === true)
42
+ die('--since needs a value, such as 1d or 2026-11-28.', 'local_report_since');
43
+ const report = summarize(readRequests(input.env), since === undefined ? null : parseSince(since, new Date()));
44
+ const traces = { on: tracesOn(input.env), folder: tracesFolder(input.env), ...tracesSize(input.env) };
45
+ out({ ...report, traces }, input.table, () => `${reportText(report)}\n${tracesText(traces)}`, input.io.stdout);
46
+ return 0;
47
+ }
48
+ function tracesOn(env) {
49
+ if (!existsSync(localConfigPath(env)))
50
+ return false;
51
+ try {
52
+ return readLocalConfig(env).traces;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ export async function replayCommand(input) {
59
+ const { flags } = input;
60
+ if (flags['since'] === true)
61
+ die('--since needs a value, such as 1d or 2026-11-28.', 'local_report_since');
62
+ const sensitivity = flags['sensitivity'];
63
+ if (sensitivity !== undefined && !SENSITIVITIES.includes(sensitivity))
64
+ die('--sensitivity takes balanced, conservative or strict.', 'replay_usage');
65
+ const limit = flags['max-move-up-tokens'];
66
+ if (limit !== undefined && (typeof limit !== 'string' || !/^\d+$/.test(limit)))
67
+ die('--max-move-up-tokens takes a whole number of tokens, such as 60000.', 'replay_usage');
68
+ const warnings = new Set();
69
+ const report = await replay({
70
+ env: input.env,
71
+ since: typeof flags['since'] === 'string' ? parseSince(flags['since'], new Date()) : null,
72
+ sensitivity: sensitivity ?? null,
73
+ maxMoveUpTokens: limit === undefined ? MAX_MOVE_UP_TOKENS : Number(limit),
74
+ warn: (line) => warnings.add(line),
75
+ });
76
+ for (const line of warnings)
77
+ input.io.stderr(line + '\n');
78
+ out(report, input.table, () => replayText(report, input.env), input.io.stdout);
79
+ return 0;
80
+ }
81
+ function tracesText(t) {
82
+ const size = t.bytes < 1024 ? `${t.bytes} bytes` : t.bytes < 1024 ** 2 ? `${Math.round(t.bytes / 1024)} KB` : `${(t.bytes / 1024 ** 2).toFixed(1)} MB`;
83
+ const saved = t.files ? `${t.files} file${t.files === 1 ? '' : 's'}, ${size} in ${t.folder}` : 'none saved';
84
+ const on = t.on === null ? "unknown, since local.json can't be read (phantom config show says why)" : t.on ? 'on' : 'off';
85
+ return `Traces (full prompts and answers): ${on}; ${saved}.`;
86
+ }
87
+ function statusOf(config, env) {
88
+ const session = readSession(env);
89
+ return {
90
+ file: localConfigPath(env),
91
+ tiers: Object.fromEntries(TIERS.map((t) => [t, config.tiers[t]])),
92
+ keys: Object.entries(config.accounts).flatMap(([account, entry]) => (entry.kind === 'chatgpt-plan' ? [] : [keyRow(env, account, entry)])),
93
+ chatgpt: session.kind === 'signed-out' ? { signed_in: false } : { signed_in: true, email: session.account.email, plan_use: session.kind !== 'plan-off' },
94
+ router: routerLocation(findRouter(env)),
95
+ router_version: rustRouterVersion(findRouter(env)),
96
+ sensitivity: config.sensitivity,
97
+ traces: { on: config.traces, folder: tracesFolder(env) },
98
+ trial: config.trial,
99
+ };
100
+ }
101
+ function statusText(s) {
102
+ const chatgpt = s.chatgpt.signed_in ? `ChatGPT: signed in as ${s.chatgpt.email}, plan use ${s.chatgpt.plan_use ? 'on' : 'off'}` : 'ChatGPT: not signed in. Run phantom config chatgpt login.';
103
+ return [
104
+ `Settings: ${s.file}`,
105
+ ...TIERS.map((t) => `${t === 'standard' ? 'Standard' : 'Frontier'}: ${describeTier(s.tiers[t])}`),
106
+ ...s.keys.map((k) => `Key for ${keyRowText(k)}`),
107
+ chatgpt,
108
+ s.router
109
+ ? `Router: ${s.router}${s.router_version ? ` (build ${s.router_version})` : ''}`
110
+ : 'Router: not on this computer, so phantom-1 picks Frontier when no rule decides. Set PHANTOM_ROUTER_DIR to a built routers/phantom-1/router/ folder.',
111
+ `Sensitivity: ${s.sensitivity}`,
112
+ s.traces.on ? `Traces: on, saving full prompts and answers in ${s.traces.folder}` : 'Traces: off (no prompts or answers are saved)',
113
+ s.trial ? 'Trial: on, a coin keeps half the tasks the router moves up on Standard' : 'Trial: off',
114
+ ].join('\n');
115
+ }
116
+ async function modelsCommand(input) {
117
+ const config = readLocalConfig(input.env);
118
+ const names = Object.keys(config.accounts);
119
+ const only = input.argv[2] !== undefined && !input.argv[2].startsWith('--') ? input.argv[2] : undefined;
120
+ if (only !== undefined && !names.includes(only))
121
+ die(`No account "${only}" in local.json. It has ${names.join(', ')}.`, 'local_account_unknown');
122
+ const lists = await Promise.all((only ? [only] : names).map((name) => listModels(name, config.accounts[name], input.env)));
123
+ const accounts = lists.map((list) => ('models' in list ? { ...list, models: list.models.filter((m) => !m.hidden) } : list));
124
+ out({ accounts }, input.table, () => accounts.map(modelsText).join('\n\n'), input.io.stdout);
125
+ return 0;
126
+ }
127
+ function modelsText(list) {
128
+ const head = `${list.account} (${ACCOUNT_KINDS[list.kind].label})`;
129
+ if ('error' in list)
130
+ return `${head}: ${list.error}`;
131
+ const width = Math.max(0, ...list.models.map((m) => m.id.length)) + 2;
132
+ const from = list.source === 'docs' ? ", from its maker's docs; other ids may work" : '';
133
+ return [`${head}: ${list.models.length} models${from}`, ...list.models.map((m) => ` ${m.id.padEnd(width)}${m.name ?? ''}`.trimEnd())].join('\n');
134
+ }
135
+ export async function startRouter(opts) {
136
+ const { env, port, notify, warn } = opts;
137
+ const config = readLocalConfig(env);
138
+ const inUse = accountsInUse(config);
139
+ const keys = {};
140
+ const missing = [];
141
+ for (const name of inUse) {
142
+ const entry = config.accounts[name];
143
+ if (entry.kind === 'chatgpt-plan')
144
+ continue;
145
+ const lookup = resolveKey(env, name, entry);
146
+ if (lookup.found)
147
+ keys[name] = lookup.key;
148
+ else
149
+ missing.push(noKeyText(name, entry, lookup.missing));
150
+ }
151
+ if (missing.length)
152
+ die(missing.join('.\n') + '.', 'local_key_missing');
153
+ for (const notice of new Set(inUse.map((a) => ACCOUNT_KINDS[config.accounts[a].kind].notice))) {
154
+ if (notice)
155
+ notify(notice);
156
+ }
157
+ const session = readSession(env);
158
+ const usable = session.kind === 'signed-in' || session.kind === 'expired';
159
+ if (inUse.some((a) => config.accounts[a].kind === 'chatgpt-plan') && !usable) {
160
+ notify(`${sessionProblem(session)} Until then, a tier on the ChatGPT plan uses its fallback, or answers 503.`);
161
+ }
162
+ const saveProblems = new Set();
163
+ const warnSave = (line) => {
164
+ warn(line);
165
+ saveProblems.add(line);
166
+ };
167
+ const takeSaveProblems = () => {
168
+ const lines = [...saveProblems];
169
+ saveProblems.clear();
170
+ return lines;
171
+ };
172
+ const readImages = imageReaderFor(config.accounts, env);
173
+ const requests = config.log ? requestLog({ env, warn: warnSave }) : null;
174
+ const traces = config.traces ? traceLog({ env, warn: warnSave }) : null;
175
+ const record = (r) => {
176
+ requests?.write(r);
177
+ opts.onRequest?.(r);
178
+ };
179
+ let server;
180
+ try {
181
+ server = await startLocalServer({
182
+ config,
183
+ keys,
184
+ port,
185
+ token: opts.token,
186
+ picker: phantom1Picker({ env, warn, sensitivity: config.sensitivity, imageReaders: imageReadersFor(config, env, readImages), ...(config.trial && { coin: flipCoin }) }),
187
+ targetReadsImages: readImages,
188
+ rustRouterVersion: rustRouterVersion(findRouter(env)),
189
+ log: opts.log,
190
+ warn,
191
+ takeSaveProblems,
192
+ record,
193
+ trace: traces?.write,
194
+ chatgpt: () => currentSession(env),
195
+ });
196
+ }
197
+ catch (err) {
198
+ die(`phantom-1 could not listen on 127.0.0.1:${port} (${err.code ?? 'error'}).`);
199
+ }
200
+ return {
201
+ url: server.url,
202
+ config,
203
+ logFile: requests ? requestLogPaths(env).current : null,
204
+ tracesFolder: traces ? tracesFolder(env) : null,
205
+ close: async () => {
206
+ await server.close();
207
+ await requests?.idle();
208
+ await traces?.idle();
209
+ },
210
+ };
211
+ }
@@ -0,0 +1,49 @@
1
+ import { type Env } from '../core/state.mts';
2
+ import { type KeyKindName } from './accounts.mts';
3
+ export type Tier = 'standard' | 'frontier';
4
+ export declare const TIERS: readonly Tier[];
5
+ export declare const TIER_NAME: Record<Tier, string>;
6
+ export type Sensitivity = 'balanced' | 'conservative' | 'strict';
7
+ export declare const SENSITIVITIES: readonly Sensitivity[];
8
+ export type KeySource = {
9
+ from: 'saved';
10
+ } | {
11
+ from: 'env';
12
+ name: string;
13
+ } | {
14
+ from: 'keychain';
15
+ service: string;
16
+ account?: string;
17
+ };
18
+ export type KeyAccount = {
19
+ kind: KeyKindName;
20
+ key: KeySource | null;
21
+ };
22
+ export type Account = KeyAccount | {
23
+ kind: 'chatgpt-plan';
24
+ };
25
+ export type Target = {
26
+ account: string;
27
+ model: string;
28
+ };
29
+ type TierEntry = Target & {
30
+ fallback?: Target;
31
+ };
32
+ export type LocalConfig = {
33
+ log: boolean;
34
+ sensitivity: Sensitivity;
35
+ traces: boolean;
36
+ trial: boolean;
37
+ accounts: Record<string, Account>;
38
+ tiers: Record<Tier, TierEntry>;
39
+ };
40
+ export declare function localConfigPath(env: Env): string;
41
+ export declare const STARTER: LocalConfig;
42
+ export declare function writeLocalConfig(env: Env, config: LocalConfig): string;
43
+ export declare function readLocalConfig(env: Env): LocalConfig;
44
+ export declare function savedOrStarter(env: Env): LocalConfig;
45
+ export declare const isAccountName: (name: string) => boolean;
46
+ export declare function parseLocalConfig(text: string): LocalConfig;
47
+ export declare function describeTier(entry: TierEntry): string;
48
+ export declare function accountsInUse(config: LocalConfig): string[];
49
+ export {};
@@ -0,0 +1,168 @@
1
+ // docs: The settings file of phantom-1 on this computer, local.json in the CLI's state folder: the accounts (a kind and where its key comes from: phantom's saved key, an environment variable or a macOS Keychain item, never the key; a ChatGPT plan account has none), the account and model for each tier, whether to save the request log and the traces (full prompts and answers, off unless turned on), and the router's sensitivity, and whether the trial is on (a coin that keeps half the tasks the router moves up on Standard; decide.mts). Reads it into a checked shape (passing over top-level fields a newer phantom added), and writes it (a starter, or what `phantom config` set) with no keys, keeping those newer fields
2
+ import path from 'node:path';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { die } from "../core/errors.mjs";
5
+ import { stateDir, writePrivate } from "../core/state.mjs";
6
+ import { ACCOUNT_KINDS, isAccountKind, modelProblem } from "./accounts.mjs";
7
+ import { shown } from "./keys.mjs";
8
+ export const TIERS = ['standard', 'frontier'];
9
+ export const TIER_NAME = { standard: 'Standard', frontier: 'Frontier' };
10
+ export const SENSITIVITIES = ['balanced', 'conservative', 'strict'];
11
+ export function localConfigPath(env) {
12
+ return path.join(stateDir(env), 'local.json');
13
+ }
14
+ export const STARTER = {
15
+ log: true,
16
+ sensitivity: 'balanced',
17
+ traces: false,
18
+ trial: false,
19
+ accounts: { gateway: { kind: 'gateway', key: { from: 'env', name: 'AI_GATEWAY_API_KEY' } } },
20
+ tiers: {
21
+ standard: { account: 'gateway', model: 'deepseek/deepseek-v4.1-flash-1017' },
22
+ frontier: { account: 'gateway', model: 'anthropic/claude-sonnet-5.5' },
23
+ },
24
+ };
25
+ const TOP_LEVEL_FIELDS = ['mode', 'log', 'sensitivity', 'traces', 'trial', 'accounts', 'tiers'];
26
+ export function writeLocalConfig(env, config) {
27
+ const file = localConfigPath(env);
28
+ const text = JSON.stringify({ ...config, ...newerFields(file) }, null, 2) + '\n';
29
+ parseLocalConfig(text);
30
+ writePrivate(env, file, text);
31
+ return file;
32
+ }
33
+ function newerFields(file) {
34
+ let saved;
35
+ try {
36
+ saved = JSON.parse(readFileSync(file, 'utf8'));
37
+ }
38
+ catch {
39
+ return {};
40
+ }
41
+ if (!saved || typeof saved !== 'object' || Array.isArray(saved))
42
+ return {};
43
+ return Object.fromEntries(Object.entries(saved).filter(([field]) => !TOP_LEVEL_FIELDS.includes(field)));
44
+ }
45
+ export function readLocalConfig(env) {
46
+ const file = localConfigPath(env);
47
+ if (!existsSync(file))
48
+ die(`No ${file} yet. Run phantom config to choose your accounts and tiers.`, 'local_config_missing');
49
+ return parseLocalConfig(readFileSync(file, 'utf8'));
50
+ }
51
+ export function savedOrStarter(env) {
52
+ return existsSync(localConfigPath(env)) ? readLocalConfig(env) : STARTER;
53
+ }
54
+ const isEnvName = (name) => /^[A-Z_][A-Z0-9_]{0,63}$/.test(name);
55
+ const ENV_NAME_RULE = 'the name of an environment variable, such as ZAI_API_KEY, never the key itself';
56
+ export const isAccountName = (name) => /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name);
57
+ export function parseLocalConfig(text) {
58
+ let raw;
59
+ try {
60
+ raw = JSON.parse(text);
61
+ }
62
+ catch {
63
+ bad('it is not valid JSON');
64
+ }
65
+ const top = record(raw, 'the file');
66
+ const log = top.log ?? true;
67
+ if (typeof log !== 'boolean')
68
+ bad('log must be true or false');
69
+ const sensitivity = top.sensitivity ?? 'balanced';
70
+ if (!SENSITIVITIES.includes(sensitivity))
71
+ bad('sensitivity must be balanced, conservative or strict');
72
+ const traces = top.traces ?? false;
73
+ if (typeof traces !== 'boolean')
74
+ bad('traces must be true or false');
75
+ const trial = top.trial ?? false;
76
+ if (typeof trial !== 'boolean')
77
+ bad('trial must be true or false');
78
+ const accounts = {};
79
+ for (const [name, value] of Object.entries(record(top.accounts, 'accounts'))) {
80
+ if (!isAccountName(name))
81
+ bad(`accounts: "${shown(name)}" can't be an account's name. A name is letters, digits, - and _`);
82
+ const entry = record(value, `accounts.${name}`);
83
+ onlyKeys(entry, ['kind', 'key', 'keyEnv'], `accounts.${name}`);
84
+ if (!isAccountKind(entry.kind))
85
+ bad(`accounts.${name}.kind must be one of ${Object.keys(ACCOUNT_KINDS).join(', ')}`);
86
+ if (entry.kind === 'chatgpt-plan') {
87
+ for (const field of ['key', 'keyEnv']) {
88
+ if (entry[field] !== undefined)
89
+ bad(`accounts.${name} takes no ${field}: a ChatGPT plan account uses the sign-in from phantom config chatgpt login`);
90
+ }
91
+ accounts[name] = { kind: entry.kind };
92
+ continue;
93
+ }
94
+ if (entry.keyEnv !== undefined && entry.key !== undefined)
95
+ bad(`accounts.${name} has both keyEnv and key. Keep key`);
96
+ if (entry.keyEnv !== undefined) {
97
+ if (typeof entry.keyEnv !== 'string' || !isEnvName(entry.keyEnv))
98
+ bad(`accounts.${name}.keyEnv must be ${ENV_NAME_RULE}`);
99
+ accounts[name] = { kind: entry.kind, key: { from: 'env', name: entry.keyEnv } };
100
+ continue;
101
+ }
102
+ accounts[name] = { kind: entry.kind, key: entry.key == null ? null : keySource(entry.key, name) };
103
+ }
104
+ const tiersRaw = record(top.tiers, 'tiers');
105
+ onlyKeys(tiersRaw, TIERS, 'tiers');
106
+ const target = (value, where, extra = []) => {
107
+ const entry = record(value, where);
108
+ onlyKeys(entry, ['account', 'model', ...extra], where);
109
+ if (typeof entry.account !== 'string' || !Object.hasOwn(accounts, entry.account))
110
+ bad(`${where}.account must name one of the accounts`);
111
+ if (typeof entry.model !== 'string')
112
+ bad(`${where}.model must be a model id`);
113
+ const problem = modelProblem(accounts[entry.account].kind, entry.model);
114
+ if (problem)
115
+ bad(`${where}.model: ${problem}`);
116
+ return { account: entry.account, model: entry.model };
117
+ };
118
+ const tier = (name) => {
119
+ const entry = record(tiersRaw[name], `tiers.${name}`);
120
+ const main = target(entry, `tiers.${name}`, ['fallback']);
121
+ return entry.fallback === undefined ? main : { ...main, fallback: target(entry.fallback, `tiers.${name}.fallback`) };
122
+ };
123
+ return { log, sensitivity: sensitivity, traces, trial, accounts, tiers: { standard: tier('standard'), frontier: tier('frontier') } };
124
+ }
125
+ export function describeTier(entry) {
126
+ const target = (t) => `${t.model} on ${shown(t.account)}`;
127
+ return `${target(entry)}${entry.fallback ? `, then ${target(entry.fallback)}` : ''}`;
128
+ }
129
+ export function accountsInUse(config) {
130
+ const names = TIERS.flatMap((t) => [config.tiers[t].account, config.tiers[t].fallback?.account]);
131
+ return [...new Set(names.filter((n) => Boolean(n)))];
132
+ }
133
+ function keySource(value, account) {
134
+ const where = `accounts.${account}.key`;
135
+ const entry = record(value, where);
136
+ switch (entry.from) {
137
+ case 'saved':
138
+ onlyKeys(entry, ['from'], where);
139
+ return { from: 'saved' };
140
+ case 'env':
141
+ onlyKeys(entry, ['from', 'name'], where);
142
+ if (typeof entry.name !== 'string' || !isEnvName(entry.name))
143
+ bad(`${where}.name must be ${ENV_NAME_RULE}`);
144
+ return { from: 'env', name: entry.name };
145
+ case 'keychain':
146
+ onlyKeys(entry, ['from', 'service', 'account'], where);
147
+ if (typeof entry.service !== 'string' || !entry.service)
148
+ bad(`${where}.service must name a Keychain item's service`);
149
+ if (entry.account !== undefined && (typeof entry.account !== 'string' || !entry.account))
150
+ bad(`${where}.account must be a Keychain account name`);
151
+ return entry.account === undefined ? { from: 'keychain', service: entry.service } : { from: 'keychain', service: entry.service, account: entry.account };
152
+ default:
153
+ bad(`${where}.from must be saved, env or keychain`);
154
+ }
155
+ }
156
+ function bad(why) {
157
+ die(`local.json: ${why}.`, 'local_config_invalid');
158
+ }
159
+ function record(value, where) {
160
+ if (!value || typeof value !== 'object' || Array.isArray(value))
161
+ bad(`${where} must be an object`);
162
+ return value;
163
+ }
164
+ function onlyKeys(entry, allowed, where) {
165
+ const extra = Object.keys(entry).find((k) => !allowed.includes(k));
166
+ if (extra !== undefined)
167
+ bad(`${where} has a field phantom doesn't know: "${extra.slice(0, 40)}"`);
168
+ }
@@ -0,0 +1,37 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import type { Sensitivity, Tier } from './config.mts';
3
+ import { type RouterSource, type RouterAnswer } from './rust-router.mts';
4
+ export type TierPick = {
5
+ tier: Tier;
6
+ reason: string;
7
+ router?: RouterAnswer;
8
+ trial?: Tier;
9
+ };
10
+ export type ReadsImages = boolean | 'unknown';
11
+ export type ImageReaders = Record<Tier, ReadsImages>;
12
+ export type Picker = (headers: Headers, messages: unknown) => Promise<TierPick>;
13
+ export declare const MAX_MOVE_UP_TOKENS = 40000;
14
+ export type Coin = () => Tier | null;
15
+ export declare const flipCoin: Coin;
16
+ export declare function phantom1Picker(opts: {
17
+ env: Env;
18
+ warn: (line: string) => void;
19
+ findRustRouter?: () => RouterSource | null;
20
+ sensitivity?: Sensitivity;
21
+ maxMoveUpTokens?: number;
22
+ imageReaders?: () => Promise<ImageReaders>;
23
+ coin?: Coin;
24
+ }): Picker;
25
+ export declare const IMAGE_NOTE = "[The person attached an image here, but the models phantom-1 routes to can't read images, so it was left out. Start your answer by saying you couldn't look at the image because their models don't have vision, then help as well as you can from their text.]";
26
+ export declare function taskHasImages(messages: unknown): boolean;
27
+ export declare function withTaskImagesAsNotes(messages: unknown[]): unknown[];
28
+ export declare function conversationId(headers: Headers, messages: unknown): string | null;
29
+ export type Signals = {
30
+ messages: number;
31
+ user_turns: number;
32
+ tool_calls: number;
33
+ tool_errors_last_turn: number;
34
+ images: number;
35
+ tokens_est: number;
36
+ };
37
+ export declare function signalsOf(messages: unknown): Signals;
@@ -0,0 +1,201 @@
1
+ // docs: phantom-1's tier decision for phantom-1 on this computer, made on this computer the way web/lib/decide-route.ts makes it on Phantom's server: a helper agent's side job stays on Standard, a task with an image goes to a tier whose model reads images (or, when none can, the image becomes a note that tells the model to say so), failure words move up to Frontier, else the router picks (at the sensitivity local.json sets), and a conversation over 40,000 estimated tokens, not counting its system and developer messages, doesn't move up for the router alone. With the trial on (CLI only), the first step of a task that the router alone moves up to Frontier flips a coin: Frontier lets the task run as the router picks, Standard keeps it on Standard wherever the router alone would move it up, and every later pick of the task names its side. Keeps only a salted conversation id, its last tier and its side, in memory. Also counts the request's signals for the request log (`signalsOf`): numbers only, no text
2
+ import { createHmac, randomBytes, randomInt } from 'node:crypto';
3
+ import { agentSession, isHelperAgent } from "./agent-headers.mjs";
4
+ import { failureSign } from "./failure-signs.mjs";
5
+ import { findRouter, loadFailure, loadRustRouter, unpackHint } from "./rust-router.mjs";
6
+ export const MAX_MOVE_UP_TOKENS = 40_000;
7
+ const MOVES_UP_AT_ANY_SIZE = new Set(['router:override', 'said-failed', 'agent-failed', 'image']);
8
+ const MAX_REMEMBERED = 1_000;
9
+ export const flipCoin = () => (randomInt(2) === 0 ? 'standard' : 'frontier');
10
+ function remember(memory, convo, tier) {
11
+ memory.delete(convo);
12
+ memory.set(convo, tier);
13
+ if (memory.size > MAX_REMEMBERED)
14
+ memory.delete(memory.keys().next().value);
15
+ }
16
+ export function phantom1Picker(opts) {
17
+ const sensitivity = opts.sensitivity ?? 'balanced';
18
+ const maxMoveUpTokens = opts.maxMoveUpTokens ?? MAX_MOVE_UP_TOKENS;
19
+ const lastTier = new Map();
20
+ const trialSide = new Map();
21
+ const warned = new Set();
22
+ const warnOnce = (line) => {
23
+ if (warned.has(line))
24
+ return;
25
+ warned.add(line);
26
+ opts.warn(line);
27
+ };
28
+ let selectAuto;
29
+ function rustRouter() {
30
+ if (selectAuto !== undefined)
31
+ return selectAuto;
32
+ const dir = (opts.findRustRouter ?? (() => findRouter(opts.env)))();
33
+ try {
34
+ selectAuto = dir ? loadRustRouter(dir) : null;
35
+ }
36
+ catch (err) {
37
+ selectAuto = null;
38
+ warnOnce(`${loadFailure(dir, err)}, so phantom-1 picks Frontier when no rule decides.${unpackHint(dir)}`);
39
+ }
40
+ if (!dir)
41
+ warnOnce('The router is not on this computer, so phantom-1 picks Frontier when no rule decides. Set PHANTOM_ROUTER_DIR to a built routers/phantom-1/router/ folder.');
42
+ return selectAuto;
43
+ }
44
+ async function firstPick(headers, messages, convo) {
45
+ if (isHelperAgent(headers))
46
+ return { tier: 'standard', reason: 'helper' };
47
+ const sign = failureSign(messages, 'openai_chat');
48
+ if (sign)
49
+ return { tier: 'frontier', reason: sign };
50
+ const select = rustRouter();
51
+ if (!select)
52
+ return { tier: 'frontier', reason: 'router:unavailable' };
53
+ try {
54
+ const choice = await select(Array.isArray(messages) ? messages : [], 'openai_chat', convo ?? undefined, sensitivity);
55
+ return { tier: choice.tier, reason: `router:${choice.source}`, router: choice };
56
+ }
57
+ catch (err) {
58
+ warnOnce(`The router's call failed (${errorName(err)}), so phantom-1 picked Frontier.`);
59
+ return { tier: 'frontier', reason: 'router:unavailable' };
60
+ }
61
+ }
62
+ function withTrial(pick, convo, hasImages) {
63
+ if (!opts.coin || convo === null)
64
+ return pick;
65
+ const routerAloneMovesUp = pick.tier === 'frontier' && pick.reason.startsWith('router:') && !MOVES_UP_AT_ANY_SIZE.has(pick.reason) && pick.reason !== 'router:unavailable';
66
+ let side = trialSide.get(convo);
67
+ if (side === undefined && routerAloneMovesUp && !hasImages) {
68
+ side = opts.coin() ?? undefined;
69
+ if (side)
70
+ remember(trialSide, convo, side);
71
+ }
72
+ if (side === undefined)
73
+ return pick;
74
+ if (side === 'standard' && routerAloneMovesUp && !hasImages)
75
+ return { tier: 'standard', reason: 'trial', router: pick.router, trial: side };
76
+ return { ...pick, trial: side };
77
+ }
78
+ return async (headers, messages) => {
79
+ const convo = conversationId(headers, messages);
80
+ const hasImages = taskHasImages(messages);
81
+ let pick = await firstPick(headers, messages, convo);
82
+ if (opts.imageReaders && hasImages)
83
+ pick = pickForImages(pick, await opts.imageReaders());
84
+ const onFrontier = convo !== null && lastTier.get(convo) === 'frontier';
85
+ const waitsOnSize = pick.tier === 'frontier' && !onFrontier && !MOVES_UP_AT_ANY_SIZE.has(pick.reason);
86
+ if (waitsOnSize && conversationTokens(messages) > maxMoveUpTokens)
87
+ pick = { tier: 'standard', reason: 'too-large', router: pick.router };
88
+ pick = withTrial(pick, convo, hasImages);
89
+ if (convo)
90
+ remember(lastTier, convo, pick.tier);
91
+ return pick;
92
+ };
93
+ }
94
+ function pickForImages(pick, readers) {
95
+ if (readers[pick.tier] !== false)
96
+ return pick;
97
+ const other = pick.tier === 'standard' ? 'frontier' : 'standard';
98
+ return readers[other] !== false ? { tier: other, reason: 'image' } : pick;
99
+ }
100
+ export const IMAGE_NOTE = "[The person attached an image here, but the models phantom-1 routes to can't read images, so it was left out. Start your answer by saying you couldn't look at the image because their models don't have vision, then help as well as you can from their text.]";
101
+ function role(message) {
102
+ return message && typeof message === 'object' ? message.role : undefined;
103
+ }
104
+ /** The person's latest typed message: the last user message that doesn't follow a tool result (pi sends an image a tool read as a user message right after the results). */
105
+ function taskStart(messages) {
106
+ for (let index = messages.length - 1; index > 0; index--) {
107
+ if (role(messages[index]) === 'user' && role(messages[index - 1]) !== 'tool')
108
+ return index;
109
+ }
110
+ return 0;
111
+ }
112
+ export function taskHasImages(messages) {
113
+ return Array.isArray(messages) && imageParts(messages.slice(taskStart(messages))).size > 0;
114
+ }
115
+ export function withTaskImagesAsNotes(messages) {
116
+ const start = taskStart(messages);
117
+ const images = imageParts(messages.slice(start));
118
+ const note = { type: 'text', text: IMAGE_NOTE };
119
+ const swap = (parts) => Array.isArray(parts) ? parts.map((part) => (images.has(part) ? note : part && typeof part === 'object' && Array.isArray(part.content) ? { ...part, content: swap(part.content) } : part)) : parts;
120
+ return messages.map((message, index) => {
121
+ if (index < start || !message || typeof message !== 'object')
122
+ return message;
123
+ const { content } = message;
124
+ return Array.isArray(content) ? { ...message, content: swap(content) } : message;
125
+ });
126
+ }
127
+ function errorName(err) {
128
+ return err instanceof Error ? err.name : 'Error';
129
+ }
130
+ const SALT = randomBytes(32);
131
+ export function conversationId(headers, messages) {
132
+ if (!Array.isArray(messages))
133
+ return null;
134
+ const all = messages;
135
+ const isSystem = (m) => m?.role === 'system' || m?.role === 'developer';
136
+ const firstUserIndex = all.findIndex((m) => m?.role === 'user');
137
+ const system = (firstUserIndex === -1 ? all : all.slice(0, firstUserIndex)).filter(isSystem);
138
+ const list = all.filter((m) => !isSystem(m));
139
+ const lastUserIndex = list.findLastIndex((m) => m?.role === 'user');
140
+ if (lastUserIndex === -1)
141
+ return null;
142
+ const session = agentSession(headers);
143
+ const scope = session ? ['session-task', session.slice(0, 200)] : ['prompt-task', JSON.stringify(system)];
144
+ const h = createHmac('sha256', SALT);
145
+ for (const part of [...scope, JSON.stringify(list.slice(0, lastUserIndex + 1))])
146
+ h.update(part).update('\0');
147
+ return 'c:' + h.digest('hex');
148
+ }
149
+ const IMAGE_TOKENS = 1_600;
150
+ function messageTokens(messages) {
151
+ if (!Array.isArray(messages))
152
+ return Math.max(1, Math.ceil(JSON.stringify(messages || '').length / 4));
153
+ const images = imageParts(messages);
154
+ const text = JSON.stringify(messages, (_key, value) => (images.has(value) ? '[image]' : value));
155
+ return Math.max(1, Math.ceil(text.length / 4)) + images.size * IMAGE_TOKENS;
156
+ }
157
+ const INSTRUCTION_ROLES = new Set(['system', 'developer']);
158
+ function conversationTokens(messages) {
159
+ if (!Array.isArray(messages))
160
+ return messageTokens(messages);
161
+ return messageTokens(messages.filter((message) => !INSTRUCTION_ROLES.has(message?.role)));
162
+ }
163
+ function imageParts(messages) {
164
+ const images = new Set();
165
+ const collect = (parts) => {
166
+ if (!Array.isArray(parts))
167
+ return;
168
+ for (const part of parts) {
169
+ if (!part || typeof part !== 'object')
170
+ continue;
171
+ const { type, content } = part;
172
+ if (type === 'image_url' || type === 'input_image' || type === 'image')
173
+ images.add(part);
174
+ else if (type === 'tool_result')
175
+ collect(content);
176
+ }
177
+ };
178
+ for (const message of messages) {
179
+ if (!message || typeof message !== 'object')
180
+ continue;
181
+ collect(message.content);
182
+ collect(message.output);
183
+ }
184
+ return images;
185
+ }
186
+ const TOOL_ERROR = /\b(errors?|failed|exceptions?|traceback)\b|exit code [1-9]/i;
187
+ export function signalsOf(messages) {
188
+ const tokens_est = messageTokens(messages);
189
+ if (!Array.isArray(messages))
190
+ return { messages: 0, user_turns: 0, tool_calls: 0, tool_errors_last_turn: 0, images: 0, tokens_est };
191
+ const all = messages;
192
+ const lastTurn = all.slice(all.findLastIndex((m) => m?.role === 'assistant') + 1);
193
+ return {
194
+ messages: all.length,
195
+ user_turns: all.filter((m) => m?.role === 'user').length,
196
+ tool_calls: all.reduce((sum, m) => sum + (m?.role === 'assistant' && Array.isArray(m.tool_calls) ? m.tool_calls.length : 0), 0),
197
+ tool_errors_last_turn: lastTurn.filter((m) => m?.role === 'tool' && TOOL_ERROR.test(typeof m.content === 'string' ? m.content : JSON.stringify(m.content ?? ''))).length,
198
+ images: imageParts(all).size,
199
+ tokens_est,
200
+ };
201
+ }