@phantomcodes/cli 1.6.2 → 1.7.0

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 (139) hide show
  1. package/README.md +138 -117
  2. package/bin/phantom.mjs +37 -2
  3. package/dist/agents/command.d.mts +8 -27
  4. package/dist/agents/command.mjs +323 -59
  5. package/dist/agents/login.d.mts +3 -0
  6. package/dist/agents/login.mjs +97 -0
  7. package/dist/agents/opencode-check.d.mts +15 -0
  8. package/dist/agents/opencode-check.mjs +193 -0
  9. package/dist/agents/phantom-key.d.mts +7 -0
  10. package/dist/agents/phantom-key.mjs +40 -0
  11. package/dist/agents/proxy.d.mts +26 -28
  12. package/dist/agents/proxy.mjs +225 -33
  13. package/dist/chatgpt/command.d.mts +2 -0
  14. package/dist/chatgpt/command.mjs +119 -0
  15. package/dist/chatgpt/session.d.mts +87 -0
  16. package/dist/chatgpt/session.mjs +253 -0
  17. package/dist/cli/accounts.d.mts +21 -0
  18. package/dist/cli/accounts.mjs +96 -0
  19. package/dist/cli/app.d.mts +4 -24
  20. package/dist/cli/app.mjs +224 -139
  21. package/dist/cli/commands.d.mts +1 -16
  22. package/dist/cli/commands.mjs +144 -239
  23. package/dist/cli/help.d.mts +0 -19
  24. package/dist/cli/help.mjs +30 -55
  25. package/dist/cli/run.mjs +35 -79
  26. package/dist/cli/start.d.mts +2 -31
  27. package/dist/cli/start.mjs +13 -116
  28. package/dist/core/brand.d.mts +0 -7
  29. package/dist/core/brand.mjs +0 -8
  30. package/dist/core/errors.d.mts +0 -16
  31. package/dist/core/errors.mjs +0 -16
  32. package/dist/core/helpers.d.mts +0 -46
  33. package/dist/core/helpers.mjs +1 -64
  34. package/dist/core/node-trust.d.mts +0 -5
  35. package/dist/core/node-trust.mjs +0 -6
  36. package/dist/core/pick.d.mts +7 -55
  37. package/dist/core/pick.mjs +49 -106
  38. package/dist/core/request.d.mts +0 -46
  39. package/dist/core/request.mjs +1 -60
  40. package/dist/core/secrets.d.mts +0 -4
  41. package/dist/core/secrets.mjs +0 -10
  42. package/dist/core/state.d.mts +3 -1
  43. package/dist/core/state.mjs +147 -4
  44. package/dist/core/style.d.mts +0 -27
  45. package/dist/core/style.mjs +0 -20
  46. package/dist/core/version.d.mts +1 -2
  47. package/dist/core/version.mjs +1 -2
  48. package/dist/local/accounts.d.mts +25 -0
  49. package/dist/local/accounts.mjs +40 -0
  50. package/dist/local/agent-headers.d.mts +7 -0
  51. package/dist/local/agent-headers.mjs +44 -0
  52. package/dist/local/chatgpt-plan.d.mts +147 -0
  53. package/dist/local/chatgpt-plan.mjs +384 -0
  54. package/dist/local/command.d.mts +24 -0
  55. package/dist/local/command.mjs +211 -0
  56. package/dist/local/config.d.mts +49 -0
  57. package/dist/local/config.mjs +168 -0
  58. package/dist/local/decide.d.mts +37 -0
  59. package/dist/local/decide.mjs +201 -0
  60. package/dist/local/failure-signs.d.mts +4 -0
  61. package/dist/local/failure-signs.mjs +99 -0
  62. package/dist/local/keys.d.mts +32 -0
  63. package/dist/local/keys.mjs +239 -0
  64. package/dist/local/models.d.mts +53 -0
  65. package/dist/local/models.mjs +117 -0
  66. package/dist/local/replay.d.mts +59 -0
  67. package/dist/local/replay.mjs +143 -0
  68. package/dist/local/report.d.mts +43 -0
  69. package/dist/local/report.mjs +153 -0
  70. package/dist/local/request-log.d.mts +53 -0
  71. package/dist/local/request-log.mjs +69 -0
  72. package/dist/local/retry-after.d.mts +3 -0
  73. package/dist/local/retry-after.mjs +28 -0
  74. package/dist/local/rust-router.d.mts +39 -0
  75. package/dist/local/rust-router.mjs +54 -0
  76. package/dist/local/server.d.mts +27 -0
  77. package/dist/local/server.mjs +449 -0
  78. package/dist/local/status-line.d.mts +17 -0
  79. package/dist/local/status-line.mjs +81 -0
  80. package/dist/local/tiers.d.mts +3 -0
  81. package/dist/local/tiers.mjs +137 -0
  82. package/dist/local/traces.d.mts +69 -0
  83. package/dist/local/traces.mjs +341 -0
  84. package/dist/phantom.d.mts +0 -37
  85. package/dist/phantom.mjs +0 -31
  86. package/package.json +15 -9
  87. package/skills/phantom-ai/SKILL.md +28 -97
  88. package/dist/cli/screens.d.mts +0 -177
  89. package/dist/cli/screens.mjs +0 -398
  90. package/dist/core/free.d.mts +0 -13
  91. package/dist/core/free.mjs +0 -14
  92. package/dist/core/motion.d.mts +0 -47
  93. package/dist/core/motion.mjs +0 -156
  94. package/dist/core/shapes.d.mts +0 -13
  95. package/dist/core/shapes.mjs +0 -1
  96. package/dist/keys/command.d.mts +0 -16
  97. package/dist/keys/command.mjs +0 -143
  98. package/dist/keys/saved.d.mts +0 -96
  99. package/dist/keys/saved.mjs +0 -169
  100. package/dist/models/choice.d.mts +0 -7
  101. package/dist/models/choice.mjs +0 -27
  102. package/dist/models/command.d.mts +0 -8
  103. package/dist/models/command.mjs +0 -66
  104. package/dist/models/list.d.mts +0 -39
  105. package/dist/models/list.mjs +0 -39
  106. package/dist/receipts/command.d.mts +0 -7
  107. package/dist/receipts/command.mjs +0 -41
  108. package/dist/receipts/receipts.d.mts +0 -76
  109. package/dist/receipts/receipts.mjs +0 -114
  110. package/dist/setup/agents.d.mts +0 -149
  111. package/dist/setup/agents.mjs +0 -886
  112. package/dist/setup/apply.d.mts +0 -85
  113. package/dist/setup/apply.mjs +0 -301
  114. package/dist/setup/command.d.mts +0 -12
  115. package/dist/setup/command.mjs +0 -307
  116. package/dist/setup/editors.d.mts +0 -108
  117. package/dist/setup/editors.mjs +0 -500
  118. package/dist/setup/legacy.d.mts +0 -13
  119. package/dist/setup/legacy.mjs +0 -36
  120. package/dist/setup/plan.d.mts +0 -104
  121. package/dist/setup/plan.mjs +0 -132
  122. package/dist/setup/screen.d.mts +0 -30
  123. package/dist/setup/screen.mjs +0 -260
  124. package/dist/setup/shared.d.mts +0 -141
  125. package/dist/setup/shared.mjs +0 -88
  126. package/dist/setup/was.d.mts +0 -42
  127. package/dist/setup/was.mjs +0 -91
  128. package/dist/spend/command.d.mts +0 -5
  129. package/dist/spend/command.mjs +0 -235
  130. package/dist/spend/lineup.d.mts +0 -61
  131. package/dist/spend/lineup.mjs +0 -39
  132. package/dist/spend/reason.d.mts +0 -5
  133. package/dist/spend/reason.mjs +0 -60
  134. package/dist/spend/report.d.mts +0 -105
  135. package/dist/spend/report.mjs +0 -68
  136. package/dist/spend/routing.d.mts +0 -74
  137. package/dist/spend/routing.mjs +0 -57
  138. package/dist/workspace/command.d.mts +0 -59
  139. package/dist/workspace/command.mjs +0 -871
