@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,137 @@
1
+ // docs: The setting flags of `phantom config`: each tier's account and model, and an optional fallback, the router's sensitivity, traces on or off, and the trial on or off, written to local.json with no keys (its log and accounts kept). --standard, --frontier, --standard-fallback and --frontier-fallback take <account>:<model>, --sensitivity balanced|conservative|strict, --traces on|off and --trial on|off (`configFromFlags`); scripts type them, and each Standard and Frontier pick on the settings screen (cli/app.mts) runs the same command. Turning traces on prints what they hold, where, and how to turn them off and delete them; turning the trial on prints what the coin does
2
+ import { readSession } from "../chatgpt/session.mjs";
3
+ import { die } from "../core/errors.mjs";
4
+ import { out } from "../core/helpers.mjs";
5
+ import { ACCOUNT_KINDS, kindNamed, modelProblem } from "./accounts.mjs";
6
+ import { SENSITIVITIES, TIERS, TIER_NAME, accountsInUse, describeTier, savedOrStarter, writeLocalConfig } from "./config.mjs";
7
+ import { fixCommand, missingText, resolveKey, shown } from "./keys.mjs";
8
+ import { listModels } from "./models.mjs";
9
+ import { tracesFolder } from "./traces.mjs";
10
+ const FLAGS = { standard: 'standard', frontier: 'frontier', 'standard-fallback': 'standard', 'frontier-fallback': 'frontier' };
11
+ const TIER_FLAGS = Object.keys(FLAGS);
12
+ export const SETTING_FLAGS = [...TIER_FLAGS, 'sensitivity', 'traces', 'trial'];
13
+ const newAccount = (kind) => (kind === 'chatgpt-plan' ? { kind } : { kind, key: { from: 'env', name: ACCOUNT_KINDS[kind].keyEnv } });
14
+ export async function configFromFlags(input) {
15
+ const { env, io, flags } = input;
16
+ const { config: checked, chosen } = withFlags(savedOrStarter(env), flags);
17
+ const lists = new Map();
18
+ for (const { account, model } of chosen) {
19
+ if (!lists.has(account))
20
+ lists.set(account, listModels(account, checked.accounts[account], env));
21
+ const list = await lists.get(account);
22
+ if ('error' in list)
23
+ io.stderr(`Could not check ${shown(model)} on ${shown(account)}: ${list.error}\n`);
24
+ else if (!list.models.some((m) => m.id === model)) {
25
+ if (list.source === 'live')
26
+ die(`${shown(account)} has no model "${shown(model)}". phantom config models ${shown(account)} lists them.`, 'local_setup_model');
27
+ io.stderr(`${shown(model)} is not in the ${ACCOUNT_KINDS[list.kind].label}'s documented models; it is written as typed.\n`);
28
+ }
29
+ }
30
+ const { config } = withFlags(savedOrStarter(env), flags);
31
+ for (const line of readiness(env, config))
32
+ io.stderr(line + '\n');
33
+ const written = writeLocalConfig(env, config);
34
+ const folder = tracesFolder(env);
35
+ const lines = [
36
+ `Wrote ${written}.`,
37
+ ...TIERS.map((t) => `${TIER_NAME[t]}: ${describeTier(config.tiers[t])}`),
38
+ ...(flags['sensitivity'] !== undefined ? [`Sensitivity: ${config.sensitivity}, from the next phantom pi (one already running keeps its setting).`] : []),
39
+ ...(flags['traces'] !== undefined ? ['', tracesText(config.traces, folder)] : []),
40
+ ...(flags['trial'] !== undefined ? ['', trialText(config)] : []),
41
+ ];
42
+ out({ file: written, tiers: config.tiers, sensitivity: config.sensitivity, traces: config.traces, traces_folder: folder, trial: config.trial }, input.table, () => lines.join('\n'), io.stdout);
43
+ return 0;
44
+ }
45
+ function tracesText(on, folder) {
46
+ if (!on) {
47
+ return [
48
+ 'Traces off from the next phantom pi: it saves no prompts or answers. A phantom pi already running keeps saving until it ends.',
49
+ `Traces already saved stay in ${folder} until you delete them with rm -r ${folder}`,
50
+ ].join('\n');
51
+ }
52
+ return [
53
+ 'Traces on. From the next phantom pi, phantom-1 saves the full prompt and the full answer of every request:',
54
+ 'your messages, your code and tool output, and the model\'s reply. They stay on this computer only,',
55
+ `in ${folder}, one file per day and run, readable by you only, up to 2 GB (the oldest files go first). Nothing is sent anywhere.`,
56
+ `Turn them off with phantom config --traces off, and delete them with rm -r ${folder}`,
57
+ ].join('\n');
58
+ }
59
+ function trialText(config) {
60
+ if (!config.trial)
61
+ return 'Trial off from the next phantom pi: the router moves tasks up to Frontier as usual.';
62
+ return [
63
+ 'Trial on from the next phantom pi. When the router moves a task up to Frontier, a coin decides the whole task:',
64
+ 'heads it runs as the router picks, tails it stays on Standard (failure words and hard errors still move it up).',
65
+ 'Each request saves its side, so whole tasks on each side can be graded and compared.',
66
+ ...(config.traces ? [] : ['Grading needs the tasks themselves: turn traces on too, with phantom config --traces on']),
67
+ 'Turn it off with phantom config --trial off',
68
+ ].join('\n');
69
+ }
70
+ function withFlags(base, flags) {
71
+ const config = structuredClone(base);
72
+ const { accounts, tiers } = config;
73
+ const chosen = [];
74
+ const traces = flags['traces'];
75
+ if (traces !== undefined) {
76
+ if (traces !== 'on' && traces !== 'off')
77
+ die('--traces takes on or off.', 'local_setup_usage');
78
+ config.traces = traces === 'on';
79
+ }
80
+ const trial = flags['trial'];
81
+ if (trial !== undefined) {
82
+ if (trial !== 'on' && trial !== 'off')
83
+ die('--trial takes on or off.', 'local_setup_usage');
84
+ config.trial = trial === 'on';
85
+ }
86
+ const sensitivity = flags['sensitivity'];
87
+ if (sensitivity !== undefined) {
88
+ if (!SENSITIVITIES.includes(sensitivity))
89
+ die('--sensitivity takes balanced, conservative or strict.', 'local_setup_usage');
90
+ config.sensitivity = sensitivity;
91
+ }
92
+ for (const flag of TIER_FLAGS.filter((f) => flags[f] !== undefined)) {
93
+ const value = flags[flag];
94
+ const tier = FLAGS[flag];
95
+ const fallback = flag.endsWith('-fallback');
96
+ if (fallback && value === 'none') {
97
+ delete tiers[tier].fallback;
98
+ continue;
99
+ }
100
+ const colon = typeof value === 'string' ? value.indexOf(':') : -1;
101
+ if (typeof value !== 'string' || colon <= 0 || colon === value.length - 1)
102
+ die(`--${flag} needs an account and a model, such as zai:glm-5.4${fallback ? ', or none' : ''}.`, 'local_setup_usage');
103
+ const name = value.slice(0, colon);
104
+ const model = value.slice(colon + 1);
105
+ if (!Object.hasOwn(accounts, name)) {
106
+ const kind = kindNamed(name);
107
+ if (!kind)
108
+ die(`--${flag} names account "${shown(name)}". Use gateway, zai, chatgpt or an account in local.json.`, 'local_setup_usage');
109
+ accounts[name] = newAccount(kind);
110
+ }
111
+ const problem = modelProblem(accounts[name].kind, model);
112
+ if (problem)
113
+ die(`--${flag}: ${problem}.`, 'local_setup_usage');
114
+ const target = { account: name, model };
115
+ if (fallback)
116
+ tiers[tier].fallback = target;
117
+ else
118
+ tiers[tier] = { ...target, ...(tiers[tier].fallback && { fallback: tiers[tier].fallback }) };
119
+ chosen.push(target);
120
+ }
121
+ return { config, chosen };
122
+ }
123
+ function readiness(env, config) {
124
+ const lines = [];
125
+ for (const name of accountsInUse(config)) {
126
+ const account = config.accounts[name];
127
+ if (account.kind === 'chatgpt-plan') {
128
+ if (readSession(env).kind !== 'signed-in')
129
+ lines.push(`${shown(name)}: run phantom config chatgpt login first, or its tiers use their fallback.`);
130
+ continue;
131
+ }
132
+ const lookup = resolveKey(env, name, account);
133
+ if (!lookup.found)
134
+ lines.push(`${shown(name)}: ${missingText(account, lookup.missing)}. Run ${fixCommand(name)} first.`);
135
+ }
136
+ return lines;
137
+ }
@@ -0,0 +1,69 @@
1
+ import { type Env } from '../core/state.mts';
2
+ import { type LocalConfig, type Sensitivity, type Tier } from './config.mts';
3
+ import { type Outcome, type RequestRecord } from './request-log.mts';
4
+ import type { RouterAnswer } from './rust-router.mts';
5
+ type ToolCall = {
6
+ id: string;
7
+ type: string;
8
+ function: {
9
+ name: string;
10
+ arguments: string;
11
+ };
12
+ };
13
+ export type TraceLine = {
14
+ v: 1 | 2;
15
+ id: string;
16
+ run: string;
17
+ conversation: string | null;
18
+ at: string;
19
+ phantom: string;
20
+ router_version: string | null;
21
+ sensitivity: Sensitivity;
22
+ tiers: LocalConfig['tiers'];
23
+ decision: {
24
+ picked: Tier;
25
+ reason: string;
26
+ router: RouterAnswer | null;
27
+ trial?: Tier;
28
+ };
29
+ request: unknown;
30
+ answer: {
31
+ account: string;
32
+ model: string;
33
+ fallback: boolean;
34
+ status: number | null;
35
+ outcome: Outcome;
36
+ text: string | null;
37
+ reasoning: string | null;
38
+ tool_calls: ToolCall[];
39
+ finish_reason: string | null;
40
+ usage: unknown;
41
+ ms: RequestRecord['ms'];
42
+ raw?: string;
43
+ };
44
+ };
45
+ export type TraceInput = {
46
+ record: RequestRecord;
47
+ tiers: LocalConfig['tiers'];
48
+ request: unknown;
49
+ received: {
50
+ sse: boolean;
51
+ text: string;
52
+ };
53
+ };
54
+ export declare function tracesFolder(env: Env): string;
55
+ export type TraceLog = {
56
+ write: (input: TraceInput) => void;
57
+ idle: () => Promise<void>;
58
+ };
59
+ export declare function traceLog(opts: {
60
+ env: Env;
61
+ warn: (line: string) => void;
62
+ capBytes?: number;
63
+ }): TraceLog;
64
+ export declare function readTraces(env: Env, since: Date | null, onBadLine?: () => void): AsyncGenerator<TraceLine>;
65
+ export declare function tracesSize(env: Env): {
66
+ files: number;
67
+ bytes: number;
68
+ };
69
+ export {};
@@ -0,0 +1,341 @@
1
+ // docs: The traces of phantom-1 on this computer, off unless `phantom config --traces on`: one JSON line per finished request in <state>/local/traces/<YYYY-MM-DD>.<run>.jsonl, a file per day and `phantom pi` run (files mode 600, folders 700) with the run, versions, settings, tiers and decision (with the trial's side, when the task is in the trial), the agent's request body, and the whole answer the agent received (text, reasoning, tool calls, finish reason, usage). A request whose first messages an earlier line of the same file already holds is saved as only the messages after them and a pointer to that line with a hash of those messages (`prefix`); every other request is saved whole, and so is the next one after a failed write or after another run deleted the file. Never a header, key or token. Past 2 GB the oldest files of other runs are deleted. Also reads them back with every request whole, for `phantom replay` and the improve-phantom-routing skill's scripts/tasks.mjs, and sizes them for `phantom report`
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { createReadStream, existsSync, readdirSync, statSync } from 'node:fs';
5
+ import { appendFile, stat, unlink } from 'node:fs/promises';
6
+ import { makePrivateFolder, stateDir } from "../core/state.mjs";
7
+ import { SENSITIVITIES } from "./config.mjs";
8
+ import { shown } from "./keys.mjs";
9
+ import { withCurrentNames } from "./request-log.mjs";
10
+ function startHashes(messages, hashOfMessagesBefore = '') {
11
+ let hash = hashOfMessagesBefore;
12
+ return messages.map((message) => (hash = createHash('sha256').update(hash).update(JSON.stringify(message)).digest('hex')));
13
+ }
14
+ const shortHash = (hash) => hash.slice(0, 16);
15
+ const startKey = (count, hash) => `${count} ${hash}`;
16
+ export function tracesFolder(env) {
17
+ return path.join(stateDir(env), 'local', 'traces');
18
+ }
19
+ const TRACES_CAP_BYTES = 2 * 1024 ** 3;
20
+ const TRACE_FILE = /^(\d{4}-\d{2}-\d{2})\.(run_[A-Za-z0-9]+)\.jsonl$/;
21
+ function traceFiles(folder) {
22
+ return readdirSync(folder)
23
+ .sort()
24
+ .flatMap((name) => {
25
+ const match = TRACE_FILE.exec(name);
26
+ return match ? [{ name, day: match[1], run: match[2] }] : [];
27
+ });
28
+ }
29
+ export function traceLog(opts) {
30
+ const folder = tracesFolder(opts.env);
31
+ const cap = opts.capBytes ?? TRACES_CAP_BYTES;
32
+ let queue = Promise.resolve();
33
+ let total = null;
34
+ const warned = new Set();
35
+ const warnOnce = (kind, line) => {
36
+ if (warned.has(kind))
37
+ return;
38
+ warned.add(kind);
39
+ opts.warn(line);
40
+ };
41
+ let current = { file: '', size: 0, ids: new Set(), idByStart: new Map() };
42
+ async function append(input) {
43
+ if (total === null) {
44
+ makePrivateFolder(opts.env, folder);
45
+ total = (await filesWithSizes()).reduce((sum, file) => sum + file.size, 0);
46
+ }
47
+ const { id } = input.record;
48
+ const file = path.join(folder, `${input.record.at.slice(0, 10)}.${input.record.run}.jsonl`);
49
+ if (file !== current.file)
50
+ current = { file, size: 0, ids: new Set(), idByStart: new Map() };
51
+ const size = await sizeOf(file);
52
+ const fileChangedSinceLastWrite = size !== current.size;
53
+ if (fileChangedSinceLastWrite)
54
+ current.idByStart = new Map();
55
+ const idWrittenBefore = current.ids.has(id);
56
+ current.ids.add(id);
57
+ if (idWrittenBefore)
58
+ for (const [key, idThere] of current.idByStart)
59
+ if (idThere === id)
60
+ current.idByStart.delete(key);
61
+ const { line, key } = withPrefix(traceLine(input), current.idByStart);
62
+ const text = (fileChangedSinceLastWrite && size > 0 ? '\n' : '') + JSON.stringify(line) + '\n';
63
+ await appendFile(file, text, { mode: 0o600 });
64
+ current.size = size + Buffer.byteLength(text);
65
+ if (!idWrittenBefore)
66
+ current.idByStart.set(key, id);
67
+ total += Buffer.byteLength(text);
68
+ if (total > cap)
69
+ await trim(input.record.run);
70
+ }
71
+ async function sizeOf(file) {
72
+ try {
73
+ return (await stat(file)).size;
74
+ }
75
+ catch (err) {
76
+ if (err.code === 'ENOENT')
77
+ return 0;
78
+ throw err;
79
+ }
80
+ }
81
+ async function trim(run) {
82
+ const files = await filesWithSizes();
83
+ total = files.reduce((sum, file) => sum + file.size, 0);
84
+ for (const oldest of files.filter((file) => file.run !== run)) {
85
+ if (total <= cap)
86
+ break;
87
+ await unlink(path.join(folder, oldest.name)).catch((err) => {
88
+ if (err.code !== 'ENOENT')
89
+ throw err;
90
+ });
91
+ total -= oldest.size;
92
+ warnOnce('cap', `Traces passed ${gb(cap)}, so phantom-1 deleted the oldest file (${oldest.name}) in ${folder}.`);
93
+ }
94
+ }
95
+ async function filesWithSizes() {
96
+ const sized = await Promise.all(traceFiles(folder).map(async (file) => {
97
+ try {
98
+ return { ...file, size: (await stat(path.join(folder, file.name))).size };
99
+ }
100
+ catch (err) {
101
+ if (err.code === 'ENOENT')
102
+ return null;
103
+ throw err;
104
+ }
105
+ }));
106
+ return sized.filter((file) => file !== null);
107
+ }
108
+ return {
109
+ write(input) {
110
+ queue = queue
111
+ .then(() => append(input))
112
+ .catch((err) => {
113
+ warnOnce('write', `phantom-1 could not save a trace in ${folder} (${err.code ?? 'error'}). Requests still go through.`);
114
+ });
115
+ },
116
+ idle: () => queue,
117
+ };
118
+ }
119
+ function gb(bytes) {
120
+ return bytes % 1024 ** 3 === 0 ? `${bytes / 1024 ** 3} GB` : `${bytes} bytes`;
121
+ }
122
+ function withPrefix(trace, idByStart) {
123
+ const messages = trace.request?.messages;
124
+ const list = Array.isArray(messages) ? messages : [];
125
+ const hashes = startHashes(list);
126
+ let prefix;
127
+ for (const [i, hash] of hashes.entries()) {
128
+ const id = idByStart.get(startKey(i + 1, hash));
129
+ if (id)
130
+ prefix = { id, messages: i + 1, hash: shortHash(hash) };
131
+ }
132
+ const key = startKey(list.length, hashes.at(-1) ?? '');
133
+ if (!prefix)
134
+ return { line: trace, key };
135
+ const { request, answer, ...head } = trace;
136
+ return { line: { ...head, prefix, request: { ...request, messages: list.slice(prefix.messages) }, answer }, key };
137
+ }
138
+ function traceLine({ record, tiers, request, received }) {
139
+ return {
140
+ v: 2,
141
+ id: record.id,
142
+ run: record.run,
143
+ conversation: record.conversation,
144
+ at: record.at,
145
+ phantom: record.phantom,
146
+ router_version: record.router_version,
147
+ sensitivity: record.sensitivity,
148
+ tiers,
149
+ decision: { picked: record.picked, reason: record.reason, router: record.router, ...(record.trial && { trial: record.trial }) },
150
+ request,
151
+ answer: {
152
+ account: record.account,
153
+ model: record.model,
154
+ fallback: record.fallback,
155
+ status: record.status,
156
+ outcome: record.outcome,
157
+ ...answerOf(received),
158
+ ms: record.ms,
159
+ },
160
+ };
161
+ }
162
+ function answerOf(received) {
163
+ const answer = { text: null, reasoning: null, tool_calls: [], finish_reason: null, usage: null };
164
+ const json = (text) => {
165
+ try {
166
+ const value = JSON.parse(text);
167
+ return value && typeof value === 'object' ? value : null;
168
+ }
169
+ catch {
170
+ return null;
171
+ }
172
+ };
173
+ let read = false;
174
+ let streamError = false;
175
+ if (received.sse) {
176
+ const calls = new Map();
177
+ let lastCall;
178
+ for (const line of received.text.split('\n')) {
179
+ if (!line.startsWith('data:'))
180
+ continue;
181
+ const chunk = json(line.slice(5).trim());
182
+ if (!chunk)
183
+ continue;
184
+ read = true;
185
+ if (chunk.error)
186
+ streamError = true;
187
+ if (chunk.usage)
188
+ answer.usage = chunk.usage;
189
+ const choice = chunk.choices?.[0];
190
+ const delta = choice?.delta ?? {};
191
+ const text = textOf(delta.content);
192
+ if (text !== null)
193
+ answer.text = (answer.text ?? '') + text;
194
+ const reasoning = reasoningOf(delta);
195
+ if (reasoning !== null)
196
+ answer.reasoning = (answer.reasoning ?? '') + reasoning;
197
+ for (const part of Array.isArray(delta.tool_calls) ? delta.tool_calls : []) {
198
+ const key = typeof part.index === 'number' ? `index ${part.index}` : typeof part.id === 'string' ? `id ${part.id}` : null;
199
+ let call = key === null ? lastCall : calls.get(key);
200
+ if (!call) {
201
+ call = { id: '', type: 'function', function: { name: '', arguments: '' } };
202
+ calls.set(key ?? `call ${calls.size}`, call);
203
+ }
204
+ lastCall = call;
205
+ call.id = part.id ?? call.id;
206
+ call.type = part.type ?? call.type;
207
+ call.function.name = part.function?.name ?? call.function.name;
208
+ call.function.arguments += part.function?.arguments ?? '';
209
+ }
210
+ if (choice?.finish_reason)
211
+ answer.finish_reason = choice.finish_reason;
212
+ }
213
+ answer.tool_calls = [...calls.values()];
214
+ }
215
+ else {
216
+ const whole = json(received.text);
217
+ const message = whole?.choices?.[0]?.message;
218
+ if (message && typeof message === 'object') {
219
+ read = true;
220
+ answer.text = textOf(message.content);
221
+ answer.reasoning = reasoningOf(message);
222
+ answer.tool_calls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
223
+ answer.finish_reason = whole.choices[0].finish_reason ?? null;
224
+ answer.usage = whole.usage ?? null;
225
+ }
226
+ }
227
+ const unfinished = !read || streamError || answer.finish_reason === null;
228
+ if (unfinished && received.text)
229
+ answer.raw = shown(received.text);
230
+ return answer;
231
+ }
232
+ function textOf(content) {
233
+ if (typeof content === 'string')
234
+ return content;
235
+ if (!Array.isArray(content))
236
+ return null;
237
+ const texts = content.flatMap((part) => (typeof part?.text === 'string' ? [part.text] : []));
238
+ return texts.length ? texts.join('') : null;
239
+ }
240
+ /** A message's reasoning: `reasoning_content`, else `reasoning` (some providers send both, one of them empty), or null. */
241
+ function reasoningOf(message) {
242
+ const reasoning = [message.reasoning_content, message.reasoning].find((value) => typeof value === 'string' && value !== '');
243
+ return typeof reasoning === 'string' ? reasoning : null;
244
+ }
245
+ export async function* readTraces(env, since, onBadLine = () => { }) {
246
+ const folder = tracesFolder(env);
247
+ if (!existsSync(folder))
248
+ return;
249
+ const files = traceFiles(folder);
250
+ const sinceDay = since?.toISOString().slice(0, 10);
251
+ const runs = new Set(files.filter((file) => !sinceDay || file.day >= sinceDay).map((file) => file.run));
252
+ for (const { name, run } of files) {
253
+ if (!runs.has(run))
254
+ continue;
255
+ const earlierLines = new Map();
256
+ for await (const text of linesOf(path.join(folder, name))) {
257
+ if (!text.trim())
258
+ continue;
259
+ let line;
260
+ try {
261
+ line = JSON.parse(text);
262
+ }
263
+ catch {
264
+ onBadLine();
265
+ continue;
266
+ }
267
+ if (line?.kind !== undefined)
268
+ continue;
269
+ const whole = withWholeRequest(withCurrentTraceNames(line), earlierLines);
270
+ if (!whole || !isTrace(whole.line)) {
271
+ onBadLine();
272
+ continue;
273
+ }
274
+ const trace = whole.line;
275
+ const messages = trace.request?.messages;
276
+ if (trace.v === 2 && Array.isArray(messages))
277
+ earlierLines.set(trace.id, { messages, hashes: whole.hashes ?? startHashes(messages) });
278
+ yield trace;
279
+ }
280
+ }
281
+ }
282
+ function withWholeRequest(line, earlierLines) {
283
+ const { prefix, ...rest } = (line ?? {});
284
+ if (prefix === undefined)
285
+ return { line, hashes: null };
286
+ const earlier = earlierLines.get(prefix?.id);
287
+ if (!earlier)
288
+ return null;
289
+ const own = rest.request?.messages;
290
+ const startHash = earlier.hashes[prefix.messages - 1];
291
+ if (!startHash || shortHash(startHash) !== prefix.hash || !Array.isArray(own))
292
+ return null;
293
+ return {
294
+ line: { ...rest, request: { ...rest.request, messages: [...earlier.messages.slice(0, prefix.messages), ...own] } },
295
+ hashes: [...earlier.hashes.slice(0, prefix.messages), ...startHashes(own, startHash)],
296
+ };
297
+ }
298
+ async function* linesOf(file) {
299
+ let started = [];
300
+ for await (const chunk of createReadStream(file, { encoding: 'utf8' })) {
301
+ const pieces = chunk.split('\n');
302
+ if (pieces.length === 1) {
303
+ started.push(pieces[0]);
304
+ continue;
305
+ }
306
+ yield started.join('') + pieces[0];
307
+ for (const line of pieces.slice(1, -1))
308
+ yield line;
309
+ started = [pieces.at(-1)];
310
+ }
311
+ const last = started.join('');
312
+ if (last)
313
+ yield last;
314
+ }
315
+ function withCurrentTraceNames(line) {
316
+ const named = withCurrentNames(line);
317
+ if (named === null || typeof named !== 'object' || !('decision' in named))
318
+ return named;
319
+ return { ...named, decision: withCurrentNames(named.decision) };
320
+ }
321
+ function isTrace(line) {
322
+ const t = line;
323
+ return ((t?.v === 1 || t?.v === 2) &&
324
+ typeof t.id === 'string' &&
325
+ typeof t.run === 'string' &&
326
+ typeof t.at === 'string' &&
327
+ !Number.isNaN(Date.parse(t.at)) &&
328
+ (t.conversation === null || typeof t.conversation === 'string') &&
329
+ (t.router_version === null || typeof t.router_version === 'string') &&
330
+ SENSITIVITIES.includes(t.sensitivity) &&
331
+ (t.decision?.picked === 'standard' || t.decision?.picked === 'frontier') &&
332
+ typeof t.decision.reason === 'string' &&
333
+ typeof t.request === 'object');
334
+ }
335
+ export function tracesSize(env) {
336
+ const folder = tracesFolder(env);
337
+ if (!existsSync(folder))
338
+ return { files: 0, bytes: 0 };
339
+ const files = traceFiles(folder);
340
+ return { files: files.length, bytes: files.reduce((sum, file) => sum + statSync(path.join(folder, file.name)).size, 0) };
341
+ }
@@ -1,45 +1,8 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * phantom: points your coding agents at Phantom AI.
4
- *
5
- * Keys, money and setup for any AI agent: a Phantom AI key, model routing,
6
- * and receipts that show which model answered. It runs as a CLI and through
7
- * the phantom-ai skill, so pi, Claude Code, Codex and Cursor can all drive it
8
- * by prompt.
9
- *
10
- * This file is the entry point. The code lives in one folder per feature
11
- * beside it, and this file exports the public API from them. From a
12
- * checkout: `node src/phantom.mts`.
13
- */
14
- export { DEFAULT_BASE_URL, REQUEST_TIMEOUT_MS, request, httpsOnly, getBalance } from './core/request.mts';
15
2
  export { VERSION } from './core/version.mts';
