@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.
- package/README.md +138 -117
- 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 -114
- 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,193 @@
|
|
|
1
|
+
// docs: Before `phantom opencode` starts OpenCode, asks OpenCode itself, with the run's own environment and in each folder whose config it may read (including the folder of a session named with -s), which models it could call (`opencode models`) and which config files it read (`opencode debug config`), and returns why to stop when anything could send a model call around phantom's relay
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { statSync } from 'node:fs';
|
|
5
|
+
const ANSWER_LIMIT_MS = 30_000;
|
|
6
|
+
/**
|
|
7
|
+
* Why phantom has to ask OpenCode instead of trusting its own settings: OpenCode 2.4.3 lays phantom's run config
|
|
8
|
+
* (`OPENCODE_CONFIG_CONTENT`) over the user's own files, but those files are merged in too. Seen with 2.4.3:
|
|
9
|
+
* - provider rules (`enabled_providers`, or an `allow` in `policies`) turn other providers back on, including one
|
|
10
|
+
* with no key yet, which `/connect` in OpenCode's screen can add a key to during the run;
|
|
11
|
+
* - settings for the run's provider (a model's `settings.baseURL`, a second model) merge into it and send calls
|
|
12
|
+
* elsewhere. The run's provider has an id no user config uses (`phantom-relay-<4 letters>`), so this takes a file
|
|
13
|
+
* that names it on purpose, but it is checked anyway.
|
|
14
|
+
* A call that goes around the relay skips phantom-1: unrouted, unlogged, on another account.
|
|
15
|
+
*
|
|
16
|
+
* The run's provider and models are read from the run's config in `env`. Returns the message to stop with, or null
|
|
17
|
+
* when every folder is clean. Rejects with the spawn error when OpenCode can't be started (not installed).
|
|
18
|
+
*/
|
|
19
|
+
export async function openCodeRoutingProblem(env, args, cwd, limitMs = ANSWER_LIMIT_MS) {
|
|
20
|
+
const run = runProvider(env);
|
|
21
|
+
const folders = foldersOpenCodeReads(args, cwd);
|
|
22
|
+
const session = sessionNamed(args);
|
|
23
|
+
if (session) {
|
|
24
|
+
const found = await sessionFolder(session, env, cwd, limitMs);
|
|
25
|
+
if ('problem' in found)
|
|
26
|
+
return found.problem;
|
|
27
|
+
folders.push(found.folder);
|
|
28
|
+
}
|
|
29
|
+
for (const folder of new Set(folders)) {
|
|
30
|
+
const problem = await folderProblem(run, env, folder, limitMs);
|
|
31
|
+
if (problem)
|
|
32
|
+
return problem;
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
function runProvider(env) {
|
|
37
|
+
const config = JSON.parse(env.OPENCODE_CONFIG_CONTENT ?? '{}');
|
|
38
|
+
const [id, provider] = Object.entries(config.providers ?? {})[0] ?? ['', {}];
|
|
39
|
+
return { id, models: Object.keys(provider.models ?? {}).map((m) => `${id}/${m}`) };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The folders OpenCode may read a project's opencode.json from: the one phantom runs in, and any folder named in
|
|
43
|
+
* the arguments (`opencode <directory>` starts there). Checking an extra folder can only add a refusal.
|
|
44
|
+
*/
|
|
45
|
+
function foldersOpenCodeReads(args, cwd) {
|
|
46
|
+
const named = args.filter((a) => !a.startsWith('-')).map((a) => path.resolve(cwd, a)).filter(isFolder);
|
|
47
|
+
return [cwd, ...named];
|
|
48
|
+
}
|
|
49
|
+
function sessionNamed(args) {
|
|
50
|
+
for (let i = 0; i < args.length; i++) {
|
|
51
|
+
if ((args[i] === '-s' || args[i] === '--session') && args[i + 1])
|
|
52
|
+
return args[i + 1];
|
|
53
|
+
if (args[i].startsWith('--session='))
|
|
54
|
+
return args[i].slice('--session='.length);
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The folder a saved session was started in. OpenCode runs a session named with -s with that folder's config, even
|
|
60
|
+
* from another folder, so that folder is checked too. `opencode session export` says where it is.
|
|
61
|
+
*/
|
|
62
|
+
async function sessionFolder(id, env, cwd, limitMs) {
|
|
63
|
+
const exported = await askOpenCode(['session', 'export', '--standalone', id], env, cwd, limitMs);
|
|
64
|
+
let folder;
|
|
65
|
+
try {
|
|
66
|
+
folder = JSON.parse(exported.stdout).info?.location?.directory;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
folder = undefined;
|
|
70
|
+
}
|
|
71
|
+
if (exported.code === 0 && typeof folder === 'string' && folder)
|
|
72
|
+
return { folder };
|
|
73
|
+
const why = lastLine(exported.stderr) || 'it gave no folder';
|
|
74
|
+
return {
|
|
75
|
+
problem: `phantom opencode stopped before starting OpenCode: OpenCode continues session ${id} with the settings of the folder it was started in, and phantom couldn't find that folder to check it (OpenCode said: ${why}). Start phantom opencode in that session's folder and use -c, or start a new session.`,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
async function folderProblem(run, env, folder, limitMs) {
|
|
79
|
+
const listed = await askOpenCode(['models', '--standalone'], env, folder, limitMs);
|
|
80
|
+
if (listed.code !== 0) {
|
|
81
|
+
return `phantom opencode stopped before starting OpenCode: it first asks OpenCode which models it can use, and OpenCode answered with an error: ${lastLine(listed.stderr) || `exit code ${listed.code}`}. Fix that, then run phantom opencode again.`;
|
|
82
|
+
}
|
|
83
|
+
const outside = listed.stdout
|
|
84
|
+
.split('\n')
|
|
85
|
+
.map((line) => line.trim())
|
|
86
|
+
.filter((model) => model && !run.models.includes(model));
|
|
87
|
+
const answer = await askOpenCode(['debug', 'config', '--standalone'], env, folder, limitMs);
|
|
88
|
+
const others = otherConfigs(answer.stdout, run.id);
|
|
89
|
+
if (!others) {
|
|
90
|
+
return `phantom opencode stopped before starting OpenCode: it couldn't read OpenCode's list of config files (\`opencode debug config\`${answer.code === 0 ? '' : `: ${lastLine(answer.stderr) || `exit code ${answer.code}`}`}), so it can't tell whether one sends calls elsewhere. Fix that, then run phantom opencode again.`;
|
|
91
|
+
}
|
|
92
|
+
const touching = others.filter((c) => JSON.stringify(c.info ?? {}).includes(run.id));
|
|
93
|
+
if (touching.length) {
|
|
94
|
+
return `phantom opencode stopped before starting OpenCode: these OpenCode config files change phantom's provider for this run (${run.id}), which could send its calls somewhere else:\n${fileList(touching)}Remove those settings, then try again.`;
|
|
95
|
+
}
|
|
96
|
+
const opening = others.filter((c) => Array.isArray(c.info?.policies) && c.info.policies.some((r) => opensAnotherProvider(r, run.id)));
|
|
97
|
+
if (opening.length || outside.length)
|
|
98
|
+
return stopMessage(outside, opening);
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Every config source in `opencode debug config`'s answer except the run's own, which OpenCode shows with no file
|
|
103
|
+
* and with the run's provider in it. Null when the answer can't be read.
|
|
104
|
+
*/
|
|
105
|
+
function otherConfigs(answer, runId) {
|
|
106
|
+
let sources;
|
|
107
|
+
try {
|
|
108
|
+
sources = JSON.parse(answer);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
if (!Array.isArray(sources))
|
|
114
|
+
return null;
|
|
115
|
+
const ours = sources.findLastIndex((s) => s?.path === undefined && Object.hasOwn(s?.info?.providers ?? {}, runId));
|
|
116
|
+
return sources.filter((s, i) => i !== ours && s?.info);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Whether a rule lets OpenCode use a provider other than the run's. OpenCode shows a file's `enabled_providers` as
|
|
120
|
+
* rules too (deny `*`, then allow each one named). An action with a `*` in it may cover provider.use, so it counts.
|
|
121
|
+
* It counts whether or not that provider has a key now: `/connect` can add one during the run.
|
|
122
|
+
*/
|
|
123
|
+
function opensAnotherProvider(rule, runId) {
|
|
124
|
+
const coversProviders = rule?.action === 'provider.use' || (typeof rule?.action === 'string' && rule.action.includes('*'));
|
|
125
|
+
return rule?.effect === 'allow' && coversProviders && rule.resource !== runId;
|
|
126
|
+
}
|
|
127
|
+
function stopMessage(outside, files) {
|
|
128
|
+
const shown = outside.length > 5 ? `${outside.slice(0, 5).join(', ')} and ${outside.length - 5} more` : outside.join(', ');
|
|
129
|
+
const now = outside.length ? `OpenCode could already use models outside phantom-1 (${shown}), and a call to one would skip phantom and go straight to that provider.` : '';
|
|
130
|
+
if (!files.length) {
|
|
131
|
+
return `phantom opencode stopped before starting OpenCode: ${now}\nphantom could not tell which config file turns them on; \`opencode debug config\` lists every file OpenCode reads. Remove the setting that adds them, then try again.`;
|
|
132
|
+
}
|
|
133
|
+
return `phantom opencode stopped before starting OpenCode: your OpenCode settings let it use providers other than phantom-1's. ${now || "OpenCode lists none of their models now, but /connect in OpenCode's screen could add a key during the run, and calls to that provider would skip phantom."}\nThese OpenCode config files turn other providers on, with their enabled_providers or policies setting:\n${fileList(files)}Remove that setting from them (or run phantom opencode where they don't apply), then try again.`;
|
|
134
|
+
}
|
|
135
|
+
function fileList(sources) {
|
|
136
|
+
return sources.map((s) => ` ${typeof s.path === 'string' ? s.path : 'a config with no file'}\n`).join('');
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Runs `opencode <args>` in `folder` with `env`, and collects what it prints. OpenCode runs in a process group of
|
|
140
|
+
* its own, so a helper it starts can be stopped with it: once OpenCode exits, its answer is complete, and a helper
|
|
141
|
+
* still holding its output open is stopped. If OpenCode hasn't exited after `limitMs`, the whole group is stopped.
|
|
142
|
+
*/
|
|
143
|
+
function askOpenCode(args, env, folder, limitMs) {
|
|
144
|
+
return new Promise((resolve, reject) => {
|
|
145
|
+
const child = spawn('opencode', args, { cwd: folder, env: env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
|
|
146
|
+
let stdout = '';
|
|
147
|
+
let stderr = '';
|
|
148
|
+
let exitCode = null;
|
|
149
|
+
const stopGroup = () => {
|
|
150
|
+
try {
|
|
151
|
+
if (child.pid)
|
|
152
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
// The group has already ended.
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
const finish = (answer) => {
|
|
159
|
+
clearTimeout(timer);
|
|
160
|
+
resolve(answer);
|
|
161
|
+
};
|
|
162
|
+
const timer = setTimeout(() => {
|
|
163
|
+
stopGroup();
|
|
164
|
+
if (exitCode !== null)
|
|
165
|
+
finish({ code: exitCode, stdout, stderr });
|
|
166
|
+
else
|
|
167
|
+
finish({ code: 1, stdout, stderr: `${stderr}\nOpenCode gave no answer within ${limitMs / 1000} seconds` });
|
|
168
|
+
}, limitMs);
|
|
169
|
+
child.stdout.on('data', (chunk) => (stdout += chunk));
|
|
170
|
+
child.stderr.on('data', (chunk) => (stderr += chunk));
|
|
171
|
+
child.on('error', (err) => {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
reject(err);
|
|
174
|
+
});
|
|
175
|
+
child.on('exit', (code) => {
|
|
176
|
+
exitCode = code ?? 1;
|
|
177
|
+
stopGroup();
|
|
178
|
+
});
|
|
179
|
+
child.on('close', (code) => finish({ code: code ?? exitCode ?? 1, stdout, stderr }));
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
function lastLine(text) {
|
|
183
|
+
const lines = text.replace(/\u001b\[[0-9;]*m/g, '').split('\n').map((l) => l.trim()).filter(Boolean);
|
|
184
|
+
return lines.at(-1) ?? '';
|
|
185
|
+
}
|
|
186
|
+
function isFolder(p) {
|
|
187
|
+
try {
|
|
188
|
+
return statSync(p).isDirectory();
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Env } from '../core/state.mts';
|
|
2
|
+
export declare function keyPath(env: Env): string;
|
|
3
|
+
export declare function namedKeyPath(env: Env, name: string): string;
|
|
4
|
+
export declare function keyId(key: string): string;
|
|
5
|
+
export declare function resolveApiKey(env: Env): string;
|
|
6
|
+
export declare function readNamedKey(env: Env, name: string): string;
|
|
7
|
+
export declare function startModel(env: Env): string;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// docs: The Phantom key `phantom codex`, `phantom claude` and `phantom pi --server` send to Phantom's server: PHANTOM_KEY_NAME (a key an older CLI saved by name), then PHANTOM_API_KEY, then the default key an older CLI saved. No command saves one any more; this only reads them. Also the model an older CLI's `models use` picked for the agents to start on
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { die } from "../core/errors.mjs";
|
|
6
|
+
import { stateDir } from "../core/state.mjs";
|
|
7
|
+
import { readSecret } from "../core/secrets.mjs";
|
|
8
|
+
const KEY_NAME = /^[a-z0-9][a-z0-9_-]{0,31}$/i;
|
|
9
|
+
export function keyPath(env) {
|
|
10
|
+
return path.join(stateDir(env), 'key');
|
|
11
|
+
}
|
|
12
|
+
export function namedKeyPath(env, name) {
|
|
13
|
+
if (!KEY_NAME.test(name))
|
|
14
|
+
die(`Key names use letters, numbers, - and _ (up to 32): ${name}`);
|
|
15
|
+
return path.join(stateDir(env), 'keys', name);
|
|
16
|
+
}
|
|
17
|
+
export function keyId(key) {
|
|
18
|
+
return createHash('sha256').update(key.trim()).digest('hex').slice(0, 12);
|
|
19
|
+
}
|
|
20
|
+
export function resolveApiKey(env) {
|
|
21
|
+
if (env.PHANTOM_KEY_NAME)
|
|
22
|
+
return readNamedKey(env, env.PHANTOM_KEY_NAME);
|
|
23
|
+
if (env.PHANTOM_API_KEY)
|
|
24
|
+
return env.PHANTOM_API_KEY;
|
|
25
|
+
return existsSync(keyPath(env)) ? readSecret(env, keyPath(env)).trim() : '';
|
|
26
|
+
}
|
|
27
|
+
export function readNamedKey(env, name) {
|
|
28
|
+
const file = namedKeyPath(env, name);
|
|
29
|
+
if (!existsSync(file))
|
|
30
|
+
die(`No saved key named ${name}. Set PHANTOM_API_KEY instead.`, 'no_key');
|
|
31
|
+
return readSecret(env, file).trim();
|
|
32
|
+
}
|
|
33
|
+
export function startModel(env) {
|
|
34
|
+
try {
|
|
35
|
+
return readFileSync(path.join(stateDir(env), 'model'), 'utf-8').trim() || 'phantom-1';
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return 'phantom-1';
|
|
39
|
+
}
|
|
40
|
+
}
|
package/dist/agents/proxy.d.mts
CHANGED
|
@@ -1,44 +1,42 @@
|
|
|
1
|
-
|
|
2
|
-
* The local proxy `phantom claude`, `phantom codex` and `phantom pi` point the agent at.
|
|
3
|
-
* It listens on 127.0.0.1 only, forwards each request to Phantom AI, and
|
|
4
|
-
* streams the answer back as it arrives, server-sent events included. The
|
|
5
|
-
* agent never holds a key: the proxy drops whatever auth the agent sends and
|
|
6
|
-
* adds its own.
|
|
7
|
-
*
|
|
8
|
-
* Because the proxy spends the user's key or wallet, it serves only the agent
|
|
9
|
-
* it started: each request must carry the run's token ({@link proxyToken}),
|
|
10
|
-
* must name the proxy in its Host header (so a page that rebinds a DNS name
|
|
11
|
-
* to 127.0.0.1 is refused), and must carry no Origin header (so no browser
|
|
12
|
-
* page can call it).
|
|
13
|
-
*/
|
|
14
|
-
/** A fresh secret for one run, which the agent sends as its key. */
|
|
1
|
+
import { type Session } from '../chatgpt/session.mts';
|
|
15
2
|
export declare function proxyToken(): string;
|
|
16
|
-
|
|
3
|
+
export declare function sameToken(given: string | undefined, token: Buffer): boolean;
|
|
17
4
|
export type ProxyAuth = {
|
|
18
|
-
/** Send a saved API key with every request. */
|
|
19
5
|
kind: 'key';
|
|
20
|
-
/** The key. It goes upstream only, never to the agent. */
|
|
21
6
|
apiKey: string;
|
|
22
7
|
};
|
|
23
|
-
|
|
8
|
+
export type ChatgptPlan = () => Promise<Session>;
|
|
24
9
|
export type AgentProxy = {
|
|
25
|
-
/** `http://127.0.0.1:<port>`. */
|
|
26
10
|
url: string;
|
|
27
|
-
/** Requests refused because of their Host, Origin or token. */
|
|
28
11
|
rejected: number;
|
|
29
|
-
/** Requests forwarded so far. */
|
|
30
12
|
forwarded: number;
|
|
31
|
-
|
|
13
|
+
direct: number;
|
|
14
|
+
notes: string[];
|
|
32
15
|
close(): Promise<void>;
|
|
33
16
|
};
|
|
34
|
-
/**
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
17
|
+
/** Responses fields the ChatGPT plan refuses: https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations */
|
|
18
|
+
export declare const PLAN_REFUSES: string[];
|
|
19
|
+
type MovedTools = Set<string>;
|
|
20
|
+
type PlanRequest = {
|
|
21
|
+
request: Record<string, unknown>;
|
|
22
|
+
moved: MovedTools;
|
|
23
|
+
};
|
|
24
|
+
export type Tool = {
|
|
25
|
+
type?: unknown;
|
|
26
|
+
name?: unknown;
|
|
27
|
+
};
|
|
28
|
+
export declare function groupLooseTools(tools: Tool[], namespace: {
|
|
29
|
+
name: string;
|
|
30
|
+
description: string;
|
|
31
|
+
}): {
|
|
32
|
+
tools: Tool[];
|
|
33
|
+
moved: MovedTools;
|
|
34
|
+
};
|
|
35
|
+
export declare function forChatgptPlan(body: Buffer): PlanRequest | null;
|
|
40
36
|
export declare function startProxy(opts: {
|
|
41
37
|
upstream: string;
|
|
42
38
|
auth: ProxyAuth;
|
|
43
39
|
token: string;
|
|
40
|
+
chatgpt?: ChatgptPlan;
|
|
44
41
|
}): Promise<AgentProxy>;
|
|
42
|
+
export {};
|
package/dist/agents/proxy.mjs
CHANGED
|
@@ -1,32 +1,22 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
3
3
|
import { explainNetworkError } from "../core/request.mjs";
|
|
4
|
-
|
|
5
|
-
* The local proxy `phantom claude`, `phantom codex` and `phantom pi` point the agent at.
|
|
6
|
-
* It listens on 127.0.0.1 only, forwards each request to Phantom AI, and
|
|
7
|
-
* streams the answer back as it arrives, server-sent events included. The
|
|
8
|
-
* agent never holds a key: the proxy drops whatever auth the agent sends and
|
|
9
|
-
* adds its own.
|
|
10
|
-
*
|
|
11
|
-
* Because the proxy spends the user's key or wallet, it serves only the agent
|
|
12
|
-
* it started: each request must carry the run's token ({@link proxyToken}),
|
|
13
|
-
* must name the proxy in its Host header (so a page that rebinds a DNS name
|
|
14
|
-
* to 127.0.0.1 is refused), and must carry no Origin header (so no browser
|
|
15
|
-
* page can call it).
|
|
16
|
-
*/
|
|
17
|
-
/** A fresh secret for one run, which the agent sends as its key. */
|
|
4
|
+
import { OPENAI } from "../chatgpt/session.mjs";
|
|
18
5
|
export function proxyToken() {
|
|
19
6
|
return randomBytes(32).toString('base64url');
|
|
20
7
|
}
|
|
21
|
-
|
|
22
|
-
function sameToken(given, token) {
|
|
8
|
+
export function sameToken(given, token) {
|
|
23
9
|
if (!given)
|
|
24
10
|
return false;
|
|
25
11
|
const b = Buffer.from(given);
|
|
26
12
|
return b.length === token.length && timingSafeEqual(b, token);
|
|
27
13
|
}
|
|
28
14
|
const HOP = new Set(['host', 'connection', 'keep-alive', 'proxy-connection', 'transfer-encoding', 'upgrade', 'content-length', 'accept-encoding', 'authorization', 'x-api-key', 'te', 'trailer']);
|
|
29
|
-
|
|
15
|
+
// x-models-etag names the version of OpenAI's model catalog. Codex fetches its catalog
|
|
16
|
+
// again whenever that differs from the one it holds, but here its catalog always comes
|
|
17
|
+
// from the proxy's /v1/models, so passing the header on only made Codex fetch it after
|
|
18
|
+
// every plan answer.
|
|
19
|
+
const HOP_BACK = new Set(['connection', 'keep-alive', 'transfer-encoding', 'content-encoding', 'content-length', 'x-models-etag']);
|
|
30
20
|
function readBody(req) {
|
|
31
21
|
return new Promise((resolve, reject) => {
|
|
32
22
|
const chunks = [];
|
|
@@ -39,17 +29,220 @@ function sendJson(res, status, body) {
|
|
|
39
29
|
res.writeHead(status, { 'content-type': 'application/json' });
|
|
40
30
|
res.end(JSON.stringify(body));
|
|
41
31
|
}
|
|
32
|
+
async function pipeBack(answer, res, editEvent) {
|
|
33
|
+
const back = {};
|
|
34
|
+
answer.headers.forEach((v, k) => {
|
|
35
|
+
if (!HOP_BACK.has(k.toLowerCase()))
|
|
36
|
+
back[k] = v;
|
|
37
|
+
});
|
|
38
|
+
res.writeHead(answer.status, back);
|
|
39
|
+
if (answer.body) {
|
|
40
|
+
const chunks = answer.body;
|
|
41
|
+
if (!editEvent) {
|
|
42
|
+
for await (const chunk of chunks)
|
|
43
|
+
res.write(chunk);
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
const decoder = new TextDecoder();
|
|
47
|
+
let pending = '';
|
|
48
|
+
for await (const chunk of chunks) {
|
|
49
|
+
pending += decoder.decode(chunk, { stream: true });
|
|
50
|
+
let end = pending.indexOf('\n\n');
|
|
51
|
+
while (end >= 0) {
|
|
52
|
+
res.write(editEvent(pending.slice(0, end + 2)));
|
|
53
|
+
pending = pending.slice(end + 2);
|
|
54
|
+
end = pending.indexOf('\n\n');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
res.write(pending + decoder.decode());
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
res.end();
|
|
61
|
+
}
|
|
62
|
+
/** Responses fields the ChatGPT plan refuses: https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations */
|
|
63
|
+
export const PLAN_REFUSES = ['background', 'conversation', 'max_output_tokens', 'max_tool_calls', 'metadata', 'moderation', 'multi_agent', 'prompt', 'prompt_cache_retention', 'safety_identifier', 'temperature', 'top_logprobs', 'top_p', 'truncation', 'user', 'previous_response_id'];
|
|
42
64
|
/**
|
|
43
|
-
*
|
|
44
|
-
* @
|
|
45
|
-
*
|
|
46
|
-
*
|
|
65
|
+
* The ChatGPT plan takes function and custom tools only inside a namespace
|
|
66
|
+
* (same page as {@link PLAN_REFUSES}). Codex sends most of its tools loose, so
|
|
67
|
+
* the proxy moves those into one namespace of its own:
|
|
68
|
+
*
|
|
69
|
+
* Codex sends tools: [exec_command, apply_patch, namespace multi_agent_v1 [...], web_search]
|
|
70
|
+
* plan gets tools: [namespace codex [exec_command, apply_patch], namespace multi_agent_v1 [...], web_search]
|
|
71
|
+
*
|
|
72
|
+
* The model then calls `exec_command` with `namespace: "codex"`. Codex looks a
|
|
73
|
+
* call up by its namespace and name together, so it would not find that tool.
|
|
74
|
+
* The proxy takes `namespace: "codex"` off those calls on the way back to Codex
|
|
75
|
+
* ({@link withCodexNames}), and puts it on again when Codex sends them back in
|
|
76
|
+
* `input` as history.
|
|
47
77
|
*/
|
|
78
|
+
const CODEX_NAMESPACE = 'codex';
|
|
79
|
+
const CODEX_TOOLS = { name: CODEX_NAMESPACE, description: 'Codex\'s own tools: shell commands, file edits and the rest of its workspace tools.' };
|
|
80
|
+
const isLoose = (tool) => tool?.type === 'function' || tool?.type === 'custom';
|
|
81
|
+
const isToolCall = (item) => item?.type === 'function_call' || item?.type === 'custom_tool_call';
|
|
82
|
+
export function groupLooseTools(tools, namespace) {
|
|
83
|
+
const loose = tools.filter(isLoose);
|
|
84
|
+
const moved = new Set(loose.map((tool) => String(tool.name)));
|
|
85
|
+
if (!loose.length)
|
|
86
|
+
return { tools, moved };
|
|
87
|
+
return { tools: [{ type: 'namespace', ...namespace, tools: loose }, ...tools.filter((tool) => !isLoose(tool))], moved };
|
|
88
|
+
}
|
|
89
|
+
export function forChatgptPlan(body) {
|
|
90
|
+
let parsed;
|
|
91
|
+
try {
|
|
92
|
+
parsed = JSON.parse(body.toString('utf-8'));
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
if (!parsed || typeof parsed !== 'object')
|
|
98
|
+
return null;
|
|
99
|
+
const request = { ...parsed };
|
|
100
|
+
if (typeof request.model !== 'string' || !request.model.startsWith('openai/'))
|
|
101
|
+
return null;
|
|
102
|
+
for (const field of PLAN_REFUSES)
|
|
103
|
+
delete request[field];
|
|
104
|
+
const grouped = groupLooseTools(Array.isArray(request.tools) ? request.tools : [], CODEX_TOOLS);
|
|
105
|
+
const moved = grouped.moved;
|
|
106
|
+
if (moved.size)
|
|
107
|
+
request.tools = grouped.tools;
|
|
108
|
+
if (Array.isArray(request.input)) {
|
|
109
|
+
request.input = request.input.map((item) => {
|
|
110
|
+
if (item?.role === 'system')
|
|
111
|
+
return { ...item, role: 'developer' };
|
|
112
|
+
if (isToolCall(item) && item.namespace === undefined && moved.has(String(item.name)))
|
|
113
|
+
return { ...item, namespace: CODEX_NAMESPACE };
|
|
114
|
+
return item;
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
return { request: { ...request, model: request.model.slice('openai/'.length), stream: true, store: false }, moved };
|
|
118
|
+
}
|
|
119
|
+
function withCodexNames(event, moved) {
|
|
120
|
+
const data = /^data: (.*)$/m.exec(event);
|
|
121
|
+
if (!data)
|
|
122
|
+
return event;
|
|
123
|
+
let parsed;
|
|
124
|
+
try {
|
|
125
|
+
parsed = JSON.parse(data[1]);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return event;
|
|
129
|
+
}
|
|
130
|
+
const output = Array.isArray(parsed?.response?.output) ? parsed.response.output : [];
|
|
131
|
+
let changed = false;
|
|
132
|
+
for (const item of [parsed?.item, ...output]) {
|
|
133
|
+
if (item && isToolCall(item) && item.namespace === CODEX_NAMESPACE && moved.has(String(item.name))) {
|
|
134
|
+
delete item.namespace;
|
|
135
|
+
changed = true;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return changed ? event.replace(data[0], () => `data: ${JSON.stringify(parsed)}`) : event;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The ChatGPT plan's models as Codex catalog entries named `openai/<slug>`, the
|
|
142
|
+
* names this proxy sends to the plan, or null when the plan's list can't be read.
|
|
143
|
+
*
|
|
144
|
+
* GET /v1/models answers a plan token in Codex's own catalog format, with each
|
|
145
|
+
* model's context window, reasoning levels and prompt
|
|
146
|
+
* (https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference),
|
|
147
|
+
* so each entry is kept whole. Four fields change, as Codex changes them itself
|
|
148
|
+
* when it runs OpenAI's models on another provider (`bedrock_model` in openai/codex
|
|
149
|
+
* `codex-rs/model-provider/src/amazon_bedrock/catalog.rs`): Responses Lite and
|
|
150
|
+
* code mode go off, so Codex sends the requests {@link forChatgptPlan} converts,
|
|
151
|
+
* and the upgrade and availability notices go, since they name models without `openai/`.
|
|
152
|
+
*/
|
|
153
|
+
async function planCatalog(accessToken) {
|
|
154
|
+
try {
|
|
155
|
+
const answer = await fetch(`${OPENAI.resource}/models`, { headers: { authorization: `Bearer ${accessToken}` } });
|
|
156
|
+
const body = answer.ok ? (await answer.json()) : null;
|
|
157
|
+
if (!Array.isArray(body?.models))
|
|
158
|
+
return null;
|
|
159
|
+
return body.models
|
|
160
|
+
.filter((m) => typeof m?.slug === 'string')
|
|
161
|
+
.map((m) => ({ ...m, slug: `openai/${m.slug}`, use_responses_lite: false, tool_mode: null, upgrade: null, availability_nux: null }));
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* OpenAI refusals that rest the plan for the rest of the run: the sign-in was
|
|
169
|
+
* not accepted (401), a policy or eligibility block (403), or a usage limit
|
|
170
|
+
* (429). Any other refusal skips the plan for that request only.
|
|
171
|
+
* https://developers.openai.com/siwc/token-sharing-open-source/errors-and-recovery
|
|
172
|
+
*/
|
|
173
|
+
const RESTS_THE_PLAN = new Set([401, 403, 429]);
|
|
174
|
+
async function refusal(answer) {
|
|
175
|
+
const body = (await answer.json().catch(() => ({})));
|
|
176
|
+
const code = typeof body.error?.code === 'string' ? ` ${body.error.code}` : '';
|
|
177
|
+
const id = answer.headers.get('x-request-id');
|
|
178
|
+
return `OpenAI answered ${answer.status}${code}${id ? ` (request ${id})` : ''}${answer.status === 429 ? `; manage usage at ${OPENAI.usage}` : ''}`;
|
|
179
|
+
}
|
|
48
180
|
export async function startProxy(opts) {
|
|
49
181
|
const upstream = opts.upstream.replace(/\/+$/, '');
|
|
50
182
|
const token = Buffer.from(opts.token);
|
|
51
|
-
const state = { forwarded: 0, rejected: 0 };
|
|
183
|
+
const state = { forwarded: 0, rejected: 0, direct: 0 };
|
|
184
|
+
const notes = new Set();
|
|
185
|
+
let planRests = false;
|
|
186
|
+
let planModels;
|
|
52
187
|
let port = 0;
|
|
188
|
+
async function withPlanModels(answer) {
|
|
189
|
+
if (!opts.chatgpt || !answer.ok)
|
|
190
|
+
return answer;
|
|
191
|
+
const session = await opts.chatgpt();
|
|
192
|
+
if (session.kind !== 'signed-in')
|
|
193
|
+
return answer;
|
|
194
|
+
planModels ??= planCatalog(session.account.access_token).then((models) => {
|
|
195
|
+
if (!models)
|
|
196
|
+
planModels = undefined;
|
|
197
|
+
return models;
|
|
198
|
+
});
|
|
199
|
+
const plan = await planModels;
|
|
200
|
+
if (!plan)
|
|
201
|
+
return answer;
|
|
202
|
+
const text = await answer.text();
|
|
203
|
+
let catalog = null;
|
|
204
|
+
try {
|
|
205
|
+
catalog = JSON.parse(text);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
}
|
|
209
|
+
const body = Array.isArray(catalog?.models) ? JSON.stringify({ ...catalog, models: [...catalog.models, ...plan] }) : text;
|
|
210
|
+
return new Response(body, { status: answer.status, headers: answer.headers });
|
|
211
|
+
}
|
|
212
|
+
async function servedByPlan({ request, moved }, res, signal) {
|
|
213
|
+
if (!opts.chatgpt || planRests)
|
|
214
|
+
return false;
|
|
215
|
+
const session = await opts.chatgpt();
|
|
216
|
+
if (session.kind === 'refresh-failed')
|
|
217
|
+
notes.add(session.reason);
|
|
218
|
+
if (session.kind !== 'signed-in')
|
|
219
|
+
return false;
|
|
220
|
+
let answer;
|
|
221
|
+
try {
|
|
222
|
+
answer = await fetch(OPENAI.responses, {
|
|
223
|
+
method: 'POST',
|
|
224
|
+
headers: { authorization: `Bearer ${session.account.access_token}`, 'content-type': 'application/json', accept: 'text/event-stream' },
|
|
225
|
+
body: JSON.stringify(request),
|
|
226
|
+
signal,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
catch (err) {
|
|
230
|
+
if (signal.aborted)
|
|
231
|
+
throw err;
|
|
232
|
+
notes.add('could not reach api.openai.com');
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
if (!answer.ok) {
|
|
236
|
+
const why = await refusal(answer);
|
|
237
|
+
notes.add(why);
|
|
238
|
+
if (RESTS_THE_PLAN.has(answer.status))
|
|
239
|
+
planRests = true;
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
state.direct++;
|
|
243
|
+
await pipeBack(answer, res, moved.size ? (event) => withCodexNames(event, moved) : undefined);
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
53
246
|
const server = createServer(async (req, res) => {
|
|
54
247
|
const method = req.method ?? 'GET';
|
|
55
248
|
const host = req.headers.host;
|
|
@@ -91,6 +284,9 @@ export async function startProxy(opts) {
|
|
|
91
284
|
});
|
|
92
285
|
try {
|
|
93
286
|
const body = method === 'GET' || method === 'HEAD' ? undefined : await readBody(req);
|
|
287
|
+
const planRequest = opts.chatgpt && body && method === 'POST' && /\/v1\/responses$/.test(target.pathname) ? forChatgptPlan(body) : null;
|
|
288
|
+
if (planRequest && (await servedByPlan(planRequest, res, aborter.signal)))
|
|
289
|
+
return;
|
|
94
290
|
state.forwarded++;
|
|
95
291
|
const answer = await fetch(`${upstream}${target.pathname}${target.search}`, {
|
|
96
292
|
method,
|
|
@@ -98,17 +294,7 @@ export async function startProxy(opts) {
|
|
|
98
294
|
...(body && body.length ? { body: new Uint8Array(body) } : {}),
|
|
99
295
|
signal: aborter.signal,
|
|
100
296
|
});
|
|
101
|
-
|
|
102
|
-
answer.headers.forEach((v, k) => {
|
|
103
|
-
if (!HOP_BACK.has(k.toLowerCase()))
|
|
104
|
-
back[k] = v;
|
|
105
|
-
});
|
|
106
|
-
res.writeHead(answer.status, back);
|
|
107
|
-
if (answer.body) {
|
|
108
|
-
for await (const chunk of answer.body)
|
|
109
|
-
res.write(chunk);
|
|
110
|
-
}
|
|
111
|
-
res.end();
|
|
297
|
+
await pipeBack(method === 'GET' && /\/v1\/models$/.test(target.pathname) ? await withPlanModels(answer) : answer, res);
|
|
112
298
|
}
|
|
113
299
|
catch (err) {
|
|
114
300
|
if (aborter.signal.aborted)
|
|
@@ -134,6 +320,12 @@ export async function startProxy(opts) {
|
|
|
134
320
|
get forwarded() {
|
|
135
321
|
return state.forwarded;
|
|
136
322
|
},
|
|
323
|
+
get direct() {
|
|
324
|
+
return state.direct;
|
|
325
|
+
},
|
|
326
|
+
get notes() {
|
|
327
|
+
return [...notes];
|
|
328
|
+
},
|
|
137
329
|
close: () => new Promise((resolve) => {
|
|
138
330
|
server.closeAllConnections();
|
|
139
331
|
server.close(() => resolve());
|