@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,119 @@
|
|
|
1
|
+
// docs: `phantom config chatgpt login` and `logout`: Sign in with ChatGPT in the browser (PKCE and a loopback callback on 127.0.0.1), so a tier on the ChatGPT plan (`phantom pi`) and `phantom codex`'s openai/ models run on the user's ChatGPT plan
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
4
|
+
import { die } from "../core/errors.mjs";
|
|
5
|
+
import { openUrl, out } from "../core/helpers.mjs";
|
|
6
|
+
import { OPENAI, PLAN_SCOPE, checkIdToken, hostId, readSaved, saveCredentials, signOut, tokenFields } from "./session.mjs";
|
|
7
|
+
const APP_NAME = 'Phantom CLI';
|
|
8
|
+
const SCOPES = `openid profile email offline_access resource.invoke ${PLAN_SCOPE}`;
|
|
9
|
+
/** The port OpenAI's guide uses for the first sign-in. Another free port works when it is taken: only the port may change. */
|
|
10
|
+
const CALLBACK_PORT = 1455;
|
|
11
|
+
const CALLBACK_PATH = '/auth/callback';
|
|
12
|
+
const WAIT = 5 * 60_000;
|
|
13
|
+
const random = () => randomBytes(32).toString('base64url');
|
|
14
|
+
async function listenForCallback() {
|
|
15
|
+
let arrived;
|
|
16
|
+
const answer = new Promise((resolve, reject) => {
|
|
17
|
+
arrived = resolve;
|
|
18
|
+
setTimeout(() => reject(new Error('No answer from the browser within 5 minutes. Run phantom config chatgpt login again.')), WAIT).unref();
|
|
19
|
+
});
|
|
20
|
+
const server = createServer((req, res) => {
|
|
21
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
22
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
23
|
+
res.writeHead(404).end();
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }).end('Phantom CLI got the answer from ChatGPT. You can close this tab and go back to the terminal.\n');
|
|
27
|
+
arrived(url.searchParams);
|
|
28
|
+
});
|
|
29
|
+
const listen = (port) => new Promise((resolve, reject) => {
|
|
30
|
+
server.once('error', reject);
|
|
31
|
+
server.listen(port, '127.0.0.1', () => resolve());
|
|
32
|
+
});
|
|
33
|
+
await listen(CALLBACK_PORT).catch(() => listen(0));
|
|
34
|
+
const { port } = server.address();
|
|
35
|
+
return { redirectUri: `http://127.0.0.1:${port}${CALLBACK_PATH}`, answer, close: () => void server.close() };
|
|
36
|
+
}
|
|
37
|
+
async function login(input) {
|
|
38
|
+
const { env, io, flags, table } = input;
|
|
39
|
+
const host = hostId(env);
|
|
40
|
+
const before = readSaved(env);
|
|
41
|
+
const state = random();
|
|
42
|
+
const nonce = random();
|
|
43
|
+
const verifier = random();
|
|
44
|
+
const callback = await listenForCallback();
|
|
45
|
+
const link = `${OPENAI.authorize}?${new URLSearchParams({
|
|
46
|
+
client_id: before?.client_id ?? 'dynamic_agent_client',
|
|
47
|
+
...(before ? { login_hint: before.email } : { agent_name_hint: APP_NAME }),
|
|
48
|
+
ext_agent_host_id: host,
|
|
49
|
+
response_type: 'code',
|
|
50
|
+
redirect_uri: callback.redirectUri,
|
|
51
|
+
scope: SCOPES,
|
|
52
|
+
resource: OPENAI.resource,
|
|
53
|
+
state,
|
|
54
|
+
nonce,
|
|
55
|
+
code_challenge_method: 'S256',
|
|
56
|
+
code_challenge: createHash('sha256').update(verifier).digest('base64url'),
|
|
57
|
+
})}`;
|
|
58
|
+
io.stderr(`Continue with ChatGPT in your browser. If it doesn't open, visit:\n ${link}\n`);
|
|
59
|
+
if (!flags['no-browser'])
|
|
60
|
+
openUrl(link);
|
|
61
|
+
let back;
|
|
62
|
+
try {
|
|
63
|
+
back = await callback.answer;
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
callback.close();
|
|
67
|
+
}
|
|
68
|
+
const stop = (why) => die(`${why} Nothing was saved. Run phantom config chatgpt login to try again.`, 'chatgpt_sign_in');
|
|
69
|
+
if (back.get('state') !== state)
|
|
70
|
+
stop("The browser's answer was not for this sign-in.");
|
|
71
|
+
const error = back.get('error');
|
|
72
|
+
if (error === 'access_denied')
|
|
73
|
+
stop('You declined in the browser.');
|
|
74
|
+
if (error)
|
|
75
|
+
stop(`OpenAI stopped the sign-in (${error}).`);
|
|
76
|
+
const returned = back.get('client_id');
|
|
77
|
+
if (before && returned && returned !== before.client_id)
|
|
78
|
+
stop('OpenAI answered for a different app registration than the one saved here.');
|
|
79
|
+
const clientId = before?.client_id ?? returned;
|
|
80
|
+
if (!clientId || clientId === 'dynamic_agent_client')
|
|
81
|
+
stop('OpenAI did not finish registering Phantom CLI.');
|
|
82
|
+
const code = back.get('code') ?? stop('The browser came back without a sign-in code.');
|
|
83
|
+
const exchange = await fetch(OPENAI.token, {
|
|
84
|
+
method: 'POST',
|
|
85
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
86
|
+
body: new URLSearchParams({ grant_type: 'authorization_code', client_id: clientId, code, code_verifier: verifier, redirect_uri: callback.redirectUri, resource: OPENAI.resource }),
|
|
87
|
+
signal: AbortSignal.timeout(30_000),
|
|
88
|
+
});
|
|
89
|
+
const tokens = (await exchange.json().catch(() => ({})));
|
|
90
|
+
if (!exchange.ok || !tokens.access_token || !tokens.refresh_token || !tokens.id_token) {
|
|
91
|
+
stop(`OpenAI did not take the sign-in code (HTTP ${exchange.status}${tokens.error ? `, ${tokens.error}` : ''}).`);
|
|
92
|
+
}
|
|
93
|
+
const who = await checkIdToken(tokens.id_token, { clientId: clientId, nonce });
|
|
94
|
+
if (before && before.subject !== who.sub)
|
|
95
|
+
stop('That is a different ChatGPT account than the one this computer signed in with before.');
|
|
96
|
+
const account = { email: who.email, issuer: OPENAI.issuer, subject: who.sub, client_id: clientId, ext_agent_host_id: host, id_token: tokens.id_token, ...tokenFields(tokens) };
|
|
97
|
+
saveCredentials(env, account);
|
|
98
|
+
const planUsage = account.scopes.includes(PLAN_SCOPE);
|
|
99
|
+
const sentence = planUsage
|
|
100
|
+
? `You're using your ChatGPT plan (${who.email}). A tier on the ChatGPT plan runs on it now, and phantom codex sends openai/ models to it. Manage usage: ${OPENAI.usage}`
|
|
101
|
+
: `Signed in as ${who.email}, but ChatGPT plan use was not allowed, so nothing runs on the plan. Run phantom config chatgpt login again and allow it.`;
|
|
102
|
+
out({ signed_in: true, email: who.email, plan_usage: planUsage }, table, () => sentence, io.stdout);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
async function logout(input) {
|
|
106
|
+
const { revoked } = await signOut(input.env);
|
|
107
|
+
if (!revoked)
|
|
108
|
+
input.io.stderr('OpenAI did not confirm it ended the sign-in. The tokens are gone from this computer; to be sure, disconnect Phantom CLI in ChatGPT under Settings (https://chatgpt.com/settings).\n');
|
|
109
|
+
out({ signed_in: false, revoked }, input.table, () => 'Signed out of ChatGPT. A tier on the ChatGPT plan uses its fallback until you sign in again.', input.io.stdout);
|
|
110
|
+
return 0;
|
|
111
|
+
}
|
|
112
|
+
export async function chatgptCommand(input) {
|
|
113
|
+
const action = input.argv[2];
|
|
114
|
+
if (action === 'login')
|
|
115
|
+
return login(input);
|
|
116
|
+
if (action === 'logout')
|
|
117
|
+
return logout(input);
|
|
118
|
+
return die('phantom config chatgpt takes login or logout. phantom config show says who is signed in.', 'config_usage');
|
|
119
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { type Env } from '../core/state.mts';
|
|
2
|
+
/**
|
|
3
|
+
* Sign in with ChatGPT lets `phantom codex` send `openai/*` models to OpenAI on
|
|
4
|
+
* the user's own ChatGPT plan, from this computer, so the plan pays instead of
|
|
5
|
+
* Phantom credit. The tokens live only in a file here (mode 600) and go only to
|
|
6
|
+
* auth.openai.com and api.openai.com: never to Phantom AI, never into output.
|
|
7
|
+
*
|
|
8
|
+
* The flow follows OpenAI's guide for open-source and locally run apps:
|
|
9
|
+
* https://developers.openai.com/siwc/token-sharing-open-source
|
|
10
|
+
*/
|
|
11
|
+
/** OpenAI's endpoints, from https://auth.openai.com/.well-known/openid-configuration. */
|
|
12
|
+
export declare const OPENAI: {
|
|
13
|
+
readonly issuer: "https://auth.openai.com";
|
|
14
|
+
readonly authorize: "https://auth.openai.com/api/accounts/authorize";
|
|
15
|
+
readonly token: "https://auth.openai.com/api/accounts/oauth/token";
|
|
16
|
+
readonly revoke: "https://auth.openai.com/api/accounts/oauth/revoke";
|
|
17
|
+
readonly jwks: "https://auth.openai.com/.well-known/jwks.json";
|
|
18
|
+
readonly resource: "https://api.openai.com/v1";
|
|
19
|
+
readonly responses: "https://api.openai.com/v1/responses";
|
|
20
|
+
readonly usage: "https://chatgpt.com/settings/usage";
|
|
21
|
+
};
|
|
22
|
+
export declare const PLAN_SCOPE = "chatgpt.tokens.use.direct";
|
|
23
|
+
export type Registration = {
|
|
24
|
+
email: string;
|
|
25
|
+
issuer: string;
|
|
26
|
+
subject: string;
|
|
27
|
+
client_id: string;
|
|
28
|
+
ext_agent_host_id: string;
|
|
29
|
+
};
|
|
30
|
+
export type Credentials = Registration & {
|
|
31
|
+
id_token: string;
|
|
32
|
+
access_token: string;
|
|
33
|
+
refresh_token: string;
|
|
34
|
+
token_type: string;
|
|
35
|
+
expires_in: number;
|
|
36
|
+
scopes: string[];
|
|
37
|
+
saved_at: string;
|
|
38
|
+
};
|
|
39
|
+
export type Session = {
|
|
40
|
+
kind: 'signed-out';
|
|
41
|
+
} | {
|
|
42
|
+
kind: 'plan-off';
|
|
43
|
+
account: Credentials;
|
|
44
|
+
} | {
|
|
45
|
+
kind: 'signed-in';
|
|
46
|
+
account: Credentials;
|
|
47
|
+
} | {
|
|
48
|
+
kind: 'expired';
|
|
49
|
+
account: Credentials;
|
|
50
|
+
} | {
|
|
51
|
+
kind: 'refresh-failed';
|
|
52
|
+
reason: string;
|
|
53
|
+
};
|
|
54
|
+
export declare function hostId(env: Env): string;
|
|
55
|
+
export declare function readSaved(env: Env): Registration | Credentials | null;
|
|
56
|
+
export declare function saveCredentials(env: Env, account: Credentials): void;
|
|
57
|
+
export declare function readSession(env: Env, now?: number): Exclude<Session, {
|
|
58
|
+
kind: 'refresh-failed';
|
|
59
|
+
}>;
|
|
60
|
+
export declare function currentSession(env: Env, now?: number): Promise<Session>;
|
|
61
|
+
/** A token endpoint answer, as https://developers.openai.com/siwc/token-sharing-open-source/token-reference lists it. */
|
|
62
|
+
export type TokenAnswer = {
|
|
63
|
+
access_token: string;
|
|
64
|
+
refresh_token: string;
|
|
65
|
+
id_token: string;
|
|
66
|
+
token_type: string;
|
|
67
|
+
expires_in: number;
|
|
68
|
+
scope?: string;
|
|
69
|
+
};
|
|
70
|
+
export declare function tokenFields(t: TokenAnswer, scopesBefore?: string[]): {
|
|
71
|
+
access_token: string;
|
|
72
|
+
refresh_token: string;
|
|
73
|
+
token_type: string;
|
|
74
|
+
expires_in: number;
|
|
75
|
+
scopes: string[];
|
|
76
|
+
saved_at: string;
|
|
77
|
+
};
|
|
78
|
+
export declare function checkIdToken(idToken: string, expect: {
|
|
79
|
+
clientId: string;
|
|
80
|
+
nonce: string;
|
|
81
|
+
}): Promise<{
|
|
82
|
+
sub: string;
|
|
83
|
+
email: string;
|
|
84
|
+
}>;
|
|
85
|
+
export declare function signOut(env: Env): Promise<{
|
|
86
|
+
revoked: boolean;
|
|
87
|
+
}>;
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// docs: The ChatGPT sign-in saved on this computer: the host id, the credential file, the five states a sign-in can be in, token refresh (one process at a time, under a lock file) and revocation, and the ID token check
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createPublicKey, randomUUID, verify } from 'node:crypto';
|
|
4
|
+
import { existsSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { die } from "../core/errors.mjs";
|
|
6
|
+
import { makePrivateFolder, stateDir, writePrivate } from "../core/state.mjs";
|
|
7
|
+
/**
|
|
8
|
+
* Sign in with ChatGPT lets `phantom codex` send `openai/*` models to OpenAI on
|
|
9
|
+
* the user's own ChatGPT plan, from this computer, so the plan pays instead of
|
|
10
|
+
* Phantom credit. The tokens live only in a file here (mode 600) and go only to
|
|
11
|
+
* auth.openai.com and api.openai.com: never to Phantom AI, never into output.
|
|
12
|
+
*
|
|
13
|
+
* The flow follows OpenAI's guide for open-source and locally run apps:
|
|
14
|
+
* https://developers.openai.com/siwc/token-sharing-open-source
|
|
15
|
+
*/
|
|
16
|
+
/** OpenAI's endpoints, from https://auth.openai.com/.well-known/openid-configuration. */
|
|
17
|
+
export const OPENAI = {
|
|
18
|
+
issuer: 'https://auth.openai.com',
|
|
19
|
+
authorize: 'https://auth.openai.com/api/accounts/authorize',
|
|
20
|
+
token: 'https://auth.openai.com/api/accounts/oauth/token',
|
|
21
|
+
revoke: 'https://auth.openai.com/api/accounts/oauth/revoke',
|
|
22
|
+
jwks: 'https://auth.openai.com/.well-known/jwks.json',
|
|
23
|
+
resource: 'https://api.openai.com/v1',
|
|
24
|
+
responses: 'https://api.openai.com/v1/responses',
|
|
25
|
+
usage: 'https://chatgpt.com/settings/usage',
|
|
26
|
+
};
|
|
27
|
+
export const PLAN_SCOPE = 'chatgpt.tokens.use.direct';
|
|
28
|
+
const REFRESH_EARLY = 5 * 60_000;
|
|
29
|
+
const REFRESH_TIMEOUT = 30_000;
|
|
30
|
+
const LOCK_STALE_AFTER = 2 * REFRESH_TIMEOUT;
|
|
31
|
+
const LOCK_WAIT = 10_000;
|
|
32
|
+
const LOCK_POLL = 100;
|
|
33
|
+
const DEAD_REFRESH = new Set(['invalid_grant', 'invalid_refresh_token', 'token_expired', 'refresh_token_expired', 'refresh_token_invalidated', 'refresh_token_reused']);
|
|
34
|
+
const folder = (env) => path.join(stateDir(env), 'chatgpt');
|
|
35
|
+
const credentialsFile = (env) => path.join(folder(env), 'credentials.json');
|
|
36
|
+
const hostIdFile = (env) => path.join(folder(env), 'host-id');
|
|
37
|
+
const lockFile = (env) => path.join(folder(env), 'refresh.lock');
|
|
38
|
+
export function hostId(env) {
|
|
39
|
+
const file = hostIdFile(env);
|
|
40
|
+
if (existsSync(file))
|
|
41
|
+
return readFileSync(file, 'utf-8').trim();
|
|
42
|
+
const id = `urn:uuid:${randomUUID()}`;
|
|
43
|
+
writePrivate(env, file, id + '\n');
|
|
44
|
+
return id;
|
|
45
|
+
}
|
|
46
|
+
export function readSaved(env) {
|
|
47
|
+
const file = credentialsFile(env);
|
|
48
|
+
if (!existsSync(file))
|
|
49
|
+
return null;
|
|
50
|
+
return JSON.parse(readFileSync(file, 'utf-8'));
|
|
51
|
+
}
|
|
52
|
+
const hasTokens = (saved) => Boolean(saved && 'refresh_token' in saved && saved.refresh_token && 'access_token' in saved && saved.access_token);
|
|
53
|
+
export function saveCredentials(env, account) {
|
|
54
|
+
writePrivate(env, credentialsFile(env), JSON.stringify(account, null, 2) + '\n');
|
|
55
|
+
}
|
|
56
|
+
function dropTokens(env, account) {
|
|
57
|
+
const { email, issuer, subject, client_id, ext_agent_host_id } = account;
|
|
58
|
+
writePrivate(env, credentialsFile(env), JSON.stringify({ email, issuer, subject, client_id, ext_agent_host_id }, null, 2) + '\n');
|
|
59
|
+
}
|
|
60
|
+
export function readSession(env, now = Date.now()) {
|
|
61
|
+
const saved = readSaved(env);
|
|
62
|
+
if (!hasTokens(saved))
|
|
63
|
+
return { kind: 'signed-out' };
|
|
64
|
+
if (!saved.scopes.includes(PLAN_SCOPE))
|
|
65
|
+
return { kind: 'plan-off', account: saved };
|
|
66
|
+
const runsOut = Date.parse(saved.saved_at) + saved.expires_in * 1000;
|
|
67
|
+
return runsOut - now > REFRESH_EARLY ? { kind: 'signed-in', account: saved } : { kind: 'expired', account: saved };
|
|
68
|
+
}
|
|
69
|
+
const refreshing = new Map();
|
|
70
|
+
export async function currentSession(env, now = Date.now()) {
|
|
71
|
+
const session = readSession(env, now);
|
|
72
|
+
if (session.kind !== 'expired')
|
|
73
|
+
return session;
|
|
74
|
+
const file = credentialsFile(env);
|
|
75
|
+
const running = refreshing.get(file);
|
|
76
|
+
if (running)
|
|
77
|
+
return running;
|
|
78
|
+
const done = refreshUnderLock(env, session.account).finally(() => refreshing.delete(file));
|
|
79
|
+
refreshing.set(file, done);
|
|
80
|
+
return done;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Refreshes while holding `refresh.lock`, so one process at a time spends the
|
|
84
|
+
* refresh token. OpenAI replaces the refresh token on each refresh, so a second
|
|
85
|
+
* process refreshing with the old one could be told to sign in again
|
|
86
|
+
* (https://developers.openai.com/siwc/token-sharing-open-source/profiles-and-sessions#refreshing-tokens).
|
|
87
|
+
*/
|
|
88
|
+
async function refreshUnderLock(env, expired) {
|
|
89
|
+
const lock = await takeRefreshLock(env);
|
|
90
|
+
if (!lock)
|
|
91
|
+
return { kind: 'expired', account: expired };
|
|
92
|
+
try {
|
|
93
|
+
const latest = readSaved(env);
|
|
94
|
+
if (!hasTokens(latest))
|
|
95
|
+
return { kind: 'signed-out' };
|
|
96
|
+
if (latest.access_token !== expired.access_token)
|
|
97
|
+
return readSession(env);
|
|
98
|
+
return await refresh(env, latest);
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
releaseRefreshLock(env, lock);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function takeRefreshLock(env) {
|
|
105
|
+
const file = lockFile(env);
|
|
106
|
+
makePrivateFolder(env, folder(env));
|
|
107
|
+
const giveUpAt = Date.now() + LOCK_WAIT;
|
|
108
|
+
for (;;) {
|
|
109
|
+
const mine = { pid: process.pid, started_at: Date.now() };
|
|
110
|
+
try {
|
|
111
|
+
writeFileSync(file, JSON.stringify(mine) + '\n', { flag: 'wx', mode: 0o600 });
|
|
112
|
+
return mine;
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
if (err.code !== 'EEXIST')
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
if (lockIsStale(file)) {
|
|
119
|
+
rmSync(file, { force: true });
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (Date.now() >= giveUpAt)
|
|
123
|
+
return null;
|
|
124
|
+
await new Promise((r) => setTimeout(r, LOCK_POLL));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function lockIsStale(file) {
|
|
128
|
+
let text;
|
|
129
|
+
let modifiedAt;
|
|
130
|
+
try {
|
|
131
|
+
text = readFileSync(file, 'utf-8');
|
|
132
|
+
modifiedAt = statSync(file).mtimeMs;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
const lock = parseLock(text);
|
|
138
|
+
if (Date.now() - (lock?.started_at ?? modifiedAt) > LOCK_STALE_AFTER)
|
|
139
|
+
return true;
|
|
140
|
+
return lock !== null && !processRuns(lock.pid);
|
|
141
|
+
}
|
|
142
|
+
function parseLock(text) {
|
|
143
|
+
try {
|
|
144
|
+
const lock = JSON.parse(text);
|
|
145
|
+
return typeof lock.pid === 'number' && typeof lock.started_at === 'number' ? { pid: lock.pid, started_at: lock.started_at } : null;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Signal 0 checks that a process exists without touching it. EPERM means it exists but belongs to another user. */
|
|
152
|
+
function processRuns(pid) {
|
|
153
|
+
try {
|
|
154
|
+
process.kill(pid, 0);
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
return err.code === 'EPERM';
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
function releaseRefreshLock(env, mine) {
|
|
162
|
+
const file = lockFile(env);
|
|
163
|
+
let held;
|
|
164
|
+
try {
|
|
165
|
+
held = parseLock(readFileSync(file, 'utf-8'));
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (held?.pid === mine.pid && held.started_at === mine.started_at)
|
|
171
|
+
rmSync(file, { force: true });
|
|
172
|
+
}
|
|
173
|
+
async function refresh(env, account) {
|
|
174
|
+
let answer;
|
|
175
|
+
try {
|
|
176
|
+
answer = await fetch(OPENAI.token, {
|
|
177
|
+
method: 'POST',
|
|
178
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
179
|
+
body: new URLSearchParams({ grant_type: 'refresh_token', client_id: account.client_id, refresh_token: account.refresh_token, resource: OPENAI.resource }),
|
|
180
|
+
signal: AbortSignal.timeout(REFRESH_TIMEOUT),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
return { kind: 'refresh-failed', reason: 'could not reach auth.openai.com to refresh the ChatGPT sign-in' };
|
|
185
|
+
}
|
|
186
|
+
const body = (await answer.json().catch(() => ({})));
|
|
187
|
+
if (answer.ok && body.access_token && body.refresh_token) {
|
|
188
|
+
const next = { ...account, ...tokenFields(body, account.scopes), id_token: body.id_token ?? account.id_token };
|
|
189
|
+
saveCredentials(env, next);
|
|
190
|
+
return readSession(env);
|
|
191
|
+
}
|
|
192
|
+
if (body.error && DEAD_REFRESH.has(body.error)) {
|
|
193
|
+
dropTokens(env, account);
|
|
194
|
+
return { kind: 'refresh-failed', reason: `the ChatGPT sign-in ended (${body.error}); run phantom config chatgpt login` };
|
|
195
|
+
}
|
|
196
|
+
return { kind: 'refresh-failed', reason: `could not refresh the ChatGPT sign-in (HTTP ${answer.status}${body.error ? `, ${body.error}` : ''})` };
|
|
197
|
+
}
|
|
198
|
+
export function tokenFields(t, scopesBefore = []) {
|
|
199
|
+
return {
|
|
200
|
+
access_token: t.access_token,
|
|
201
|
+
refresh_token: t.refresh_token,
|
|
202
|
+
token_type: t.token_type ?? 'Bearer',
|
|
203
|
+
expires_in: t.expires_in,
|
|
204
|
+
scopes: t.scope ? t.scope.split(' ').filter(Boolean).sort() : scopesBefore,
|
|
205
|
+
saved_at: new Date().toISOString(),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
export async function checkIdToken(idToken, expect) {
|
|
209
|
+
const bad = (what) => die(`OpenAI's sign-in answer failed a check (${what}), so phantom did not save it. Run phantom config chatgpt login again.`, 'chatgpt_sign_in');
|
|
210
|
+
const [head, payload, signature] = idToken.split('.');
|
|
211
|
+
if (!head || !payload || !signature)
|
|
212
|
+
bad('ID token shape');
|
|
213
|
+
const header = JSON.parse(Buffer.from(head, 'base64url').toString());
|
|
214
|
+
if (header.alg !== 'RS256')
|
|
215
|
+
bad('ID token algorithm');
|
|
216
|
+
const { keys } = (await (await fetch(OPENAI.jwks, { signal: AbortSignal.timeout(30_000) })).json());
|
|
217
|
+
const jwk = keys.find((k) => k.kid === header.kid) ?? bad('ID token key');
|
|
218
|
+
if (!verify('RSA-SHA256', Buffer.from(`${head}.${payload}`), createPublicKey({ key: jwk, format: 'jwk' }), Buffer.from(signature, 'base64url')))
|
|
219
|
+
bad('ID token signature');
|
|
220
|
+
const claims = JSON.parse(Buffer.from(payload, 'base64url').toString());
|
|
221
|
+
if (claims.iss !== OPENAI.issuer)
|
|
222
|
+
bad('issuer');
|
|
223
|
+
if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).includes(expect.clientId))
|
|
224
|
+
bad('audience');
|
|
225
|
+
if (!claims.exp || claims.exp * 1000 <= Date.now())
|
|
226
|
+
bad('expiry');
|
|
227
|
+
if (claims.nonce !== expect.nonce)
|
|
228
|
+
bad('nonce');
|
|
229
|
+
if (!claims.sub)
|
|
230
|
+
bad('subject');
|
|
231
|
+
return { sub: claims.sub, email: claims.email ?? '' };
|
|
232
|
+
}
|
|
233
|
+
export async function signOut(env) {
|
|
234
|
+
const saved = readSaved(env);
|
|
235
|
+
if (!hasTokens(saved))
|
|
236
|
+
return { revoked: true };
|
|
237
|
+
let revoked = false;
|
|
238
|
+
for (let attempt = 0; attempt < 3 && !revoked; attempt++) {
|
|
239
|
+
if (attempt)
|
|
240
|
+
await new Promise((r) => setTimeout(r, 250 * attempt));
|
|
241
|
+
const answer = await fetch(OPENAI.revoke, {
|
|
242
|
+
method: 'POST',
|
|
243
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
244
|
+
body: new URLSearchParams({ token: saved.refresh_token, token_type_hint: 'refresh_token', client_id: saved.client_id }),
|
|
245
|
+
signal: AbortSignal.timeout(30_000),
|
|
246
|
+
}).catch(() => null);
|
|
247
|
+
revoked = answer?.status === 200;
|
|
248
|
+
if (answer && answer.status < 500 && !revoked)
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
dropTokens(env, saved);
|
|
252
|
+
return { revoked };
|
|
253
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Env } from '../core/state.mts';
|
|
2
|
+
import type { Paint } from '../core/style.mts';
|
|
3
|
+
import { type AccountKindName } from '../local/accounts.mts';
|
|
4
|
+
import { type LocalConfig } from '../local/config.mts';
|
|
5
|
+
export type AccountState = {
|
|
6
|
+
ready: boolean;
|
|
7
|
+
word: string;
|
|
8
|
+
};
|
|
9
|
+
export type AccountView = {
|
|
10
|
+
name: string;
|
|
11
|
+
kind: AccountKindName;
|
|
12
|
+
state: AccountState;
|
|
13
|
+
from: string | null;
|
|
14
|
+
hasKey: boolean;
|
|
15
|
+
tiers: string[];
|
|
16
|
+
requests: number | null;
|
|
17
|
+
};
|
|
18
|
+
export declare function readAccounts(env: Env, config: LocalConfig | null, now?: number): AccountView[];
|
|
19
|
+
export declare const cut: (text: string, width: number) => string;
|
|
20
|
+
export declare function accountsTable(accounts: AccountView[], p: Paint, width: number): string[];
|
|
21
|
+
export declare function routingLine(config: LocalConfig, accounts: AccountView[]): string;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// docs: The PROVIDERS table in `phantom config`, and the routing line over the agent picker: one row per account in local.json (or the starter's, before there is one) with its kind, whether its key is found or ChatGPT is signed in, where the key comes from, which tiers use it, and its requests in the last 24 hours from requests.jsonl. Reads no network and never holds a key in what it returns
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { readSession } from "../chatgpt/session.mjs";
|
|
4
|
+
import { ACCOUNT_KINDS } from "../local/accounts.mjs";
|
|
5
|
+
import { STARTER, TIERS, TIER_NAME } from "../local/config.mjs";
|
|
6
|
+
import { keyRow, shown } from "../local/keys.mjs";
|
|
7
|
+
import { readRequests } from "../local/report.mjs";
|
|
8
|
+
import { requestLogPaths } from "../local/request-log.mjs";
|
|
9
|
+
function fromText(source) {
|
|
10
|
+
if (source.from === 'saved')
|
|
11
|
+
return 'saved in phantom';
|
|
12
|
+
if (source.from === 'env')
|
|
13
|
+
return `env ${source.name}`;
|
|
14
|
+
return `Keychain "${shown(source.service)}"`;
|
|
15
|
+
}
|
|
16
|
+
function tiersOf(config, name) {
|
|
17
|
+
return TIERS.flatMap((t) => {
|
|
18
|
+
const entry = config.tiers[t];
|
|
19
|
+
return [...(entry.account === name ? [`${TIER_NAME[t]} (${entry.model})`] : []), ...(entry.fallback?.account === name ? [`${TIER_NAME[t]} fallback (${entry.fallback.model})`] : [])];
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
export function readAccounts(env, config, now = Date.now()) {
|
|
23
|
+
const session = readSession(env);
|
|
24
|
+
const log = requestLogPaths(env);
|
|
25
|
+
const logged = config?.log && (existsSync(log.current) || existsSync(log.previous));
|
|
26
|
+
const recent = logged ? readRequests(env).filter((r) => now - Date.parse(r.at) < 24 * 3600_000) : [];
|
|
27
|
+
return Object.entries((config ?? STARTER).accounts).map(([name, account]) => {
|
|
28
|
+
const tiers = tiersOf(config ?? STARTER, name);
|
|
29
|
+
const requests = logged ? recent.filter((r) => r.account === name).length : null;
|
|
30
|
+
if (account.kind === 'chatgpt-plan') {
|
|
31
|
+
const state = session.kind === 'signed-out' ? { ready: false, word: 'not signed in' } : session.kind === 'plan-off' ? { ready: false, word: 'plan use off' } : { ready: true, word: 'signed in' };
|
|
32
|
+
return { name, kind: account.kind, state, from: session.kind === 'signed-out' ? null : session.account.email, hasKey: false, tiers, requests };
|
|
33
|
+
}
|
|
34
|
+
const row = keyRow(env, name, account);
|
|
35
|
+
const state = row.found ? { ready: true, word: 'key found' } : { ready: false, word: account.key ? 'no key found' : 'no key yet' };
|
|
36
|
+
return { name, kind: account.kind, state, from: account.key ? fromText(account.key) : null, hasKey: Boolean(account.key), tiers, requests };
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
export const cut = (text, width) => (text.length <= width ? text : text.slice(0, Math.max(0, width - 1)) + '…');
|
|
40
|
+
export function accountsTable(accounts, p, width) {
|
|
41
|
+
const counted = accounts.some((a) => a.requests !== null);
|
|
42
|
+
const columns = [
|
|
43
|
+
{ key: 'name', head: 'account', cells: accounts.map((a) => ({ text: shown(a.name), color: p.bold })) },
|
|
44
|
+
{ key: 'kind', head: 'kind', cells: accounts.map((a) => ({ text: ACCOUNT_KINDS[a.kind].label })) },
|
|
45
|
+
{ key: 'state', head: 'state', cells: accounts.map((a) => (a.state.ready ? { text: `✓ ${a.state.word}`, color: p.lime } : { text: `! ${a.state.word}`, color: p.yellow })) },
|
|
46
|
+
{ key: 'from', head: 'from', cells: accounts.map((a) => ({ text: a.from ?? '–', color: p.dim })) },
|
|
47
|
+
{ key: 'tiers', head: 'tiers', cells: accounts.map((a) => (a.tiers.length ? { text: a.tiers.join(', ') } : { text: '– not used by a tier', color: p.dim })) },
|
|
48
|
+
...(counted ? [{ key: 'today', head: '24h', right: true, cells: accounts.map((a) => ({ text: a.requests === null ? '' : String(a.requests) })) }] : []),
|
|
49
|
+
];
|
|
50
|
+
const widthOf = (c) => Math.max(c.head.length, ...c.cells.map((cell) => cell.text.length));
|
|
51
|
+
const widths = new Map(columns.map((c) => [c.key, widthOf(c)]));
|
|
52
|
+
let shownColumns = columns;
|
|
53
|
+
const total = () => 2 + shownColumns.reduce((sum, c) => sum + widths.get(c.key), 0) + 2 * (shownColumns.length - 1);
|
|
54
|
+
const drop = (key) => {
|
|
55
|
+
if (total() > width)
|
|
56
|
+
shownColumns = shownColumns.filter((c) => c.key !== key);
|
|
57
|
+
};
|
|
58
|
+
const shrinkTiers = (least) => {
|
|
59
|
+
if (total() > width)
|
|
60
|
+
widths.set('tiers', Math.max(Math.min(least, widths.get('tiers')), widths.get('tiers') - (total() - width)));
|
|
61
|
+
};
|
|
62
|
+
shrinkTiers(30);
|
|
63
|
+
drop('from');
|
|
64
|
+
shrinkTiers(24);
|
|
65
|
+
drop('kind');
|
|
66
|
+
shrinkTiers(8);
|
|
67
|
+
drop('tiers');
|
|
68
|
+
const line = (cells) => ' ' +
|
|
69
|
+
cells
|
|
70
|
+
.map((cell, k) => {
|
|
71
|
+
const c = shownColumns[k];
|
|
72
|
+
const w = widths.get(c.key);
|
|
73
|
+
const text = cut(cell.text, w);
|
|
74
|
+
const padded = c.right ? text.padStart(w) : k === cells.length - 1 ? text : text.padEnd(w);
|
|
75
|
+
return cell.color ? cell.color(padded) : padded;
|
|
76
|
+
})
|
|
77
|
+
.join(' ');
|
|
78
|
+
const head = line(shownColumns.map((c) => ({ text: c.head, color: p.dim })));
|
|
79
|
+
const rows = accounts.map((_, i) => line(shownColumns.map((c) => c.cells[i])));
|
|
80
|
+
return [head, ...rows];
|
|
81
|
+
}
|
|
82
|
+
function need(a) {
|
|
83
|
+
if (a.state.ready)
|
|
84
|
+
return null;
|
|
85
|
+
if (a.kind !== 'chatgpt-plan')
|
|
86
|
+
return 'needs a key';
|
|
87
|
+
return a.state.word === 'plan use off' ? 'needs plan use allowed' : 'needs sign-in';
|
|
88
|
+
}
|
|
89
|
+
export function routingLine(config, accounts) {
|
|
90
|
+
const tiers = TIERS.map((t) => `${TIER_NAME[t]} ${config.tiers[t].model} on ${shown(config.tiers[t].account)}`);
|
|
91
|
+
const needs = accounts.filter((a) => a.tiers.length).flatMap((a) => {
|
|
92
|
+
const what = need(a);
|
|
93
|
+
return what ? [`${shown(a.name)} ${what}`] : [];
|
|
94
|
+
});
|
|
95
|
+
return [...tiers, needs.length ? `! ${needs.join(', ')}` : '✓ ready'].join(' · ');
|
|
96
|
+
}
|
package/dist/cli/app.d.mts
CHANGED
|
@@ -1,25 +1,5 @@
|
|
|
1
1
|
import type { Env } from '../core/state.mts';
|
|
2
|
-
import { type
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
} | {
|
|
7
|
-
open: 'keys' | 'more' | 'commands';
|
|
8
|
-
};
|
|
9
|
-
/** What the app knows about this computer, without asking the network: signed in, set up, which agents are installed. */
|
|
10
|
-
export type AppState = {
|
|
11
|
-
signedIn: boolean;
|
|
12
|
-
setUp: boolean;
|
|
13
|
-
installed: (bin: string) => boolean;
|
|
14
|
-
};
|
|
15
|
-
/** The main menu for the state this computer is in. */
|
|
16
|
-
export declare function mainMenu(s: AppState): Choice<Action>[];
|
|
17
|
-
/** After a command's result: the next steps that fit it, as choices, so nobody types the "→" line. */
|
|
18
|
-
export declare function nextSteps(ran: string[]): Choice<string[]>[];
|
|
19
|
-
/**
|
|
20
|
-
* Runs the app until Quit, Esc on the main menu, or Ctrl+C. `runCommand` runs
|
|
21
|
-
* one command the way `phantom <args>` would and returns its exit code; the app
|
|
22
|
-
* passes it `fromMenu`, so a command's first Esc comes back here.
|
|
23
|
-
*/
|
|
24
|
-
export declare function runApp(env: Env, pick: PickIo, write: (s: string) => void, runCommand: (argv: string[]) => Promise<number>, installed?: (bin: string) => boolean): Promise<number>;
|
|
25
|
-
export {};
|
|
2
|
+
import { type PickIo } from '../core/pick.mts';
|
|
3
|
+
export type RunCommand = (argv: string[]) => Promise<number>;
|
|
4
|
+
export declare function runPicker(env: Env, pick: PickIo, write: (s: string) => void, runCommand: RunCommand, installed?: (bin: string) => boolean): Promise<number>;
|
|
5
|
+
export declare function runConfig(env: Env, pick: PickIo, write: (s: string) => void, runCommand: RunCommand): Promise<number>;
|