16
3
  export { PhantomApiError, CliError, die } from './core/errors.mts';
17
- export type { BalanceResult } from './core/shapes.mts';
18
- export { getLineup, putLineup, resetLineup, LINEUP_TIERS } from './spend/lineup.mts';
19
- export type { Lineup, LineupPicks, LineupTier, LineupChoice, LineupTierModel, LineupResult } from './spend/lineup.mts';
20
- export { getRoute, putRoute, patchRoute, clearRoute, testRoute, parseCondition } from './spend/routing.mts';
21
- export type { RouteRule, RoutePolicy, RouteResult, RouteTestResult } from './spend/routing.mts';
22
- export { getSpend, tableSpend } from './spend/report.mts';
23
- export type { SpendResult, SpendLine, SpendTotal, SpendKey, SpendKeyModel, SpendModel, SpendDay, SpendRouting, SpendDates } from './spend/report.mts';
24
- export { checkReceipt, modelsMatch, verifyModel } from './receipts/receipts.mts';
25
- export type { Receipt, ReceiptCheck, VerifyModelResult } from './receipts/receipts.mts';
26
4
  export type { Env } from './core/state.mts';
27
- export { keychain } from './core/secrets.mts';
28
- export { keyId, keySource, resolveApiKey, readNamedKey, saveNamedKey, removeNamedKey, listNamedKeys, saveApiKey, removeApiKey } from './keys/saved.mts';
29
- export type { KeySource } from './keys/saved.mts';
30
- export { SETUP_MODEL, agentBaseUrl } from './setup/shared.mts';
31
- export type { SetupAgent, AgentPath, ProviderResult } from './setup/shared.mts';
32
- export { planSetup } from './setup/plan.mts';
33
- export type { SetupFile, SetupPlan, SetupResult, SetupOptions } from './setup/plan.mts';
34
- export { applySetup, previewSetup, setupAgents, restoreSetup } from './setup/apply.mts';
35
- export type { RestoreResult } from './setup/apply.mts';
36
- export type { SetupContext, SetupEdit, ProviderPlan, SetupAgentSpec } from './setup/shared.mts';
37
- export { jsonEdit, tomlSet, tomlRemoveOurs, yamlSetTop, yamlAddModel, yamlRemoveOurs, shellRcFile, shellBlock } from './setup/editors.mts';
38
- export type { JsonChange, ShellBlockState } from './setup/editors.mts';
39
- export { SETUP_AGENTS } from './setup/agents.mts';
40
- export { claudeProvider } from './setup/apply.mts';
41
5
  export { ENV_VARS, HELP } from './cli/help.mts';
