@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.
- package/LICENSE +1 -2
- package/README.md +139 -118
- package/bin/phantom.mjs +37 -2
- package/dist/agents/command.d.mts +8 -27
- package/dist/agents/command.mjs +323 -59
- package/dist/agents/login.d.mts +3 -0
- package/dist/agents/login.mjs +97 -0
- package/dist/agents/opencode-check.d.mts +15 -0
- package/dist/agents/opencode-check.mjs +193 -0
- package/dist/agents/phantom-key.d.mts +7 -0
- package/dist/agents/phantom-key.mjs +40 -0
- package/dist/agents/proxy.d.mts +26 -28
- package/dist/agents/proxy.mjs +225 -33
- package/dist/chatgpt/command.d.mts +2 -0
- package/dist/chatgpt/command.mjs +119 -0
- package/dist/chatgpt/session.d.mts +87 -0
- package/dist/chatgpt/session.mjs +253 -0
- package/dist/cli/accounts.d.mts +21 -0
- package/dist/cli/accounts.mjs +96 -0
- package/dist/cli/app.d.mts +4 -24
- package/dist/cli/app.mjs +224 -139
- package/dist/cli/commands.d.mts +1 -16
- package/dist/cli/commands.mjs +144 -239
- package/dist/cli/help.d.mts +0 -19
- package/dist/cli/help.mjs +30 -55
- package/dist/cli/run.mjs +35 -79
- package/dist/cli/start.d.mts +2 -31
- package/dist/cli/start.mjs +13 -116
- package/dist/core/brand.d.mts +0 -7
- package/dist/core/brand.mjs +0 -8
- package/dist/core/errors.d.mts +0 -16
- package/dist/core/errors.mjs +0 -16
- package/dist/core/helpers.d.mts +0 -46
- package/dist/core/helpers.mjs +1 -64
- package/dist/core/node-trust.d.mts +0 -5
- package/dist/core/node-trust.mjs +0 -6
- package/dist/core/pick.d.mts +7 -55
- package/dist/core/pick.mjs +49 -106
- package/dist/core/request.d.mts +0 -46
- package/dist/core/request.mjs +1 -60
- package/dist/core/secrets.d.mts +0 -4
- package/dist/core/secrets.mjs +0 -10
- package/dist/core/state.d.mts +3 -1
- package/dist/core/state.mjs +147 -4
- package/dist/core/style.d.mts +0 -27
- package/dist/core/style.mjs +0 -20
- package/dist/core/version.d.mts +1 -2
- package/dist/core/version.mjs +1 -2
- package/dist/local/accounts.d.mts +25 -0
- package/dist/local/accounts.mjs +40 -0
- package/dist/local/agent-headers.d.mts +7 -0
- package/dist/local/agent-headers.mjs +44 -0
- package/dist/local/chatgpt-plan.d.mts +147 -0
- package/dist/local/chatgpt-plan.mjs +384 -0
- package/dist/local/command.d.mts +24 -0
- package/dist/local/command.mjs +211 -0
- package/dist/local/config.d.mts +49 -0
- package/dist/local/config.mjs +168 -0
- package/dist/local/decide.d.mts +37 -0
- package/dist/local/decide.mjs +201 -0
- package/dist/local/failure-signs.d.mts +4 -0
- package/dist/local/failure-signs.mjs +99 -0
- package/dist/local/keys.d.mts +32 -0
- package/dist/local/keys.mjs +239 -0
- package/dist/local/models.d.mts +53 -0
- package/dist/local/models.mjs +117 -0
- package/dist/local/replay.d.mts +59 -0
- package/dist/local/replay.mjs +143 -0
- package/dist/local/report.d.mts +43 -0
- package/dist/local/report.mjs +153 -0
- package/dist/local/request-log.d.mts +53 -0
- package/dist/local/request-log.mjs +69 -0
- package/dist/local/retry-after.d.mts +3 -0
- package/dist/local/retry-after.mjs +28 -0
- package/dist/local/rust-router.d.mts +39 -0
- package/dist/local/rust-router.mjs +54 -0
- package/dist/local/server.d.mts +27 -0
- package/dist/local/server.mjs +449 -0
- package/dist/local/status-line.d.mts +17 -0
- package/dist/local/status-line.mjs +81 -0
- package/dist/local/tiers.d.mts +3 -0
- package/dist/local/tiers.mjs +137 -0
- package/dist/local/traces.d.mts +69 -0
- package/dist/local/traces.mjs +341 -0
- package/dist/phantom.d.mts +0 -37
- package/dist/phantom.mjs +0 -31
- package/package.json +15 -9
- package/skills/phantom-ai/SKILL.md +28 -97
- package/dist/cli/screens.d.mts +0 -177
- package/dist/cli/screens.mjs +0 -398
- package/dist/core/free.d.mts +0 -13
- package/dist/core/free.mjs +0 -14
- package/dist/core/motion.d.mts +0 -47
- package/dist/core/motion.mjs +0 -156
- package/dist/core/shapes.d.mts +0 -13
- package/dist/core/shapes.mjs +0 -1
- package/dist/keys/command.d.mts +0 -16
- package/dist/keys/command.mjs +0 -143
- package/dist/keys/saved.d.mts +0 -96
- package/dist/keys/saved.mjs +0 -169
- package/dist/models/choice.d.mts +0 -7
- package/dist/models/choice.mjs +0 -27
- package/dist/models/command.d.mts +0 -8
- package/dist/models/command.mjs +0 -66
- package/dist/models/list.d.mts +0 -39
- package/dist/models/list.mjs +0 -39
- package/dist/receipts/command.d.mts +0 -7
- package/dist/receipts/command.mjs +0 -41
- package/dist/receipts/receipts.d.mts +0 -76
- package/dist/receipts/receipts.mjs +0 -118
- package/dist/setup/agents.d.mts +0 -149
- package/dist/setup/agents.mjs +0 -886
- package/dist/setup/apply.d.mts +0 -85
- package/dist/setup/apply.mjs +0 -301
- package/dist/setup/command.d.mts +0 -12
- package/dist/setup/command.mjs +0 -307
- package/dist/setup/editors.d.mts +0 -108
- package/dist/setup/editors.mjs +0 -500
- package/dist/setup/legacy.d.mts +0 -13
- package/dist/setup/legacy.mjs +0 -36
- package/dist/setup/plan.d.mts +0 -104
- package/dist/setup/plan.mjs +0 -132
- package/dist/setup/screen.d.mts +0 -30
- package/dist/setup/screen.mjs +0 -260
- package/dist/setup/shared.d.mts +0 -141
- package/dist/setup/shared.mjs +0 -88
- package/dist/setup/was.d.mts +0 -42
- package/dist/setup/was.mjs +0 -91
- package/dist/spend/command.d.mts +0 -5
- package/dist/spend/command.mjs +0 -235
- package/dist/spend/lineup.d.mts +0 -61
- package/dist/spend/lineup.mjs +0 -39
- package/dist/spend/reason.d.mts +0 -5
- package/dist/spend/reason.mjs +0 -60
- package/dist/spend/report.d.mts +0 -105
- package/dist/spend/report.mjs +0 -68
- package/dist/spend/routing.d.mts +0 -74
- package/dist/spend/routing.mjs +0 -57
- package/dist/workspace/command.d.mts +0 -59
- package/dist/workspace/command.mjs +0 -871
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// docs: `phantom replay`: runs the saved traces through this CLI's own tier decision (decide.mts) again, once with the settings each was recorded with (the self-check) and once with changed settings (--sensitivity, --max-move-up-tokens), with no model call (it reads the Gateway's public model list once a run when a task has an image and a tier is on the Gateway, to know which models read images), a task the trial put on a side keeping the side its trace saved, and reports which requests change tier, the Frontier share before and after, and the router's score for each request on its own, with how many picks were near the move-up threshold
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { die } from "../core/errors.mjs";
|
|
4
|
+
import { readLocalConfig } from "./config.mjs";
|
|
5
|
+
import { imageReadersFor } from "./models.mjs";
|
|
6
|
+
import { phantom1Picker } from "./decide.mjs";
|
|
7
|
+
import { findRouter, loadFailure, loadRustRouterScore, rustRouterVersion, unpackHint } from "./rust-router.mjs";
|
|
8
|
+
import { readTraces, tracesFolder } from "./traces.mjs";
|
|
9
|
+
const MOVE_UP_THRESHOLD = { balanced: 0.5, conservative: 0.4, strict: 0.2 };
|
|
10
|
+
const NEAR = 0.1;
|
|
11
|
+
function accountsToday(env) {
|
|
12
|
+
try {
|
|
13
|
+
return readLocalConfig(env).accounts;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return {};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export async function replay(opts) {
|
|
20
|
+
const { env } = opts;
|
|
21
|
+
const dir = findRouter(env);
|
|
22
|
+
if (!dir)
|
|
23
|
+
die('phantom replay needs the router add-on to decide tiers again. Set PHANTOM_ROUTER_DIR to a built routers/phantom-1/router/ folder.', 'replay_no_router');
|
|
24
|
+
const replayId = randomBytes(4).toString('hex');
|
|
25
|
+
const pickers = new Map();
|
|
26
|
+
const accounts = accountsToday(env);
|
|
27
|
+
let scoreAuto;
|
|
28
|
+
try {
|
|
29
|
+
scoreAuto = loadRustRouterScore(dir);
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
die(`${loadFailure(dir, err)}, so phantom replay cannot decide tiers again.${unpackHint(dir)}`, 'replay_router_would_not_load');
|
|
33
|
+
}
|
|
34
|
+
const report = {
|
|
35
|
+
since: opts.since?.toISOString() ?? null,
|
|
36
|
+
traces: 0,
|
|
37
|
+
warm_up: 0,
|
|
38
|
+
skipped: 0,
|
|
39
|
+
from: null,
|
|
40
|
+
to: null,
|
|
41
|
+
settings: { sensitivity: opts.sensitivity, max_move_up_tokens: opts.maxMoveUpTokens },
|
|
42
|
+
recorded: { sensitivity: [], router_version: [] },
|
|
43
|
+
router_version: rustRouterVersion(dir),
|
|
44
|
+
self_check: { differ: 0, ids: [] },
|
|
45
|
+
frontier: { live: 0, as_recorded: 0, with_changes: 0 },
|
|
46
|
+
changed: [],
|
|
47
|
+
scores: [],
|
|
48
|
+
near_threshold: { within: NEAR, standard: 0, frontier: 0 },
|
|
49
|
+
};
|
|
50
|
+
let replaying = null;
|
|
51
|
+
const sideSaved = () => replaying?.decision.trial ?? null;
|
|
52
|
+
for await (const trace of readTraces(env, opts.since, () => report.skipped++)) {
|
|
53
|
+
replaying = trace;
|
|
54
|
+
let run = pickers.get(trace.run);
|
|
55
|
+
if (!run) {
|
|
56
|
+
const imageReaders = imageReadersFor({ tiers: trace.tiers, accounts }, env);
|
|
57
|
+
run = {
|
|
58
|
+
asRecorded: phantom1Picker({ env, warn: opts.warn, sensitivity: trace.sensitivity, imageReaders, coin: sideSaved }),
|
|
59
|
+
withChanges: phantom1Picker({ env, warn: opts.warn, sensitivity: opts.sensitivity ?? trace.sensitivity, maxMoveUpTokens: opts.maxMoveUpTokens, imageReaders, coin: sideSaved }),
|
|
60
|
+
};
|
|
61
|
+
pickers.set(trace.run, run);
|
|
62
|
+
}
|
|
63
|
+
const live = { tier: trace.decision.picked, reason: trace.decision.reason };
|
|
64
|
+
const asRecorded = await pickAgain(run.asRecorded, `${replayId}/recorded`, trace, live);
|
|
65
|
+
const withChanges = await pickAgain(run.withChanges, `${replayId}/changed`, trace, live);
|
|
66
|
+
if (opts.since && new Date(trace.at) < opts.since) {
|
|
67
|
+
report.warm_up++;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
report.traces++;
|
|
71
|
+
if (report.from === null || trace.at < report.from)
|
|
72
|
+
report.from = trace.at;
|
|
73
|
+
if (report.to === null || trace.at > report.to)
|
|
74
|
+
report.to = trace.at;
|
|
75
|
+
if (!report.recorded.sensitivity.includes(trace.sensitivity))
|
|
76
|
+
report.recorded.sensitivity.push(trace.sensitivity);
|
|
77
|
+
if (!report.recorded.router_version.includes(trace.router_version))
|
|
78
|
+
report.recorded.router_version.push(trace.router_version);
|
|
79
|
+
if (asRecorded.tier !== live.tier || asRecorded.reason !== live.reason) {
|
|
80
|
+
report.self_check.differ++;
|
|
81
|
+
report.self_check.ids.push(trace.id);
|
|
82
|
+
}
|
|
83
|
+
if (live.tier === 'frontier')
|
|
84
|
+
report.frontier.live++;
|
|
85
|
+
if (asRecorded.tier === 'frontier')
|
|
86
|
+
report.frontier.as_recorded++;
|
|
87
|
+
if (withChanges.tier === 'frontier')
|
|
88
|
+
report.frontier.with_changes++;
|
|
89
|
+
if (withChanges.tier !== asRecorded.tier) {
|
|
90
|
+
report.changed.push({ id: trace.id, at: trace.at, run: trace.run, conversation: trace.conversation, before: asRecorded, after: withChanges });
|
|
91
|
+
}
|
|
92
|
+
const messages = trace.request?.messages;
|
|
93
|
+
const score = scoreAuto && live.reason !== 'helper' ? (await scoreAuto(Array.isArray(messages) ? messages : [], 'openai_chat')).score : null;
|
|
94
|
+
const threshold = MOVE_UP_THRESHOLD[trace.sensitivity];
|
|
95
|
+
let near = null;
|
|
96
|
+
if (score !== null && live.tier === 'standard' && live.reason.startsWith('router:') && score < threshold && score >= threshold - NEAR)
|
|
97
|
+
near = 'under';
|
|
98
|
+
if (score !== null && live.tier === 'frontier' && live.reason === 'router:dimensions' && score >= threshold && score < threshold + NEAR)
|
|
99
|
+
near = 'over';
|
|
100
|
+
if (near === 'under')
|
|
101
|
+
report.near_threshold.standard++;
|
|
102
|
+
if (near === 'over')
|
|
103
|
+
report.near_threshold.frontier++;
|
|
104
|
+
report.scores.push({ id: trace.id, score, near });
|
|
105
|
+
}
|
|
106
|
+
return report;
|
|
107
|
+
}
|
|
108
|
+
async function pickAgain(picker, pass, trace, live) {
|
|
109
|
+
if (live.reason === 'helper')
|
|
110
|
+
return live;
|
|
111
|
+
const session = new Headers({ 'x-phantom-session': `${pass}/${trace.run}/${trace.conversation ?? trace.id}` });
|
|
112
|
+
const { tier, reason } = await picker(session, trace.request?.messages);
|
|
113
|
+
return { tier, reason };
|
|
114
|
+
}
|
|
115
|
+
export function replayText(r, env) {
|
|
116
|
+
if (!r.traces) {
|
|
117
|
+
return `No traces saved${r.since ? ` since ${r.since.slice(0, 10)}` : ''} in ${tracesFolder(env)}. phantom replay reads traces, which are off unless you run phantom config --traces on.`;
|
|
118
|
+
}
|
|
119
|
+
const share = (n) => `${n} of ${r.traces} (${Math.round((n / r.traces) * 100)}%)`;
|
|
120
|
+
const otherBuilds = r.recorded.router_version.filter((sha) => sha !== r.router_version);
|
|
121
|
+
const lines = [
|
|
122
|
+
`Replayed ${r.traces} traced request${r.traces === 1 ? '' : 's'}, from ${r.from} to ${r.to}, through this CLI's tier decision. No model was called.`,
|
|
123
|
+
...(r.warm_up ? [`${r.warm_up} earlier trace${r.warm_up === 1 ? '' : 's'} of the same runs went through first, uncounted, to set up their holds.`] : []),
|
|
124
|
+
...(r.skipped ? [`${r.skipped} line${r.skipped === 1 ? '' : 's'} in the trace files ${r.skipped === 1 ? 'was' : 'were'} cut off or not a whole trace, and ${r.skipped === 1 ? 'was' : 'were'} passed over.`] : []),
|
|
125
|
+
`Settings: sensitivity ${r.settings.sensitivity ?? `as recorded (${r.recorded.sensitivity.join(', ')})`}, move-up limit ${r.settings.max_move_up_tokens.toLocaleString('en-US')} tokens.`,
|
|
126
|
+
...(otherBuilds.length ? [`The router here is ${r.router_version ?? 'missing'}; some traces were recorded with ${otherBuilds.map((sha) => sha ?? 'none').join(', ')}, so their picks may differ.`] : []),
|
|
127
|
+
r.self_check.differ
|
|
128
|
+
? [
|
|
129
|
+
`Self-check: with the recorded settings, ${r.self_check.differ} replayed pick${r.self_check.differ === 1 ? '' : 's'} differ from the live one${r.self_check.differ === 1 ? '' : 's'} (${r.self_check.ids.slice(0, 5).join(', ')}${r.self_check.differ > 5 ? ', ...' : ''}), so the replay isn't exact for those.`,
|
|
130
|
+
'Likely causes: another router build or phantom version; earlier traces of the run missing (saved before traces were on, or deleted past the 2 GB cap), so its holds start empty;',
|
|
131
|
+
'or a task idle over an hour between requests, which the router forgets live and the replay does not.',
|
|
132
|
+
].join('\n')
|
|
133
|
+
: 'Self-check: with the recorded settings, every replayed pick matches the live one.',
|
|
134
|
+
`Frontier: ${share(r.frontier.live)} live, ${share(r.frontier.as_recorded)} replayed as recorded, ${share(r.frontier.with_changes)} with these settings.`,
|
|
135
|
+
r.scores.some((s) => s.score !== null)
|
|
136
|
+
? `The router's own score, each request alone: ${r.near_threshold.standard} Standard pick${r.near_threshold.standard === 1 ? '' : 's'} scored within ${r.near_threshold.within} under the move-up threshold, and ${r.near_threshold.frontier} Frontier pick${r.near_threshold.frontier === 1 ? '' : 's'} within ${r.near_threshold.within} over it. --json gives every score.`
|
|
137
|
+
: "The router gave no scores: every request was a helper's or an override.",
|
|
138
|
+
r.changed.length ? `${r.changed.length} request${r.changed.length === 1 ? '' : 's'} change tier:` : 'No request changes tier.',
|
|
139
|
+
...r.changed.slice(0, 30).map((c) => ` ${c.at} ${c.id} ${c.conversation ?? '-'} ${c.before.tier} (${c.before.reason}) -> ${c.after.tier} (${c.after.reason})`),
|
|
140
|
+
...(r.changed.length > 30 ? [` and ${r.changed.length - 30} more; --json lists them all.`] : []),
|
|
141
|
+
];
|
|
142
|
+
return lines.join('\n');
|
|
143
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Env } from '../core/state.mts';
|
|
2
|
+
import { type Tier } from './config.mts';
|
|
3
|
+
import { type Outcome, type RequestRecord } from './request-log.mts';
|
|
4
|
+
export type Report = {
|
|
5
|
+
since: string | null;
|
|
6
|
+
requests: number;
|
|
7
|
+
from: string | null;
|
|
8
|
+
to: string | null;
|
|
9
|
+
tiers: Record<Tier, number>;
|
|
10
|
+
models: {
|
|
11
|
+
account: string;
|
|
12
|
+
model: string;
|
|
13
|
+
requests: number;
|
|
14
|
+
tokens_in: number;
|
|
15
|
+
tokens_out: number;
|
|
16
|
+
total_ms_p50: number | null;
|
|
17
|
+
total_ms_p95: number | null;
|
|
18
|
+
first_byte_ms_p50: number | null;
|
|
19
|
+
}[];
|
|
20
|
+
reasons: {
|
|
21
|
+
reason: string;
|
|
22
|
+
requests: number;
|
|
23
|
+
}[];
|
|
24
|
+
conversations: {
|
|
25
|
+
count: number;
|
|
26
|
+
started_on_frontier: number;
|
|
27
|
+
moved_up: number;
|
|
28
|
+
came_back_down: number;
|
|
29
|
+
};
|
|
30
|
+
fallbacks: {
|
|
31
|
+
account: string;
|
|
32
|
+
requests: number;
|
|
33
|
+
}[];
|
|
34
|
+
failures: {
|
|
35
|
+
outcome: Outcome;
|
|
36
|
+
status: number | null;
|
|
37
|
+
requests: number;
|
|
38
|
+
}[];
|
|
39
|
+
};
|
|
40
|
+
export declare function readRequests(env: Env): RequestRecord[];
|
|
41
|
+
export declare function parseSince(text: string, now: Date): Date;
|
|
42
|
+
export declare function summarize(all: RequestRecord[], since: Date | null): Report;
|
|
43
|
+
export declare function reportText(r: Report): string;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// docs: `phantom report`: reads requests.jsonl and requests.1.jsonl and sums up what phantom-1 on this computer did, optionally since a time: requests by tier, by account and model with tokens and timings, reasons, tasks that ran on Frontier from the start, moved up to it partway or came back down, fallbacks and failures
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { die } from "../core/errors.mjs";
|
|
4
|
+
import { TIERS } from "./config.mjs";
|
|
5
|
+
import { requestLogPaths, withCurrentNames } from "./request-log.mjs";
|
|
6
|
+
export function readRequests(env) {
|
|
7
|
+
const { previous, current } = requestLogPaths(env);
|
|
8
|
+
return [previous, current]
|
|
9
|
+
.filter((file) => existsSync(file))
|
|
10
|
+
.flatMap((file) => readFileSync(file, 'utf8').split('\n'))
|
|
11
|
+
.flatMap((line) => {
|
|
12
|
+
try {
|
|
13
|
+
const record = withCurrentNames(JSON.parse(line));
|
|
14
|
+
return isRecord(record) ? [record] : [];
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return [];
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
function isRecord(value) {
|
|
22
|
+
const r = value;
|
|
23
|
+
return (typeof r?.at === 'string' &&
|
|
24
|
+
!Number.isNaN(Date.parse(r.at)) &&
|
|
25
|
+
TIERS.includes(r.picked) &&
|
|
26
|
+
[r.reason, r.account, r.model, r.outcome].every((field) => typeof field === 'string') &&
|
|
27
|
+
typeof r.ms?.total === 'number');
|
|
28
|
+
}
|
|
29
|
+
export function parseSince(text, now) {
|
|
30
|
+
const back = /^(\d+)([hd])$/.exec(text);
|
|
31
|
+
if (back) {
|
|
32
|
+
const date = new Date(now.getTime() - Number(back[1]) * (back[2] === 'h' ? 3_600_000 : 86_400_000));
|
|
33
|
+
if (Number.isNaN(date.getTime()))
|
|
34
|
+
die(`--since ${text} goes back further than a date can. Try a smaller number, such as 30d, or a date such as 2026-11-28.`, 'local_report_since');
|
|
35
|
+
return date;
|
|
36
|
+
}
|
|
37
|
+
const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
|
|
38
|
+
if (day) {
|
|
39
|
+
const date = new Date(`${text}T00:00:00.000Z`);
|
|
40
|
+
// 2026-02-31 parses as 3 March, so a date must come back as it was typed.
|
|
41
|
+
if (!Number.isNaN(date.getTime()) && date.toISOString().startsWith(text))
|
|
42
|
+
return date;
|
|
43
|
+
}
|
|
44
|
+
die('--since takes hours or days back, such as 1h, 1d or 7d, or a date such as 2026-11-28.', 'local_report_since');
|
|
45
|
+
}
|
|
46
|
+
export function summarize(all, since) {
|
|
47
|
+
const records = all.filter((r) => !since || new Date(r.at) >= since).sort((a, b) => a.at.localeCompare(b.at));
|
|
48
|
+
const tiers = { standard: 0, frontier: 0 };
|
|
49
|
+
for (const r of records)
|
|
50
|
+
tiers[r.picked]++;
|
|
51
|
+
const models = [...groupBy(records, (r) => `${r.account}\0${r.model}`).values()].map((group) => {
|
|
52
|
+
const totals = group.map((r) => r.ms.total);
|
|
53
|
+
const firstBytes = group.flatMap((r) => (r.ms.first_byte === null ? [] : [r.ms.first_byte]));
|
|
54
|
+
return {
|
|
55
|
+
account: group[0].account,
|
|
56
|
+
model: group[0].model,
|
|
57
|
+
requests: group.length,
|
|
58
|
+
tokens_in: sum(group.map((r) => r.tokens?.in ?? 0)),
|
|
59
|
+
tokens_out: sum(group.map((r) => r.tokens?.out ?? 0)),
|
|
60
|
+
total_ms_p50: percentile(totals, 50),
|
|
61
|
+
total_ms_p95: percentile(totals, 95),
|
|
62
|
+
first_byte_ms_p50: percentile(firstBytes, 50),
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
const conversations = { count: 0, started_on_frontier: 0, moved_up: 0, came_back_down: 0 };
|
|
66
|
+
for (const group of groupBy(records.filter((r) => r.conversation !== null), (r) => r.conversation).values()) {
|
|
67
|
+
let sawStandard = false;
|
|
68
|
+
let movedUp = false;
|
|
69
|
+
let cameBack = false;
|
|
70
|
+
for (const r of group) {
|
|
71
|
+
if (r.picked === 'frontier' && sawStandard)
|
|
72
|
+
movedUp = true;
|
|
73
|
+
if (r.picked === 'standard' && movedUp)
|
|
74
|
+
cameBack = true;
|
|
75
|
+
if (r.picked === 'standard')
|
|
76
|
+
sawStandard = true;
|
|
77
|
+
}
|
|
78
|
+
conversations.count++;
|
|
79
|
+
if (group[0].picked === 'frontier')
|
|
80
|
+
conversations.started_on_frontier++;
|
|
81
|
+
if (movedUp)
|
|
82
|
+
conversations.moved_up++;
|
|
83
|
+
if (cameBack)
|
|
84
|
+
conversations.came_back_down++;
|
|
85
|
+
}
|
|
86
|
+
const failed = records.filter((r) => r.outcome !== 'ok');
|
|
87
|
+
return {
|
|
88
|
+
since: since?.toISOString() ?? null,
|
|
89
|
+
requests: records.length,
|
|
90
|
+
from: records[0]?.at ?? null,
|
|
91
|
+
to: records.at(-1)?.at ?? null,
|
|
92
|
+
tiers,
|
|
93
|
+
models: mostFirst(models, (m) => `${m.account} ${m.model}`),
|
|
94
|
+
reasons: mostFirst([...groupBy(records, (r) => r.reason)].map(([reason, group]) => ({ reason, requests: group.length })), (x) => x.reason),
|
|
95
|
+
conversations,
|
|
96
|
+
fallbacks: mostFirst([...groupBy(records.filter((r) => r.fallback), (r) => r.account)].map(([account, group]) => ({ account, requests: group.length })), (f) => f.account),
|
|
97
|
+
failures: mostFirst([...groupBy(failed, (r) => `${r.outcome} ${r.status}`).values()].map((group) => ({ outcome: group[0].outcome, status: group[0].status, requests: group.length })), (f) => `${f.outcome} ${f.status}`),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function reportText(r) {
|
|
101
|
+
if (!r.requests)
|
|
102
|
+
return r.since ? `No requests saved since ${readableUtcTime(r.since)}.` : 'No requests saved yet. phantom-1 saves one line per request while it runs (phantom pi).';
|
|
103
|
+
const ms = (n) => (n === null ? 'none' : `${n.toLocaleString('en-US')} ms`);
|
|
104
|
+
const requests = (n) => `${n} ${n === 1 ? 'request' : 'requests'}`;
|
|
105
|
+
return [
|
|
106
|
+
`${requests(r.requests)}, from ${readableUtcTime(r.from)} to ${readableUtcTime(r.to)}${r.since ? ` (since ${readableUtcTime(r.since)})` : ''}.`,
|
|
107
|
+
'',
|
|
108
|
+
'Tiers',
|
|
109
|
+
` Standard ${requests(r.tiers.standard)}`,
|
|
110
|
+
` Frontier ${requests(r.tiers.frontier)}`,
|
|
111
|
+
'',
|
|
112
|
+
'By account and model',
|
|
113
|
+
...r.models.flatMap((m) => [
|
|
114
|
+
` ${m.model} on ${m.account}: ${requests(m.requests)}, ${m.tokens_in.toLocaleString('en-US')} tokens in, ${m.tokens_out.toLocaleString('en-US')} out`,
|
|
115
|
+
` total time: median ${ms(m.total_ms_p50)}, 95th percentile ${ms(m.total_ms_p95)}; first byte: median ${ms(m.first_byte_ms_p50)}`,
|
|
116
|
+
]),
|
|
117
|
+
'',
|
|
118
|
+
'Reasons',
|
|
119
|
+
...r.reasons.map((x) => ` ${x.reason}: ${x.requests}`),
|
|
120
|
+
'',
|
|
121
|
+
`Tasks (one per message you typed): ${r.conversations.count}. ${r.conversations.started_on_frontier} ran on Frontier from the start, ${r.conversations.moved_up} moved up partway, and ${r.conversations.came_back_down} of the ones that moved up came back down to Standard.`,
|
|
122
|
+
`Fallbacks: ${r.fallbacks.length ? r.fallbacks.map((f) => `${f.requests} answered by ${f.account}`).join(', ') : 'none'}.`,
|
|
123
|
+
`Failures: ${r.failures.length ? r.failures.map((f) => `${f.requests} ${f.outcome}${f.status === null ? '' : ` (${f.status})`}`).join(', ') : 'none'}.`,
|
|
124
|
+
].join('\n');
|
|
125
|
+
}
|
|
126
|
+
const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
127
|
+
function readableUtcTime(iso) {
|
|
128
|
+
const month = MONTH_NAMES[Number(iso.slice(5, 7)) - 1];
|
|
129
|
+
const day = Number(iso.slice(8, 10));
|
|
130
|
+
return `${month} ${day}, ${iso.slice(0, 4)} ${iso.slice(11, 16)} UTC`;
|
|
131
|
+
}
|
|
132
|
+
function groupBy(items, key) {
|
|
133
|
+
const groups = new Map();
|
|
134
|
+
for (const item of items) {
|
|
135
|
+
const k = key(item);
|
|
136
|
+
const group = groups.get(k);
|
|
137
|
+
if (group)
|
|
138
|
+
group.push(item);
|
|
139
|
+
else
|
|
140
|
+
groups.set(k, [item]);
|
|
141
|
+
}
|
|
142
|
+
return groups;
|
|
143
|
+
}
|
|
144
|
+
function mostFirst(rows, name) {
|
|
145
|
+
return [...rows].sort((a, b) => b.requests - a.requests || name(a).localeCompare(name(b)));
|
|
146
|
+
}
|
|
147
|
+
const sum = (values) => values.reduce((a, b) => a + b, 0);
|
|
148
|
+
function percentile(values, p) {
|
|
149
|
+
if (!values.length)
|
|
150
|
+
return null;
|
|
151
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
152
|
+
return sorted[Math.ceil((p / 100) * sorted.length) - 1];
|
|
153
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type Env } from '../core/state.mts';
|
|
2
|
+
import type { Sensitivity, Tier } from './config.mts';
|
|
3
|
+
import type { Signals } from './decide.mts';
|
|
4
|
+
import type { RouterAnswer } from './rust-router.mts';
|
|
5
|
+
export type Outcome = 'ok' | 'upstream-error' | 'stream-failed' | 'client-closed' | 'unreachable' | 'not-signed-in';
|
|
6
|
+
export type RequestRecord = {
|
|
7
|
+
v: 2;
|
|
8
|
+
at: string;
|
|
9
|
+
id: string;
|
|
10
|
+
run: string;
|
|
11
|
+
phantom: string;
|
|
12
|
+
router_version: string | null;
|
|
13
|
+
sensitivity: Sensitivity;
|
|
14
|
+
conversation: string | null;
|
|
15
|
+
messages: number;
|
|
16
|
+
stream: boolean;
|
|
17
|
+
picked: Tier;
|
|
18
|
+
reason: string;
|
|
19
|
+
trial?: Tier;
|
|
20
|
+
account: string;
|
|
21
|
+
model: string;
|
|
22
|
+
fallback: boolean;
|
|
23
|
+
because?: string;
|
|
24
|
+
code?: string;
|
|
25
|
+
status: number | null;
|
|
26
|
+
outcome: Outcome;
|
|
27
|
+
ms: {
|
|
28
|
+
decide: number;
|
|
29
|
+
first_byte: number | null;
|
|
30
|
+
total: number;
|
|
31
|
+
};
|
|
32
|
+
tokens: {
|
|
33
|
+
in: number;
|
|
34
|
+
out: number;
|
|
35
|
+
} | null;
|
|
36
|
+
signals: Signals;
|
|
37
|
+
router: RouterAnswer | null;
|
|
38
|
+
};
|
|
39
|
+
export declare function currentReason(reason: string): string;
|
|
40
|
+
export declare function withCurrentNames(line: unknown): unknown;
|
|
41
|
+
export declare function requestLogPaths(env: Env): {
|
|
42
|
+
current: string;
|
|
43
|
+
previous: string;
|
|
44
|
+
};
|
|
45
|
+
export type RequestLog = {
|
|
46
|
+
write: (record: RequestRecord) => void;
|
|
47
|
+
idle: () => Promise<void>;
|
|
48
|
+
};
|
|
49
|
+
export declare function requestLog(opts: {
|
|
50
|
+
env: Env;
|
|
51
|
+
warn: (line: string) => void;
|
|
52
|
+
capBytes?: number;
|
|
53
|
+
}): RequestLog;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// docs: The request log of phantom-1 on this computer: one JSON line per finished request in <state>/local/requests.jsonl (mode 600), with the run, versions and settings, the tiers, what the router said, the trial's side (when the task is in the trial), account, model, outcome, why a fallback was tried, the plan's error code, three timings, token counts and the messages' counts (signals), never message text, keys or headers. Past 10 MB the file moves to requests.1.jsonl, replacing the older one
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import { appendFile, readFile, rename, stat, unlink } from 'node:fs/promises';
|
|
5
|
+
import { makePrivateFolder, stateDir } from "../core/state.mjs";
|
|
6
|
+
export function currentReason(reason) {
|
|
7
|
+
return reason.startsWith('switchyard:') ? `router:${reason.slice('switchyard:'.length)}` : reason;
|
|
8
|
+
}
|
|
9
|
+
export function withCurrentNames(line) {
|
|
10
|
+
if (line === null || typeof line !== 'object' || Array.isArray(line))
|
|
11
|
+
return line;
|
|
12
|
+
const { switchyard_sha, switchyard, ...rest } = line;
|
|
13
|
+
return {
|
|
14
|
+
...rest,
|
|
15
|
+
...(switchyard_sha !== undefined && !('router_version' in rest) && { router_version: switchyard_sha }),
|
|
16
|
+
...(switchyard !== undefined && !('router' in rest) && { router: switchyard }),
|
|
17
|
+
...(typeof rest.reason === 'string' && { reason: currentReason(rest.reason) }),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function requestLogPaths(env) {
|
|
21
|
+
const folder = path.join(stateDir(env), 'local');
|
|
22
|
+
return { current: path.join(folder, 'requests.jsonl'), previous: path.join(folder, 'requests.1.jsonl') };
|
|
23
|
+
}
|
|
24
|
+
const LOG_CAP_BYTES = 10 * 1024 * 1024;
|
|
25
|
+
export function requestLog(opts) {
|
|
26
|
+
const { current, previous } = requestLogPaths(opts.env);
|
|
27
|
+
const cap = opts.capBytes ?? LOG_CAP_BYTES;
|
|
28
|
+
let queue = Promise.resolve();
|
|
29
|
+
let warned = false;
|
|
30
|
+
let folderMade = false;
|
|
31
|
+
async function append(line) {
|
|
32
|
+
if (!folderMade)
|
|
33
|
+
makePrivateFolder(opts.env, path.dirname(current));
|
|
34
|
+
folderMade = true;
|
|
35
|
+
if ((await sizeOf(current)) >= cap)
|
|
36
|
+
await moveAside();
|
|
37
|
+
await appendFile(current, line, { mode: 0o600 });
|
|
38
|
+
}
|
|
39
|
+
async function moveAside() {
|
|
40
|
+
const taken = `${current}.${process.pid}-${randomBytes(4).toString('hex')}`;
|
|
41
|
+
try {
|
|
42
|
+
await rename(current, taken);
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
if (err.code === 'ENOENT')
|
|
46
|
+
return;
|
|
47
|
+
throw err;
|
|
48
|
+
}
|
|
49
|
+
if ((await sizeOf(taken)) >= cap)
|
|
50
|
+
return rename(taken, previous);
|
|
51
|
+
await appendFile(current, await readFile(taken), { mode: 0o600 });
|
|
52
|
+
await unlink(taken);
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
write(record) {
|
|
56
|
+
const line = JSON.stringify(record) + '\n';
|
|
57
|
+
queue = queue.then(() => append(line)).catch((err) => {
|
|
58
|
+
if (warned)
|
|
59
|
+
return;
|
|
60
|
+
warned = true;
|
|
61
|
+
opts.warn(`phantom-1 could not save the request log at ${current} (${err.code ?? 'error'}). Requests still go through.`);
|
|
62
|
+
});
|
|
63
|
+
},
|
|
64
|
+
idle: () => queue,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
async function sizeOf(file) {
|
|
68
|
+
return stat(file).then((s) => s.size, () => 0);
|
|
69
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// docs: How phantom-1 on this computer waits when an account asks it to: the answer's `Retry-After` (seconds or a date) as milliseconds, the longest wait it sits through, and a pause that ends early when the agent hangs up
|
|
2
|
+
export const MAX_WAIT_MS = 60_000;
|
|
3
|
+
/** An HTTP date as the header's rules allow it (RFC 1123), the only date shape the wait trusts. */
|
|
4
|
+
const HTTP_DATE = /^[A-Za-z]{3}, \d{1,2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/;
|
|
5
|
+
export function retryAfterMs(header, now = Date.now()) {
|
|
6
|
+
if (!header)
|
|
7
|
+
return null;
|
|
8
|
+
const text = header.trim();
|
|
9
|
+
if (/^\d+$/.test(text))
|
|
10
|
+
return Number(text) * 1000;
|
|
11
|
+
if (!HTTP_DATE.test(text))
|
|
12
|
+
return null;
|
|
13
|
+
const at = Date.parse(text);
|
|
14
|
+
return Number.isNaN(at) ? null : at - now;
|
|
15
|
+
}
|
|
16
|
+
export async function pause(ms, signal) {
|
|
17
|
+
if (signal.aborted)
|
|
18
|
+
return;
|
|
19
|
+
await new Promise((resolve) => {
|
|
20
|
+
const done = () => {
|
|
21
|
+
clearTimeout(timer);
|
|
22
|
+
signal.removeEventListener('abort', done);
|
|
23
|
+
resolve();
|
|
24
|
+
};
|
|
25
|
+
const timer = setTimeout(done, ms);
|
|
26
|
+
signal.addEventListener('abort', done, { once: true });
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Env } from '../core/state.mts';
|
|
2
|
+
import type { Sensitivity, Tier } from './config.mts';
|
|
3
|
+
export type RouterSignals = {
|
|
4
|
+
severity: number;
|
|
5
|
+
spinning: number;
|
|
6
|
+
exploring: number;
|
|
7
|
+
productionIntensity: number;
|
|
8
|
+
};
|
|
9
|
+
export type RouterAnswer = {
|
|
10
|
+
tier: Tier;
|
|
11
|
+
source: string;
|
|
12
|
+
confidence?: number;
|
|
13
|
+
threshold?: number;
|
|
14
|
+
signals?: RouterSignals;
|
|
15
|
+
override?: string;
|
|
16
|
+
};
|
|
17
|
+
export type SelectAuto = (messages: unknown[], format: 'openai_chat', sessionId: string | undefined, sensitivity: Sensitivity) => Promise<RouterAnswer>;
|
|
18
|
+
export declare function rustRouterDir(env: Env, here?: string): string | null;
|
|
19
|
+
export type ScoreAuto = (messages: unknown[], format: 'openai_chat') => Promise<{
|
|
20
|
+
score: number | null;
|
|
21
|
+
source: string;
|
|
22
|
+
}>;
|
|
23
|
+
export type RouterAddOn = {
|
|
24
|
+
selectAuto: SelectAuto;
|
|
25
|
+
scoreAuto?: ScoreAuto;
|
|
26
|
+
};
|
|
27
|
+
export type EmbeddedRouter = {
|
|
28
|
+
load: () => RouterAddOn;
|
|
29
|
+
version: string | null;
|
|
30
|
+
};
|
|
31
|
+
export type RouterSource = string | EmbeddedRouter;
|
|
32
|
+
export declare function embedRouter(router: EmbeddedRouter | null): void;
|
|
33
|
+
export declare function findRouter(env: Env, here?: string): RouterSource | null;
|
|
34
|
+
export declare function routerLocation(source: RouterSource | null): string | null;
|
|
35
|
+
export declare function loadFailure(source: RouterSource | null, err: unknown): string;
|
|
36
|
+
export declare function unpackHint(source: RouterSource | null): string;
|
|
37
|
+
export declare function loadRustRouter(source: RouterSource): SelectAuto;
|
|
38
|
+
export declare function loadRustRouterScore(source: RouterSource): ScoreAuto | null;
|
|
39
|
+
export declare function rustRouterVersion(source: RouterSource | null): string | null;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// docs: Finds and loads Phantom's router (the Rust add-on in routers/phantom-1/router) for phantom-1 on this computer, only when the first request needs it: from PHANTOM_ROUTER_DIR, else the repo checkout this CLI runs from, and reads which build of the router it is. The published CLI ships without it, and then phantom-1 answers Frontier as it does on Phantom's server
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
export function rustRouterDir(env, here = path.dirname(fileURLToPath(import.meta.url))) {
|
|
7
|
+
const candidates = [env.PHANTOM_ROUTER_DIR, path.resolve(here, '../../../routers/phantom-1/router')];
|
|
8
|
+
return candidates.find((dir) => Boolean(dir) && existsSync(path.join(dir, 'dist', 'phantom-router.node'))) ?? null;
|
|
9
|
+
}
|
|
10
|
+
let embeddedRouter = null;
|
|
11
|
+
export function embedRouter(router) {
|
|
12
|
+
embeddedRouter = router;
|
|
13
|
+
}
|
|
14
|
+
export function findRouter(env, here) {
|
|
15
|
+
return embeddedRouter ?? rustRouterDir(env, here);
|
|
16
|
+
}
|
|
17
|
+
export function routerLocation(source) {
|
|
18
|
+
if (source === null)
|
|
19
|
+
return null;
|
|
20
|
+
return typeof source === 'string' ? source : 'embedded';
|
|
21
|
+
}
|
|
22
|
+
export function loadFailure(source, err) {
|
|
23
|
+
return `The router at ${routerLocation(source)} would not load (${err instanceof Error ? err.name : 'Error'})`;
|
|
24
|
+
}
|
|
25
|
+
export function unpackHint(source) {
|
|
26
|
+
return typeof source === 'object' && source !== null ? ' phantom unpacks its router into TMPDIR: set TMPDIR to a folder you own that allows running programs.' : '';
|
|
27
|
+
}
|
|
28
|
+
export function loadRustRouter(source) {
|
|
29
|
+
return addOn(source).selectAuto;
|
|
30
|
+
}
|
|
31
|
+
export function loadRustRouterScore(source) {
|
|
32
|
+
return addOn(source).scoreAuto ?? null;
|
|
33
|
+
}
|
|
34
|
+
function addOn(source) {
|
|
35
|
+
if (typeof source !== 'string')
|
|
36
|
+
return source.load();
|
|
37
|
+
const dir = source;
|
|
38
|
+
const load = createRequire(path.join(dir, 'package.json'));
|
|
39
|
+
return load(path.join(dir, 'index.cjs'));
|
|
40
|
+
}
|
|
41
|
+
export function rustRouterVersion(source) {
|
|
42
|
+
if (!source)
|
|
43
|
+
return null;
|
|
44
|
+
if (typeof source !== 'string')
|
|
45
|
+
return source.version;
|
|
46
|
+
const dir = source;
|
|
47
|
+
try {
|
|
48
|
+
const version = JSON.parse(readFileSync(path.join(dir, 'dist', 'source.json'), 'utf8')).version;
|
|
49
|
+
return typeof version === 'string' ? version : null;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Session } from '../chatgpt/session.mts';
|
|
2
|
+
import type { LocalConfig, Target } from './config.mts';
|
|
3
|
+
import { type Picker, type ReadsImages } from './decide.mts';
|
|
4
|
+
import type { RequestRecord } from './request-log.mts';
|
|
5
|
+
import type { TraceInput } from './traces.mts';
|
|
6
|
+
export type LocalServer = {
|
|
7
|
+
url: string;
|
|
8
|
+
close(): Promise<void>;
|
|
9
|
+
};
|
|
10
|
+
export type LocalServerOptions = {
|
|
11
|
+
config: LocalConfig;
|
|
12
|
+
keys: Record<string, string>;
|
|
13
|
+
picker: Picker;
|
|
14
|
+
port: number;
|
|
15
|
+
log: (line: string) => void;
|
|
16
|
+
record?: (record: RequestRecord) => void;
|
|
17
|
+
warn: (line: string) => void;
|
|
18
|
+
takeSaveProblems?: () => string[];
|
|
19
|
+
targetReadsImages?: (target: Target) => Promise<ReadsImages>;
|
|
20
|
+
chatgpt?: () => Promise<Session>;
|
|
21
|
+
token?: string;
|
|
22
|
+
rustRouterVersion?: string | null;
|
|
23
|
+
trace?: (input: TraceInput) => void;
|
|
24
|
+
wait?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
25
|
+
};
|
|
26
|
+
export declare const LOCAL_MODEL = "phantom-1";
|
|
27
|
+
export declare function startLocalServer(opts: LocalServerOptions): Promise<LocalServer>;
|