@@ -0,0 +1,449 @@
1
+ // docs: The server phantom-1 on this computer runs on 127.0.0.1: OpenAI Chat Completions in, phantom-1 picks a tier, and the request goes straight to the account local.json names for it: a key account gets the body with only `model` changed, the ChatGPT plan gets it translated to the Responses API on the `phantom config chatgpt login` token. Streams the answer back as it arrives, tries a tier's fallback once on 429 or 5xx (and when the plan has no usable sign-in, refuses the request, or stops partway through an answer the agent asked for whole), waits out the shortest `Retry-After` its failed answers asked for, up to a minute, and then tries the tier once more, and for each request prints one line and hands a record with its timings to the request log, with no message text, key or header. Each answer's headers also carry the line pi's footer shows and, when something went wrong, a warning (status-line.mts). When traces are on, it also hands over the agent's body and the text the agent received, for traces.mts. Given an agent run's token, it serves only requests that carry it
2
+ import { randomBytes } from 'node:crypto';
3
+ import { createServer } from 'node:http';
4
+ import { applyEdits, modify } from 'jsonc-parser';
5
+ import { VERSION } from "../core/version.mjs";
6
+ import { sameToken } from "../agents/proxy.mjs";
7
+ import { ACCOUNT_KINDS } from "./accounts.mjs";
8
+ import { fixCommand, shown } from "./keys.mjs";
9
+ import { chatToPlanRequest, chunksToCompletion, classifyPlanError, readPlan, sessionProblem, signInAdvice } from "./chatgpt-plan.mjs";
10
+ import { conversationId, signalsOf, taskHasImages, withTaskImagesAsNotes } from "./decide.mjs";
11
+ import { MAX_WAIT_MS, pause, retryAfterMs } from "./retry-after.mjs";
12
+ import { problemNotice, statusLine } from "./status-line.mjs";
13
+ export const LOCAL_MODEL = 'phantom-1';
14
+ /** Answer headers that describe the upstream's connection or encoding, not the answer. fetch has already decoded the body. */
15
+ const HOP_BACK = new Set(['connection', 'keep-alive', 'transfer-encoding', 'content-encoding', 'content-length']);
16
+ function withModel(raw, model) {
17
+ return applyEdits(raw, modify(raw, ['model'], model, { formattingOptions: { insertSpaces: true, tabSize: 2 } }));
18
+ }
19
+ class UsageReader {
20
+ pending = '';
21
+ whole = [];
22
+ wholeSize = 0;
23
+ usage = null;
24
+ sawDone = false;
25
+ stream;
26
+ constructor(stream) {
27
+ this.stream = stream;
28
+ }
29
+ feed(text) {
30
+ if (!this.stream) {
31
+ if (this.wholeSize < 4_000_000)
32
+ this.whole.push(text);
33
+ this.wholeSize += text.length;
34
+ return;
35
+ }
36
+ const lines = (this.pending + text).split('\n');
37
+ this.pending = lines.pop() ?? '';
38
+ for (const line of lines)
39
+ this.read(line.replace(/^data:\s*/, ''));
40
+ }
41
+ done() {
42
+ if (this.stream)
43
+ this.read(this.pending.replace(/^data:\s*/, ''));
44
+ else if (this.wholeSize < 4_000_000)
45
+ this.read(this.whole.join(''));
46
+ this.pending = '';
47
+ this.whole = [];
48
+ }
49
+ read(json) {
50
+ if (json.trim() === '[DONE]')
51
+ this.sawDone = true;
52
+ if (!json.includes('"usage"'))
53
+ return;
54
+ try {
55
+ const usage = JSON.parse(json).usage;
56
+ if (typeof usage?.prompt_tokens === 'number' && typeof usage.completion_tokens === 'number') {
57
+ this.usage = { in: usage.prompt_tokens, out: usage.completion_tokens };
58
+ }
59
+ }
60
+ catch {
61
+ }
62
+ }
63
+ }
64
+ const MAX_BODY_BYTES = 32 * 1024 * 1024;
65
+ /**
66
+ * The request's body, or null when it is over {@link MAX_BODY_BYTES}. A body that is too large is still
67
+ * read to its end, without being kept, so the 413 reaches the agent instead of a broken connection.
68
+ */
69
+ async function readBody(req) {
70
+ const chunks = [];
71
+ let size = 0;
72
+ for await (const chunk of req) {
73
+ size += chunk.length;
74
+ if (size <= MAX_BODY_BYTES)
75
+ chunks.push(chunk);
76
+ }
77
+ return size > MAX_BODY_BYTES ? null : Buffer.concat(chunks);
78
+ }
79
+ function sendJson(res, status, body, headers = {}) {
80
+ res.writeHead(status, { 'content-type': 'application/json', ...headers });
81
+ res.end(JSON.stringify(body));
82
+ }
83
+ const errorBody = (type, message) => ({ error: { type, message } });
84
+ function headersOf(req) {
85
+ const headers = new Headers();
86
+ for (const [name, value] of Object.entries(req.headers))
87
+ if (typeof value === 'string')
88
+ headers.set(name, value);
89
+ return headers;
90
+ }
91
+ const retryable = (status) => status === 429 || status >= 500;
92
+ function waitFor(attempt) {
93
+ const header = attempt.kind === 'reply' ? attempt.headers?.['retry-after'] : attempt.answer.headers.get('retry-after');
94
+ const ms = retryAfterMs(header);
95
+ return ms !== null && ms > 0 && ms <= MAX_WAIT_MS ? ms : null;
96
+ }
97
+ function networkCodeOf(err) {
98
+ const code = err instanceof Error ? err.cause?.code : undefined;
99
+ return typeof code === 'string' && /^[A-Z][A-Z0-9_]*$/.test(code) ? code : undefined;
100
+ }
101
+ function stderrLine(r) {
102
+ const status = {
103
+ ok: String(r.status),
104
+ 'upstream-error': String(r.status),
105
+ 'stream-failed': `${r.status} stream-failed`,
106
+ 'client-closed': 'client-closed',
107
+ unreachable: '502',
108
+ 'not-signed-in': '503 not-signed-in',
109
+ }[r.outcome];
110
+ const tokens = r.tokens ? ` tokens=${r.tokens.in}+${r.tokens.out}` : '';
111
+ const code = r.code ? ` code=${r.code}` : '';
112
+ const because = r.because ? ` because=${r.because}` : '';
113
+ return `${r.at} picked=${r.picked} reason=${r.reason} account=${shown(r.account)}${r.fallback ? ' (fallback)' : ''} model=${shown(r.model)} status=${status}${code}${tokens} ms=${r.ms.total}${shown(because)}`;
114
+ }
115
+ export async function startLocalServer(opts) {
116
+ const { config, keys } = opts;
117
+ const token = opts.token === undefined ? null : Buffer.from(opts.token);
118
+ const run = `run_${randomBytes(4).toString('hex')}`;
119
+ let port = opts.port;
120
+ const inFlight = new Set();
121
+ async function tryKeyAccount(target, kind, raw, accept, signal) {
122
+ let answer;
123
+ try {
124
+ answer = await fetch(kind.chatUrl, {
125
+ method: 'POST',
126
+ headers: { 'content-type': 'application/json', accept: accept ?? 'application/json', 'user-agent': `phantom-local/${VERSION}`, ...kind.auth(keys[target.account]) },
127
+ body: withModel(raw, target.model),
128
+ signal,
129
+ });
130
+ }
131
+ catch (err) {
132
+ return unreachable(target, err);
133
+ }
134
+ return { attempt: { kind: 'pipe', answer }, because: retryable(answer.status) ? `${target.account}:${answer.status}` : null };
135
+ }
136
+ async function tryPlan(target, body, signal) {
137
+ const session = (await opts.chatgpt?.()) ?? { kind: 'signed-out' };
138
+ if (session.kind !== 'signed-in') {
139
+ const reply = JSON.stringify(errorBody('chatgpt_not_signed_in', sessionProblem(session)));
140
+ return { attempt: { kind: 'reply', status: 503, body: reply, outcome: 'not-signed-in', logStatus: null }, because: `${target.account}:not-signed-in` };
141
+ }
142
+ let answer;
143
+ try {
144
+ answer = await fetch(ACCOUNT_KINDS['chatgpt-plan'].responsesUrl, {
145
+ method: 'POST',
146
+ headers: { 'content-type': 'application/json', accept: 'text/event-stream', 'user-agent': `phantom-local/${VERSION}`, authorization: `Bearer ${session.account.access_token}` },
147
+ body: JSON.stringify(chatToPlanRequest(body, target.model)),
148
+ signal,
149
+ });
150
+ }
151
+ catch (err) {
152
+ return unreachable(target, err);
153
+ }
154
+ if (answer.ok && body.stream === true)
155
+ return { attempt: { kind: 'plan', answer }, because: null };
156
+ if (answer.ok)
157
+ return readWholePlan(target, answer);
158
+ const text = await answer.text().catch(() => '');
159
+ const error = classifyPlanError(answer.status, text);
160
+ const headers = Object.fromEntries(['retry-after', 'x-request-id'].flatMap((name) => (answer.headers.has(name) ? [[name, answer.headers.get(name)]] : [])));
161
+ const attempt = { kind: 'reply', status: answer.status, body: text, headers, outcome: 'upstream-error', logStatus: answer.status, ...(error.code && { code: error.code }) };
162
+ if (error.kind === 'next-entry' || error.kind === 'refused')
163
+ return { attempt, because: `${target.account}:${answer.status}${error.code ? `:${error.code}` : ''}` };
164
+ if (error.kind !== 'sign-in')
165
+ return { attempt, because: null };
166
+ const advice = signInAdvice(error);
167
+ opts.warn(advice);
168
+ return { attempt: { ...attempt, advice }, because: null };
169
+ }
170
+ /**
171
+ * The plan's answer for an agent that sent stream:false. The plan always
172
+ * streams, so it is read to its end here, before anything goes to the agent:
173
+ * a finished answer becomes one chat.completion, and one that stops partway
174
+ * becomes phantom-1's 502, worth the fallback, since the agent has nothing yet.
175
+ */
176
+ async function readWholePlan(target, answer) {
177
+ const chunks = [];
178
+ const { done, code, tokens } = await readPlan(answer, target.model, (chunk) => chunks.push(chunk));
179
+ if (done)
180
+ return { attempt: { kind: 'reply', status: 200, body: JSON.stringify(chunksToCompletion(chunks)), outcome: 'ok', logStatus: 200, tokens }, because: null };
181
+ const reply = JSON.stringify(errorBody('upstream_failed', `The ChatGPT plan stopped before it finished the answer${code ? ` (${code})` : ''}.`));
182
+ return {
183
+ attempt: { kind: 'reply', status: 502, body: reply, outcome: 'stream-failed', logStatus: answer.status, tokens, ...(code && { code }) },
184
+ because: `${target.account}:stream-failed${code ? `:${code}` : ''}`,
185
+ };
186
+ }
187
+ function unreachable(target, err) {
188
+ const code = networkCodeOf(err);
189
+ const reason = code ?? (err instanceof Error ? err.name : 'Error');
190
+ const body = JSON.stringify(errorBody('upstream_unreachable', `phantom-1 could not reach account "${shown(target.account)}" (${reason}).`));
191
+ return {
192
+ attempt: { kind: 'reply', status: 502, body, outcome: 'unreachable', logStatus: null, ...(code && { code }) },
193
+ because: `${target.account}:unreachable${code ? `:${code}` : ''}`,
194
+ };
195
+ }
196
+ async function chat(req, res) {
197
+ const arrived = performance.now();
198
+ const at = new Date().toISOString();
199
+ const msSince = (start) => Math.round(performance.now() - start);
200
+ const id = `r_${randomBytes(4).toString('hex')}`;
201
+ const abort = new AbortController();
202
+ res.on('close', () => {
203
+ if (!res.writableFinished)
204
+ abort.abort();
205
+ });
206
+ const bytes = await readBody(req);
207
+ if (!bytes)
208
+ return sendJson(res, 413, errorBody('request_too_large', 'phantom-1 takes a request body of up to 32 MB.'));
209
+ const raw = bytes.toString('utf8');
210
+ let body;
211
+ try {
212
+ body = JSON.parse(raw);
213
+ if (!body || typeof body !== 'object' || Array.isArray(body))
214
+ throw new TypeError();
215
+ }
216
+ catch {
217
+ return sendJson(res, 400, errorBody('invalid_request_error', 'The request body must be a JSON object.'));
218
+ }
219
+ const headers = headersOf(req);
220
+ const convo = conversationId(headers, body.messages);
221
+ const decideStart = performance.now();
222
+ const pick = await opts.picker(headers, body.messages);
223
+ const decide = msSince(decideStart);
224
+ const headersFor = (where, status, outcome, advice, code) => {
225
+ const answered = { pick, account: where.target.account, model: where.target.model, fallback: where.fallback, because: where.because, status, outcome, advice, code, saveProblems: opts.takeSaveProblems?.(), imagesLeftOut: where.imagesLeftOut };
226
+ const notice = problemNotice(answered);
227
+ return {
228
+ 'x-phantom-local-tier': pick.tier,
229
+ 'x-phantom-local-reason': pick.reason,
230
+ 'x-phantom-local-request-id': id,
231
+ 'x-phantom-local-status': statusLine(answered),
232
+ ...(notice && { 'x-phantom-local-notice': notice }),
233
+ };
234
+ };
235
+ const received = { sse: false, parts: [] };
236
+ let waited = 0;
237
+ const keep = (text) => {
238
+ if (opts.trace)
239
+ received.parts.push(text);
240
+ };
241
+ const finish = (where, end) => {
242
+ const record = {
243
+ v: 2,
244
+ at,
245
+ id,
246
+ run,
247
+ phantom: VERSION,
248
+ router_version: opts.rustRouterVersion ?? null,
249
+ sensitivity: config.sensitivity,
250
+ conversation: convo ? `c_${convo.slice(2, 10)}` : null,
251
+ messages: Array.isArray(body.messages) ? body.messages.length : 0,
252
+ stream: body.stream === true,
253
+ picked: pick.tier,
254
+ reason: pick.reason,
255
+ ...(pick.trial && { trial: pick.trial }),
256
+ account: where.target.account,
257
+ model: where.target.model,
258
+ fallback: where.fallback,
259
+ ...(where.because && { because: where.because }),
260
+ ...(end.code && { code: end.code }),
261
+ status: end.status,
262
+ outcome: end.outcome,
263
+ ms: { decide, first_byte: end.firstByte, total: msSince(arrived) },
264
+ tokens: end.tokens,
265
+ signals: signalsOf(body.messages),
266
+ router: pick.router ?? null,
267
+ };
268
+ opts.log(`${stderrLine(record)}${waited ? ` waited=${waited}` : ''}`);
269
+ opts.record?.(record);
270
+ opts.trace?.({ record, tiers: config.tiers, request: body, received: { sse: received.sse, text: received.parts.join('') } });
271
+ };
272
+ const noAnswer = (outcome) => ({ status: null, outcome, firstByte: null, tokens: null });
273
+ if (abort.signal.aborted)
274
+ return finish({ target: config.tiers[pick.tier], fallback: false }, noAnswer('client-closed'));
275
+ const accept = typeof req.headers.accept === 'string' ? req.headers.accept : undefined;
276
+ const entry = config.tiers[pick.tier];
277
+ const hasImages = taskHasImages(body.messages);
278
+ const tries = entry.fallback ? [entry, entry.fallback] : [entry];
279
+ function send(attempt, where) {
280
+ const firstByte = msSince(arrived);
281
+ if (attempt.kind === 'reply') {
282
+ res.writeHead(attempt.status, { 'content-type': 'application/json', ...attempt.headers, ...headersFor(where, attempt.status, attempt.outcome, attempt.advice, attempt.code) });
283
+ res.end(attempt.body);
284
+ keep(attempt.body);
285
+ finish(where, { status: attempt.logStatus, outcome: attempt.outcome, firstByte: attempt.logStatus === null ? null : firstByte, tokens: attempt.tokens ?? null, code: attempt.code });
286
+ return;
287
+ }
288
+ if (attempt.kind === 'plan')
289
+ return relayPlan(attempt.answer, where, firstByte);
290
+ return relayAnswer(attempt.answer, where, firstByte);
291
+ }
292
+ async function pass() {
293
+ let whyFallback;
294
+ let waitMs = null;
295
+ const noteWait = (attempt) => {
296
+ const asked = waitFor(attempt);
297
+ if (asked !== null && (waitMs === null || asked < waitMs))
298
+ waitMs = asked;
299
+ };
300
+ for (const [index, target] of tries.entries()) {
301
+ const account = config.accounts[target.account];
302
+ const imagesLeftOut = hasImages && Array.isArray(body.messages) && (await opts.targetReadsImages?.(target)) === false;
303
+ const sentBody = imagesLeftOut ? { ...body, messages: withTaskImagesAsNotes(body.messages) } : body;
304
+ const { attempt, because } = account.kind === 'chatgpt-plan'
305
+ ? await tryPlan(target, sentBody, abort.signal)
306
+ : await tryKeyAccount(target, ACCOUNT_KINDS[account.kind], imagesLeftOut ? JSON.stringify(sentBody) : raw, accept, abort.signal);
307
+ const where = { target, fallback: index > 0, because: whyFallback, imagesLeftOut };
308
+ if (abort.signal.aborted) {
309
+ if (attempt.kind !== 'reply')
310
+ await attempt.answer.body?.cancel().catch(() => { });
311
+ finish(where, noAnswer('client-closed'));
312
+ return null;
313
+ }
314
+ if (because && index < tries.length - 1) {
315
+ if (attempt.kind !== 'reply')
316
+ await attempt.answer.body?.cancel().catch(() => { });
317
+ whyFallback = because;
318
+ noteWait(attempt);
319
+ continue;
320
+ }
321
+ if (!because) {
322
+ send(attempt, where);
323
+ return null;
324
+ }
325
+ noteWait(attempt);
326
+ return { attempt, where, waitMs };
327
+ }
328
+ return null;
329
+ }
330
+ let triesLeft = 1;
331
+ for (;;) {
332
+ const last = await pass();
333
+ if (last === null)
334
+ return;
335
+ if (abort.signal.aborted) {
336
+ if (last.attempt.kind !== 'reply')
337
+ await last.attempt.answer.body?.cancel().catch(() => { });
338
+ return finish(last.where, noAnswer('client-closed'));
339
+ }
340
+ const ms = triesLeft > 0 ? last.waitMs : null;
341
+ if (ms === null)
342
+ return send(last.attempt, last.where);
343
+ triesLeft -= 1;
344
+ if (last.attempt.kind !== 'reply')
345
+ await last.attempt.answer.body?.cancel().catch(() => { });
346
+ const waitStart = performance.now();
347
+ await (opts.wait ?? pause)(ms, abort.signal);
348
+ waited += msSince(waitStart);
349
+ if (abort.signal.aborted)
350
+ return finish(last.where, noAnswer('client-closed'));
351
+ }
352
+ async function relayAnswer(answer, where, firstByte) {
353
+ if (answer.status === 401 || answer.status === 403) {
354
+ const name = where.target.account;
355
+ opts.warn(`Account "${shown(name)}" refused its key (${answer.status}). phantom config show says where it comes from; ${fixCommand(name)} saves a new one.`);
356
+ }
357
+ const back = {};
358
+ answer.headers.forEach((value, name) => {
359
+ if (!HOP_BACK.has(name.toLowerCase()))
360
+ back[name] = value;
361
+ });
362
+ res.writeHead(answer.status, { ...back, ...headersFor(where, answer.status) });
363
+ received.sse = (answer.headers.get('content-type') ?? '').includes('event-stream');
364
+ const usage = new UsageReader(received.sse);
365
+ const decoder = new TextDecoder();
366
+ let broke = false;
367
+ try {
368
+ if (answer.body) {
369
+ for await (const chunk of answer.body) {
370
+ res.write(chunk);
371
+ const text = decoder.decode(chunk, { stream: true });
372
+ usage.feed(text);
373
+ keep(text);
374
+ }
375
+ }
376
+ }
377
+ catch {
378
+ broke = true;
379
+ }
380
+ const whole = !broke || usage.sawDone;
381
+ const outcome = whole ? (answer.ok ? 'ok' : 'upstream-error') : abort.signal.aborted ? 'client-closed' : 'stream-failed';
382
+ if (outcome === 'stream-failed')
383
+ res.destroy();
384
+ else
385
+ res.end();
386
+ usage.done();
387
+ finish(where, { status: answer.status, outcome, firstByte, tokens: usage.usage });
388
+ }
389
+ async function relayPlan(answer, where, firstByte) {
390
+ const options = body.stream_options;
391
+ const wantsUsage = typeof options === 'object' && options !== null && options.include_usage === true;
392
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', ...headersFor(where, 200) });
393
+ received.sse = true;
394
+ const { done, code, tokens } = await readPlan(answer, where.target.model, (chunk) => {
395
+ const event = `data: ${JSON.stringify(chunk)}\n\n`;
396
+ if (!chunk.usage || wantsUsage)
397
+ res.write(event);
398
+ keep(event);
399
+ });
400
+ const outcome = abort.signal.aborted ? 'client-closed' : done ? 'ok' : 'stream-failed';
401
+ if (outcome === 'ok')
402
+ res.end('data: [DONE]\n\n');
403
+ else
404
+ res.destroy();
405
+ finish(where, { status: answer.status, outcome, firstByte, tokens, code });
406
+ }
407
+ }
408
+ const server = createServer((req, res) => {
409
+ if (req.headers.host !== `127.0.0.1:${port}` && req.headers.host !== `localhost:${port}`) {
410
+ return sendJson(res, 403, errorBody('forbidden', 'phantom-1 serves only requests addressed to 127.0.0.1.'));
411
+ }
412
+ if (req.headers.origin !== undefined) {
413
+ return sendJson(res, 403, errorBody('forbidden', 'phantom-1 refuses requests from web pages.'));
414
+ }
415
+ if (token && !sameToken(req.headers.authorization?.replace(/^Bearer /i, ''), token)) {
416
+ return sendJson(res, 401, errorBody('unauthorized', 'This phantom-1 server serves only the agent phantom started it for.'));
417
+ }
418
+ const path = new URL(req.url ?? '/', 'http://x').pathname.replace(/\/+$/, '');
419
+ if (req.method === 'GET' && path === '/v1/models') {
420
+ return sendJson(res, 200, { object: 'list', data: [{ id: LOCAL_MODEL, object: 'model', created: 0, owned_by: 'phantom' }] });
421
+ }
422
+ if (req.method === 'POST' && path === '/v1/chat/completions') {
423
+ const handled = chat(req, res)
424
+ .catch(() => {
425
+ if (!res.headersSent)
426
+ sendJson(res, 500, errorBody('server_error', 'phantom-1 failed on this request.'));
427
+ else
428
+ res.end();
429
+ })
430
+ .finally(() => inFlight.delete(handled));
431
+ inFlight.add(handled);
432
+ return;
433
+ }
434
+ sendJson(res, 404, errorBody('not_found', 'phantom-1 serves POST /v1/chat/completions and GET /v1/models.'));
435
+ });
436
+ await new Promise((resolve, reject) => {
437
+ server.once('error', reject);
438
+ server.listen(port, '127.0.0.1', () => resolve());
439
+ });
440
+ port = server.address().port;
441
+ return {
442
+ url: `http://127.0.0.1:${port}`,
443
+ close: async () => {
444
+ server.closeAllConnections();
445
+ await new Promise((resolve) => server.close(() => resolve()));
446
+ await Promise.all(inFlight);
447
+ },
448
+ };
449
+ }
@@ -0,0 +1,17 @@
1
+ import type { TierPick } from './decide.mts';
2
+ import type { Outcome } from './request-log.mts';
3
+ export type Answered = {
4
+ pick: TierPick;
5
+ account: string;
6
+ model: string;
7
+ fallback: boolean;
8
+ because?: string;
9
+ status: number;
10
+ outcome?: Outcome;
11
+ advice?: string;
12
+ code?: string;
13
+ saveProblems?: string[];
14
+ imagesLeftOut?: boolean;
15
+ };
16
+ export declare function statusLine(answered: Answered): string;
17
+ export declare function problemNotice(answered: Answered): string | null;
@@ -0,0 +1,81 @@
1
+ import { shown } from "./keys.mjs";
2
+ const TIER_NAMES = { standard: 'Standard', frontier: 'Frontier' };
3
+ const OVERRIDE_WORDS = {
4
+ critical_error: 'a critical error',
5
+ repeated_failure: 'the same failure twice',
6
+ compaction: 'the chat was compacted',
7
+ };
8
+ export function statusLine(answered) {
9
+ const fallback = answered.fallback ? ' (fallback)' : '';
10
+ return headerSafe(`phantom: ${TIER_NAMES[answered.pick.tier]}, ${where(answered)}${fallback}, ${whyInWords(answered.pick)}`);
11
+ }
12
+ export function problemNotice(answered) {
13
+ const problems = [];
14
+ const tier = TIER_NAMES[answered.pick.tier];
15
+ if (answered.pick.reason === 'router:unavailable') {
16
+ problems.push("the router didn't answer, so phantom-1 picked Frontier. phantom config show says where the router is.");
17
+ }
18
+ if (answered.fallback && answered.because) {
19
+ problems.push(`${fallbackCause(answered.because)}, so ${tier} used its fallback, ${where(answered)}.`);
20
+ }
21
+ if (answered.imagesLeftOut) {
22
+ problems.push(`${where(answered)} can't read images, so it was told it can't see your image and answered from your text.`);
23
+ }
24
+ if (answered.status >= 400) {
25
+ problems.push(answered.advice ? `${tier} (${where(answered)}): ${answered.advice}` : `${tier} (${where(answered)}) ${failureInWords(answered)}`);
26
+ }
27
+ problems.push(...(answered.saveProblems ?? []));
28
+ return problems.length === 0 ? null : headerSafe(`phantom: ${problems.join(' ')}`);
29
+ }
30
+ function where(answered) {
31
+ return `${shown(answered.model)} on ${shown(answered.account)}`;
32
+ }
33
+ function whyInWords(pick) {
34
+ switch (pick.reason) {
35
+ case 'helper':
36
+ return 'a helper agent';
37
+ case 'said-failed':
38
+ return 'you said it failed';
39
+ case 'agent-failed':
40
+ return 'the agent said it failed';
41
+ case 'too-large':
42
+ return 'chat too long to move up';
43
+ case 'router:unavailable':
44
+ return "the router didn't answer";
45
+ case 'router:capable_hold':
46
+ return 'staying on Frontier after a move up';
47
+ case 'router:override':
48
+ return OVERRIDE_WORDS[pick.router?.override ?? ''] ?? 'a hard reason';
49
+ case 'router:dimensions':
50
+ return pick.tier === 'frontier' ? 'a hard step' : 'a routine step';
51
+ case 'router:fall_open':
52
+ return 'a routine step';
53
+ case 'trial':
54
+ return 'the trial kept this task on Standard';
55
+ case 'image':
56
+ return `an image ${pick.tier === 'frontier' ? 'Standard' : 'Frontier'}'s model can't read`;
57
+ default:
58
+ return pick.reason;
59
+ }
60
+ }
61
+ function fallbackCause(because) {
62
+ const [account, what, code] = because.split(':');
63
+ const name = shown(account);
64
+ if (what === 'unreachable')
65
+ return `${name} couldn't be reached${code ? ` (${code})` : ''}`;
66
+ if (what === 'not-signed-in')
67
+ return `${name} has no usable ChatGPT sign-in (run phantom config chatgpt login)`;
68
+ if (what === 'stream-failed')
69
+ return `${name} stopped partway through its answer`;
70
+ return `${name} answered ${what}${code ? ` (${code})` : ''}`;
71
+ }
72
+ function failureInWords(answered) {
73
+ if (answered.outcome === 'unreachable')
74
+ return `couldn't be reached${answered.code ? ` (${answered.code})` : ''}.`;
75
+ if (answered.outcome === 'not-signed-in')
76
+ return 'has no usable ChatGPT sign-in. Run phantom config chatgpt login.';
77
+ return `answered ${answered.status}.`;
78
+ }
79
+ function headerSafe(text) {
80
+ return text.replace(/[^\x20-\x7e]/g, '?');
81
+ }
@@ -0,0 +1,3 @@
1
+ import { type CommandInput } from '../core/helpers.mts';
2
+ export declare const SETTING_FLAGS: string[];
3
+ export declare function configFromFlags(input: CommandInput): Promise<number>;