42
6
  export type { EnvVar } from './cli/help.mts';
43
7
  export { run } from './cli/run.mts';
44
- /** The installed entry point: {@link run} with the process's arguments, then `process.exit` with its code when it is not 0. */
45
8
  export declare function main(): Promise<void>;
package/dist/phantom.mjs CHANGED
@@ -1,48 +1,17 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * phantom: points your coding agents at Phantom AI.
4
- *
5
- * Keys, money and setup for any AI agent: a Phantom AI key, model routing,
6
- * and receipts that show which model answered. It runs as a CLI and through
7
- * the phantom-ai skill, so pi, Claude Code, Codex and Cursor can all drive it
8
- * by prompt.
9
- *
10
- * This file is the entry point. The code lives in one folder per feature
11
- * beside it, and this file exports the public API from them. From a
12
- * checkout: `node src/phantom.mts`.
13
- */
14
2
  import { fileURLToPath } from 'node:url';
15
3
  import { realpathSync } from 'node:fs';
16
4
  import { run } from "./cli/run.mjs";
17
- export { DEFAULT_BASE_URL, REQUEST_TIMEOUT_MS, request, httpsOnly, getBalance } from "./core/request.mjs";
18
5
  export { VERSION } from "./core/version.mjs";
19
6
  export { PhantomApiError, CliError, die } from "./core/errors.mjs";
20
- export { getLineup, putLineup, resetLineup, LINEUP_TIERS } from "./spend/lineup.mjs";
21
- export { getRoute, putRoute, patchRoute, clearRoute, testRoute, parseCondition } from "./spend/routing.mjs";
22
- export { getSpend, tableSpend } from "./spend/report.mjs";
23
- export { checkReceipt, modelsMatch, verifyModel } from "./receipts/receipts.mjs";
24
- export { keychain } from "./core/secrets.mjs";
25
- export { keyId, keySource, resolveApiKey, readNamedKey, saveNamedKey, removeNamedKey, listNamedKeys, saveApiKey, removeApiKey } from "./keys/saved.mjs";
26
- // Supported setup interface: plan, preview, apply, and restore.
27
- export { SETUP_MODEL, agentBaseUrl } from "./setup/shared.mjs";
28
- export { planSetup } from "./setup/plan.mjs";
29
- export { applySetup, previewSetup, setupAgents, restoreSetup } from "./setup/apply.mjs";
30
- export { jsonEdit, tomlSet, tomlRemoveOurs, yamlSetTop, yamlAddModel, yamlRemoveOurs, shellRcFile, shellBlock } from "./setup/editors.mjs";
31
- export { SETUP_AGENTS } from "./setup/agents.mjs";
32
- export { claudeProvider } from "./setup/apply.mjs";
33
7
  export { ENV_VARS, HELP } from "./cli/help.mjs";
34
8
  export { run } from "./cli/run.mjs";
35
- /** The installed entry point: {@link run} with the process's arguments, then `process.exit` with its code when it is not 0. */
36
9
  export async function main() {
37
10
  const code = await run();
38
11
  if (code !== 0) {
39
12
  process.exit(code);
40
13
  }
41
14
  }
42
- /**
43
- * True for `node src/phantom.mts`. Installed, the entry point is bin/phantom.mjs,
44
- * which imports `main` and calls it, so this stays false there.
45
- */
46
15
  const isDirectRun = (() => {
47
16
  if (!process.argv[1])
48
17
  return false;