@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,99 @@
|
|
|
1
|
+
// docs: A copy of phantom-1's failure-word reader (routers/phantom-1/runtime/src/failure-signs.ts) for phantom-1 on this computer: reads one chat request for signs that the last try failed and returns a label, never the text. The CLI can't import the original (a private package that ships TypeScript), so change both together. One rule differs: here a hyphen joined to the next word (error-handling) does not end a clause
|
|
2
|
+
const PERSON_PHRASES = [
|
|
3
|
+
'still broken',
|
|
4
|
+
'still not working',
|
|
5
|
+
"still doesn't work",
|
|
6
|
+
"didn't work",
|
|
7
|
+
'not fixed',
|
|
8
|
+
'same error',
|
|
9
|
+
"that's not what i asked",
|
|
10
|
+
'try again',
|
|
11
|
+
'nothing happens',
|
|
12
|
+
'does nothing',
|
|
13
|
+
'no change',
|
|
14
|
+
];
|
|
15
|
+
const AGENT_PHRASES = [
|
|
16
|
+
'still fails',
|
|
17
|
+
'still failing',
|
|
18
|
+
"didn't work",
|
|
19
|
+
"didn't fix",
|
|
20
|
+
'the same error',
|
|
21
|
+
];
|
|
22
|
+
const AGENT_PLANS = ['let me try a different approach', 'let me try another approach'];
|
|
23
|
+
export function failureSign(messages, format) {
|
|
24
|
+
const turns = typedTurns(messages, format);
|
|
25
|
+
const latest = latestPersonTurn(turns);
|
|
26
|
+
if (latest === -1)
|
|
27
|
+
return null;
|
|
28
|
+
const agentTriedBefore = turns.slice(0, latest).some((turn) => turn.who === 'agent');
|
|
29
|
+
if (agentTriedBefore && says(turns[latest].text, PERSON_PATTERNS))
|
|
30
|
+
return 'said-failed';
|
|
31
|
+
const agentSinceThen = turns.slice(latest + 1).filter((turn) => turn.who === 'agent');
|
|
32
|
+
if (agentSinceThen.some((turn) => says(turn.text, AGENT_PATTERNS) || says(turn.text, AGENT_PLAN_PATTERNS)))
|
|
33
|
+
return 'agent-failed';
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
function latestPersonTurn(turns) {
|
|
37
|
+
for (let index = turns.length - 1; index >= 0; index--) {
|
|
38
|
+
if (turns[index].who === 'person')
|
|
39
|
+
return index;
|
|
40
|
+
}
|
|
41
|
+
return -1;
|
|
42
|
+
}
|
|
43
|
+
const REPORT_ENDINGS = ['again', 'now', 'too', 'still', 'anymore', 'at all', 'for me', 'when i', 'if i', 'because', 'since', 'but', 'so'];
|
|
44
|
+
const CLAUSE_MARKS = '(?:[\\n.,;:!?…—–)\\]"]|-(?![\\p{L}\\p{N}]))';
|
|
45
|
+
function wholeWords(phrase) {
|
|
46
|
+
const escaped = phrase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/ /g, '\\s+');
|
|
47
|
+
return `(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`;
|
|
48
|
+
}
|
|
49
|
+
function endsItsClause(phrase) {
|
|
50
|
+
const endings = REPORT_ENDINGS.map(wholeWords).join('|');
|
|
51
|
+
return new RegExp(`${wholeWords(phrase)}(?=[ \\t]*(?:$|${CLAUSE_MARKS})|[ \\t]+-|[ \\t]+(?:${endings}))`, 'u');
|
|
52
|
+
}
|
|
53
|
+
const PERSON_PATTERNS = PERSON_PHRASES.map(endsItsClause);
|
|
54
|
+
const AGENT_PATTERNS = AGENT_PHRASES.map(endsItsClause);
|
|
55
|
+
const AGENT_PLAN_PATTERNS = AGENT_PLANS.map((phrase) => new RegExp(wholeWords(phrase), 'u'));
|
|
56
|
+
function says(text, patterns) {
|
|
57
|
+
const plain = typedWords(text);
|
|
58
|
+
return patterns.some((pattern) => pattern.test(plain));
|
|
59
|
+
}
|
|
60
|
+
function typedWords(text) {
|
|
61
|
+
return text
|
|
62
|
+
.replace(/<system-reminder>[\s\S]*?(<\/system-reminder>|$)/gi, ' ')
|
|
63
|
+
.replace(/```[\s\S]*?(```|$)/g, ' ')
|
|
64
|
+
.replace(/^[ \t]*>.*$/gm, ' ')
|
|
65
|
+
.toLowerCase()
|
|
66
|
+
.replace(/[‘’]/g, "'");
|
|
67
|
+
}
|
|
68
|
+
function typedTurns(messages, format) {
|
|
69
|
+
if (!Array.isArray(messages))
|
|
70
|
+
return [];
|
|
71
|
+
return messages.flatMap((message) => turnOf(message, format));
|
|
72
|
+
}
|
|
73
|
+
function turnOf(message, format) {
|
|
74
|
+
if (!message || typeof message !== 'object')
|
|
75
|
+
return [];
|
|
76
|
+
const { role, content } = message;
|
|
77
|
+
if (role === 'assistant')
|
|
78
|
+
return [{ who: 'agent', text: textOf(content) }];
|
|
79
|
+
if (role !== 'user')
|
|
80
|
+
return [];
|
|
81
|
+
if (format === 'anthropic_messages' && holdsOnlyToolResults(content))
|
|
82
|
+
return [];
|
|
83
|
+
return [{ who: 'person', text: textOf(content) }];
|
|
84
|
+
}
|
|
85
|
+
function holdsOnlyToolResults(content) {
|
|
86
|
+
return (Array.isArray(content) &&
|
|
87
|
+
content.length > 0 &&
|
|
88
|
+
content.every((block) => !!block && typeof block === 'object' && block.type === 'tool_result'));
|
|
89
|
+
}
|
|
90
|
+
function textOf(content) {
|
|
91
|
+
if (typeof content === 'string')
|
|
92
|
+
return content;
|
|
93
|
+
if (!Array.isArray(content))
|
|
94
|
+
return '';
|
|
95
|
+
return content
|
|
96
|
+
.map((part) => (part && typeof part === 'object' && typeof part.text === 'string' ? part.text : ''))
|
|
97
|
+
.filter(Boolean)
|
|
98
|
+
.join('\n');
|
|
99
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type CommandInput } from '../core/helpers.mts';
|
|
2
|
+
import { type PickIo } from '../core/pick.mts';
|
|
3
|
+
import { type Env } from '../core/state.mts';
|
|
4
|
+
import { type KeyKindName } from './accounts.mts';
|
|
5
|
+
import { type KeyAccount, type KeySource } from './config.mts';
|
|
6
|
+
export declare function savedKeyPath(env: Env, name: string): string;
|
|
7
|
+
type KeyMissing = 'no-source' | 'env-unset' | 'saved-gone' | 'saved-unreadable' | 'keychain-unreadable' | 'keychain-not-macos';
|
|
8
|
+
type KeyLookup = {
|
|
9
|
+
found: true;
|
|
10
|
+
key: string;
|
|
11
|
+
} | {
|
|
12
|
+
found: false;
|
|
13
|
+
missing: KeyMissing;
|
|
14
|
+
};
|
|
15
|
+
export declare function resolveKey(env: Env, name: string, account: KeyAccount): KeyLookup;
|
|
16
|
+
export declare function shown(name: string): string;
|
|
17
|
+
export declare function missingText(account: KeyAccount, why: KeyMissing): string;
|
|
18
|
+
export declare const fixCommand: (name: string) => string;
|
|
19
|
+
type KeyRow = {
|
|
20
|
+
account: string;
|
|
21
|
+
kind: KeyKindName;
|
|
22
|
+
source: KeySource | null;
|
|
23
|
+
found: boolean;
|
|
24
|
+
problem?: string;
|
|
25
|
+
fix?: string;
|
|
26
|
+
};
|
|
27
|
+
export declare function keyRow(env: Env, name: string, account: KeyAccount): KeyRow;
|
|
28
|
+
export declare function keyRowText(row: KeyRow): string;
|
|
29
|
+
export declare function noKeyText(name: string, account: KeyAccount, why: KeyMissing): string;
|
|
30
|
+
export declare function askKey(io: PickIo, question: string): Promise<string | null>;
|
|
31
|
+
export declare function keysCommand(input: CommandInput): Promise<number>;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// docs: Where phantom-1 on this computer gets each key account's key, and `phantom config key`: `resolveKey` is the one place every caller (the server, `config models`, the tier settings, `config show`) reads a key from phantom's saved store, an environment variable or a macOS Keychain item, getting the key or a reason it is missing. The command saves a key with hidden typing or from stdin (`key set`), points an account at a Keychain item phantom didn't write (`key use-keychain`), and forgets one (`key rm`). No output holds a key
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { die } from "../core/errors.mjs";
|
|
6
|
+
import { out, pickIo } from "../core/helpers.mjs";
|
|
7
|
+
import { Cancelled, keyboard } from "../core/pick.mjs";
|
|
8
|
+
import { keychainOn, readSecret, removeSecret, writeSecret } from "../core/secrets.mjs";
|
|
9
|
+
import { stateDir } from "../core/state.mjs";
|
|
10
|
+
import { colorOn, paint } from "../core/style.mjs";
|
|
11
|
+
import { ACCOUNT_KINDS, kindNamed } from "./accounts.mjs";
|
|
12
|
+
import { isAccountName, readLocalConfig, savedOrStarter, writeLocalConfig } from "./config.mjs";
|
|
13
|
+
export function savedKeyPath(env, name) {
|
|
14
|
+
return path.join(stateDir(env), 'local', 'keys', name);
|
|
15
|
+
}
|
|
16
|
+
function readKeychainItem(service, account) {
|
|
17
|
+
const args = ['find-generic-password', '-s', service, ...(account ? ['-a', account] : []), '-w'];
|
|
18
|
+
const r = spawnSync('/usr/bin/security', args, { encoding: 'utf-8' });
|
|
19
|
+
const value = r.status === 0 ? r.stdout.trim() : '';
|
|
20
|
+
return value || null;
|
|
21
|
+
}
|
|
22
|
+
export function resolveKey(env, name, account) {
|
|
23
|
+
const source = account.key;
|
|
24
|
+
const missing = (why) => ({ found: false, missing: why });
|
|
25
|
+
if (!source)
|
|
26
|
+
return missing('no-source');
|
|
27
|
+
switch (source.from) {
|
|
28
|
+
case 'env': {
|
|
29
|
+
const key = env[source.name]?.trim();
|
|
30
|
+
return key ? { found: true, key } : missing('env-unset');
|
|
31
|
+
}
|
|
32
|
+
case 'saved': {
|
|
33
|
+
const file = savedKeyPath(env, name);
|
|
34
|
+
if (!existsSync(file))
|
|
35
|
+
return missing('saved-gone');
|
|
36
|
+
try {
|
|
37
|
+
const key = readSecret(env, file).trim();
|
|
38
|
+
return key ? { found: true, key } : missing('saved-gone');
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return missing('saved-unreadable');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
case 'keychain': {
|
|
45
|
+
if (process.platform !== 'darwin')
|
|
46
|
+
return missing('keychain-not-macos');
|
|
47
|
+
const key = readKeychainItem(source.service, source.account);
|
|
48
|
+
return key ? { found: true, key } : missing('keychain-unreadable');
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function describeSource(source) {
|
|
53
|
+
if (!source)
|
|
54
|
+
return 'no key source';
|
|
55
|
+
if (source.from === 'saved')
|
|
56
|
+
return 'saved in phantom';
|
|
57
|
+
if (source.from === 'env')
|
|
58
|
+
return `environment variable ${source.name}`;
|
|
59
|
+
return keychainItemName(source);
|
|
60
|
+
}
|
|
61
|
+
const keychainItemName = (item) => `Keychain item "${shown(item.service)}"${item.account ? ` (account ${shown(item.account)})` : ''}`;
|
|
62
|
+
export function shown(name) {
|
|
63
|
+
const masked = name.replace(/sk-phantom-[A-Za-z0-9_-]+/g, 'sk-phantom-****').replace(/sk-ant-[A-Za-z0-9_-]+/g, 'sk-ant-****');
|
|
64
|
+
const randomLooking = (part) => part.length >= 12 && /[0-9]/.test(part) && /[A-Za-z]/.test(part);
|
|
65
|
+
return masked.replace(/[A-Za-z0-9._-]{24,}/g, (word) => (word.split(/[-.]/).some(randomLooking) ? `${word.slice(0, 4)}****` : word));
|
|
66
|
+
}
|
|
67
|
+
export function missingText(account, why) {
|
|
68
|
+
const source = account.key;
|
|
69
|
+
switch (why) {
|
|
70
|
+
case 'no-source':
|
|
71
|
+
return 'no key is set up';
|
|
72
|
+
case 'env-unset':
|
|
73
|
+
return `${source?.from === 'env' ? source.name : 'its variable'} is not set in this shell`;
|
|
74
|
+
case 'saved-gone':
|
|
75
|
+
return 'the saved key is gone';
|
|
76
|
+
case 'saved-unreadable':
|
|
77
|
+
return "the saved key's Keychain item could not be read (if the Keychain is locked, run security unlock-keychain)";
|
|
78
|
+
case 'keychain-unreadable':
|
|
79
|
+
return `the ${source?.from === 'keychain' ? keychainItemName(source) : 'Keychain item'} could not be read: it isn't there, or the Keychain is locked`;
|
|
80
|
+
case 'keychain-not-macos':
|
|
81
|
+
return 'a Keychain item is read only on macOS';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export const fixCommand = (name) => `phantom config key set ${shown(name)}`;
|
|
85
|
+
export function keyRow(env, name, account) {
|
|
86
|
+
const lookup = resolveKey(env, name, account);
|
|
87
|
+
const row = { account: name, kind: account.kind, source: account.key };
|
|
88
|
+
return lookup.found ? { ...row, found: true } : { ...row, found: false, problem: missingText(account, lookup.missing), fix: fixCommand(name) };
|
|
89
|
+
}
|
|
90
|
+
export function keyRowText(row) {
|
|
91
|
+
const head = `${shown(row.account)} (${ACCOUNT_KINDS[row.kind].label}): `;
|
|
92
|
+
if (row.found)
|
|
93
|
+
return `${head}${describeSource(row.source)}, found`;
|
|
94
|
+
return `${head}${row.source ? `${describeSource(row.source)}, ` : ''}not found, ${row.problem}. Run ${row.fix}`;
|
|
95
|
+
}
|
|
96
|
+
export function noKeyText(name, account, why) {
|
|
97
|
+
return `No key for ${shown(name)}: ${missingText(account, why)}. Run ${fixCommand(name)}`;
|
|
98
|
+
}
|
|
99
|
+
const MOVE_KEYS = new Set(['up', 'down', 'left', 'right', 'tab', 'shift-tab', 'home', 'pageup', 'pagedown', 'insert']);
|
|
100
|
+
export async function askKey(io, question) {
|
|
101
|
+
const p = paint(io.env, colorOn(io.env, true));
|
|
102
|
+
const keys = (io.keys ?? keyboard)();
|
|
103
|
+
let text = '';
|
|
104
|
+
const draw = (note = 'paste or type · enter go on · esc back') => {
|
|
105
|
+
const width = (io.columns ?? 80) - 1;
|
|
106
|
+
const head = ` ? ${question} `;
|
|
107
|
+
const fits = width - head.length - note.length - 2 >= 8;
|
|
108
|
+
const room = width - head.length - (fits ? note.length + 2 : 0);
|
|
109
|
+
const dots = '•'.repeat(Math.max(0, Math.min(text.length, 48, room)));
|
|
110
|
+
io.write(`\r\x1b[J ${p.lime('?')} ${p.bold(question)} ${dots}${fits ? ` ${p.dim(note)}` : ''}`);
|
|
111
|
+
};
|
|
112
|
+
try {
|
|
113
|
+
draw();
|
|
114
|
+
for (;;) {
|
|
115
|
+
const key = await keys.next();
|
|
116
|
+
if (key === 'return') {
|
|
117
|
+
if (text.trim())
|
|
118
|
+
return text.trim();
|
|
119
|
+
draw('nothing typed yet');
|
|
120
|
+
}
|
|
121
|
+
else if (key === 'escape' || key === 'end')
|
|
122
|
+
return null;
|
|
123
|
+
else if (key === 'ctrl-c')
|
|
124
|
+
throw new Cancelled();
|
|
125
|
+
else {
|
|
126
|
+
if (key === 'backspace' || key === 'delete')
|
|
127
|
+
text = text.slice(0, -1);
|
|
128
|
+
else if (key === 'space')
|
|
129
|
+
text += ' ';
|
|
130
|
+
else if (!MOVE_KEYS.has(key))
|
|
131
|
+
text += key;
|
|
132
|
+
draw();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
io.write('\r\x1b[J');
|
|
138
|
+
keys.close();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function checkedKey(raw) {
|
|
142
|
+
const key = raw.trim();
|
|
143
|
+
if (!key)
|
|
144
|
+
die('No key was given, so nothing was saved.', 'local_key_empty');
|
|
145
|
+
if (/\s/.test(key))
|
|
146
|
+
die('A key is one line with no spaces. Nothing was saved.', 'local_key_invalid');
|
|
147
|
+
return key;
|
|
148
|
+
}
|
|
149
|
+
function configWith(env, name) {
|
|
150
|
+
const config = structuredClone(savedOrStarter(env));
|
|
151
|
+
const there = Object.hasOwn(config.accounts, name) ? config.accounts[name] : undefined;
|
|
152
|
+
if (there?.kind === 'chatgpt-plan')
|
|
153
|
+
die(`${shown(name)} is a ChatGPT plan account: it uses the sign-in from phantom config chatgpt login, not a key.`, 'local_account_no_key');
|
|
154
|
+
if (there)
|
|
155
|
+
return { config, account: there };
|
|
156
|
+
const kind = kindNamed(name);
|
|
157
|
+
if (!kind || kind === 'chatgpt-plan') {
|
|
158
|
+
const keyAccounts = Object.keys(config.accounts).filter((a) => config.accounts[a].kind !== 'chatgpt-plan');
|
|
159
|
+
die(`No key account "${shown(name)}" in local.json. It has ${keyAccounts.map(shown).join(', ') || 'none'}; gateway and zai can be added.`, 'local_account_unknown');
|
|
160
|
+
}
|
|
161
|
+
const account = { kind, key: null };
|
|
162
|
+
config.accounts[name] = account;
|
|
163
|
+
return { config, account };
|
|
164
|
+
}
|
|
165
|
+
function pointAt(env, config, name, key) {
|
|
166
|
+
const account = config.accounts[name];
|
|
167
|
+
account.key = key;
|
|
168
|
+
writeLocalConfig(env, config);
|
|
169
|
+
const file = savedKeyPath(env, name);
|
|
170
|
+
if (key?.from !== 'saved' && existsSync(file))
|
|
171
|
+
removeSecret(file);
|
|
172
|
+
return account;
|
|
173
|
+
}
|
|
174
|
+
export async function keysCommand(input) {
|
|
175
|
+
const { env, io, argv, flags, table } = input;
|
|
176
|
+
const action = argv[2] !== undefined && !argv[2].startsWith('--') ? argv[2] : undefined;
|
|
177
|
+
const name = argv[3] !== undefined && !argv[3].startsWith('--') ? argv[3] : undefined;
|
|
178
|
+
const show = (row, line) => out(row, table, () => line, io.stdout);
|
|
179
|
+
if (!action || !['set', 'use-keychain', 'rm'].includes(action))
|
|
180
|
+
die('phantom config key takes set, use-keychain or rm, then an account. phantom config show lists each key account. See phantom config --help.', 'local_keys_usage');
|
|
181
|
+
if (!name)
|
|
182
|
+
die(`Name the account: phantom config key ${action} <account>, such as gateway or zai.`, 'local_keys_usage');
|
|
183
|
+
if (!isAccountName(name))
|
|
184
|
+
die(`"${shown(name)}" is not an account name: a name is letters, digits, - and _.`, 'local_keys_usage');
|
|
185
|
+
if (action === 'set') {
|
|
186
|
+
if (argv[4] !== undefined && !argv[4].startsWith('--'))
|
|
187
|
+
die(`Don't type the key on the command line, where shell history keeps it. Run ${fixCommand(name)} and paste it when asked, or pipe it in with --stdin.`, 'local_keys_usage');
|
|
188
|
+
const { account } = configWith(env, name);
|
|
189
|
+
let raw;
|
|
190
|
+
if (flags['stdin'] !== undefined)
|
|
191
|
+
raw = await readStdin();
|
|
192
|
+
else {
|
|
193
|
+
const pick = pickIo(input);
|
|
194
|
+
if (!pick)
|
|
195
|
+
die(`${fixCommand(name)} asks for the key at a terminal. In a script, pipe it in: ... | ${fixCommand(name)} --stdin`, 'local_keys_usage');
|
|
196
|
+
raw = await askKey(pick, `Paste the ${ACCOUNT_KINDS[account.kind].label} key`);
|
|
197
|
+
if (raw === null)
|
|
198
|
+
die('Nothing was saved.', 'local_keys_cancelled');
|
|
199
|
+
}
|
|
200
|
+
const key = checkedKey(raw);
|
|
201
|
+
const { config } = configWith(env, name);
|
|
202
|
+
writeSecret(env, savedKeyPath(env, name), key);
|
|
203
|
+
show(keyRow(env, name, pointAt(env, config, name, { from: 'saved' })), `Saved the key for ${shown(name)} in ${keychainOn(env) ? 'the macOS Keychain' : 'a file only you can read'}. phantom reads it from there.`);
|
|
204
|
+
return 0;
|
|
205
|
+
}
|
|
206
|
+
if (action === 'use-keychain') {
|
|
207
|
+
const service = flags['service'];
|
|
208
|
+
const itemAccount = flags['keychain-account'];
|
|
209
|
+
if (typeof service !== 'string' || !service)
|
|
210
|
+
die(`Name the item: phantom config key use-keychain ${shown(name)} --service <name> [--keychain-account <name>].`, 'local_keys_usage');
|
|
211
|
+
if (itemAccount === true || itemAccount === '')
|
|
212
|
+
die('--keychain-account needs a name.', 'local_keys_usage');
|
|
213
|
+
if (process.platform !== 'darwin')
|
|
214
|
+
die(`A Keychain item can be used only on macOS. Save the key in phantom instead: ${fixCommand(name)}`, 'local_keychain_macos_only');
|
|
215
|
+
const item = itemAccount === undefined ? { from: 'keychain', service } : { from: 'keychain', service, account: itemAccount };
|
|
216
|
+
const { config } = configWith(env, name);
|
|
217
|
+
if (readKeychainItem(service, itemAccount) === null) {
|
|
218
|
+
die(`Could not read the ${keychainItemName(item)}: it isn't there, or the Keychain is locked. Check it with: security find-generic-password -s ${shown(service)}${itemAccount ? ` -a ${shown(itemAccount)}` : ''}. local.json is unchanged.`, 'local_keychain_unreadable');
|
|
219
|
+
}
|
|
220
|
+
const account = pointAt(env, config, name, item);
|
|
221
|
+
show(keyRow(env, name, account), `${shown(name)} reads its key from the ${keychainItemName(item)}. It can be read. phantom keeps no copy.`);
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
224
|
+
const config = readLocalConfig(env);
|
|
225
|
+
const there = Object.hasOwn(config.accounts, name) ? config.accounts[name] : undefined;
|
|
226
|
+
if (!there || there.kind === 'chatgpt-plan')
|
|
227
|
+
die(`No key account "${shown(name)}" in local.json.`, 'local_account_unknown');
|
|
228
|
+
const before = there.key;
|
|
229
|
+
const account = pointAt(env, config, name, null);
|
|
230
|
+
const kept = before?.from === 'keychain' ? ` The ${keychainItemName(before)} stays; phantom no longer reads it.` : '';
|
|
231
|
+
show(keyRow(env, name, account), `${shown(name)} has no key now.${kept} ${fixCommand(name)} gives it one.`);
|
|
232
|
+
return 0;
|
|
233
|
+
}
|
|
234
|
+
async function readStdin() {
|
|
235
|
+
let text = '';
|
|
236
|
+
for await (const chunk of process.stdin)
|
|
237
|
+
text += String(chunk);
|
|
238
|
+
return text;
|
|
239
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Env } from '../core/state.mts';
|
|
2
|
+
import { type AccountKindName } from './accounts.mts';
|
|
3
|
+
import type { Account, LocalConfig, Target } from './config.mts';
|
|
4
|
+
import type { ImageReaders, ReadsImages } from './decide.mts';
|
|
5
|
+
type ModelEntry = {
|
|
6
|
+
id: string;
|
|
7
|
+
name?: string;
|
|
8
|
+
hidden?: true;
|
|
9
|
+
images?: boolean;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The Gateway's models: GET https://ai-gateway.vercel.sh/v1/models
|
|
13
|
+
* (https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-chat-completions#list-models),
|
|
14
|
+
* `data[].id` in the Gateway's order. The page shows id, object, created and
|
|
15
|
+
* owned_by; the live answer also carries `name` and `type` (seen 2026-11-28),
|
|
16
|
+
* so a model whose `type` says it isn't a chat model is kept hidden. The list
|
|
17
|
+
* answers without a key, so the key goes along only when there is one.
|
|
18
|
+
*/
|
|
19
|
+
export declare function gatewayModels(key?: string): Promise<ModelEntry[]>;
|
|
20
|
+
/**
|
|
21
|
+
* The ChatGPT plan's models for the signed-in account: GET
|
|
22
|
+
* https://api.openai.com/v1/models on the plan token, `models[]` with `slug`,
|
|
23
|
+
* `display_name` and `visibility`, in the server's order. Only `visibility:
|
|
24
|
+
* "list"` is meant for display
|
|
25
|
+
* (https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference),
|
|
26
|
+
* so the rest are kept hidden.
|
|
27
|
+
*/
|
|
28
|
+
export declare function chatgptPlanModels(token: string): Promise<ModelEntry[]>;
|
|
29
|
+
/**
|
|
30
|
+
* Z.ai documents no model list endpoint. These are the models its FAQ says
|
|
31
|
+
* every GLM Coding Plan includes: "All plans support GLM-5.4, GLM-5.3 and
|
|
32
|
+
* GLM-5.3-Flash" (https://docs.z.ai/devpack/faq, read 2026-11-28). Any other
|
|
33
|
+
* GLM id may be typed. Whether each reads images: glm-5.4 answered "NO IMAGE"
|
|
34
|
+
* and glm-5.3-flash named the colour of a red test image on the Coding Plan
|
|
35
|
+
* endpoint (2026-11-30); the Gateway's list tags zai/glm-5.3 without
|
|
36
|
+
* `vision`. glm-5.4 drops an image without an error.
|
|
37
|
+
*/
|
|
38
|
+
export declare const ZAI_CODING_PLAN_MODELS: ModelEntry[];
|
|
39
|
+
export type ModelList = {
|
|
40
|
+
account: string;
|
|
41
|
+
kind: AccountKindName;
|
|
42
|
+
source: 'live' | 'docs';
|
|
43
|
+
models: ModelEntry[];
|
|
44
|
+
} | {
|
|
45
|
+
account: string;
|
|
46
|
+
kind: AccountKindName;
|
|
47
|
+
error: string;
|
|
48
|
+
};
|
|
49
|
+
export declare function listModels(name: string, account: Account, env: Env): Promise<ModelList>;
|
|
50
|
+
export declare function readsImages(name: string, account: Account, model: string, env: Env): Promise<ReadsImages>;
|
|
51
|
+
export declare function imageReaderFor(accounts: LocalConfig['accounts'], env: Env): (target: Target) => Promise<ReadsImages>;
|
|
52
|
+
export declare function imageReadersFor(config: Pick<LocalConfig, 'tiers' | 'accounts'>, env: Env, read?: (target: Target) => Promise<ReadsImages>): () => Promise<ImageReaders>;
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// docs: The models each kind of account offers, one function per kind: the Gateway's list endpoint, the ChatGPT plan's list on the sign-in token, and Z.ai's list from its docs (it has no list endpoint). `listModels` picks the one for an account in local.json and reads its key or sign-in; `phantom config models`, the tier flags and the Standard and Frontier lists of the settings screen use it
|
|
2
|
+
import { OPENAI, currentSession } from "../chatgpt/session.mjs";
|
|
3
|
+
import { ACCOUNT_KINDS } from "./accounts.mjs";
|
|
4
|
+
import { sessionProblem } from "./chatgpt-plan.mjs";
|
|
5
|
+
import { resolveKey } from "./keys.mjs";
|
|
6
|
+
const LIST_TIMEOUT = 15_000;
|
|
7
|
+
async function getJson(url, headers, who) {
|
|
8
|
+
const answer = await fetch(url, { headers, signal: AbortSignal.timeout(LIST_TIMEOUT) });
|
|
9
|
+
const body = await answer.json().catch(() => null);
|
|
10
|
+
if (!answer.ok) {
|
|
11
|
+
const code = body?.error?.code;
|
|
12
|
+
throw new Error(`${who} answered ${answer.status}${typeof code === 'string' ? ` ${code}` : ''}`);
|
|
13
|
+
}
|
|
14
|
+
return body;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The Gateway's models: GET https://ai-gateway.vercel.sh/v1/models
|
|
18
|
+
* (https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-chat-completions#list-models),
|
|
19
|
+
* `data[].id` in the Gateway's order. The page shows id, object, created and
|
|
20
|
+
* owned_by; the live answer also carries `name` and `type` (seen 2026-11-28),
|
|
21
|
+
* so a model whose `type` says it isn't a chat model is kept hidden. The list
|
|
22
|
+
* answers without a key, so the key goes along only when there is one.
|
|
23
|
+
*/
|
|
24
|
+
export async function gatewayModels(key) {
|
|
25
|
+
const body = await getJson('https://ai-gateway.vercel.sh/v1/models', key ? { authorization: `Bearer ${key}` } : {}, 'the Gateway');
|
|
26
|
+
const data = body.data;
|
|
27
|
+
return (Array.isArray(data) ? data : []).flatMap((m) => typeof m?.id === 'string'
|
|
28
|
+
? [
|
|
29
|
+
{
|
|
30
|
+
id: m.id,
|
|
31
|
+
...(typeof m.name === 'string' && { name: m.name }),
|
|
32
|
+
...(m.type !== undefined && m.type !== 'language' && { hidden: true }),
|
|
33
|
+
...(Array.isArray(m.tags) && { images: m.tags.includes('vision') }),
|
|
34
|
+
},
|
|
35
|
+
]
|
|
36
|
+
: []);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The ChatGPT plan's models for the signed-in account: GET
|
|
40
|
+
* https://api.openai.com/v1/models on the plan token, `models[]` with `slug`,
|
|
41
|
+
* `display_name` and `visibility`, in the server's order. Only `visibility:
|
|
42
|
+
* "list"` is meant for display
|
|
43
|
+
* (https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference),
|
|
44
|
+
* so the rest are kept hidden.
|
|
45
|
+
*/
|
|
46
|
+
export async function chatgptPlanModels(token) {
|
|
47
|
+
const body = await getJson(`${OPENAI.resource}/models`, { authorization: `Bearer ${token}` }, 'OpenAI');
|
|
48
|
+
const models = body.models;
|
|
49
|
+
return (Array.isArray(models) ? models : []).flatMap((m) => typeof m?.slug === 'string' ? [{ id: m.slug, ...(typeof m.display_name === 'string' && { name: m.display_name }), ...(m.visibility !== 'list' && { hidden: true }) }] : []);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Z.ai documents no model list endpoint. These are the models its FAQ says
|
|
53
|
+
* every GLM Coding Plan includes: "All plans support GLM-5.4, GLM-5.3 and
|
|
54
|
+
* GLM-5.3-Flash" (https://docs.z.ai/devpack/faq, read 2026-11-28). Any other
|
|
55
|
+
* GLM id may be typed. Whether each reads images: glm-5.4 answered "NO IMAGE"
|
|
56
|
+
* and glm-5.3-flash named the colour of a red test image on the Coding Plan
|
|
57
|
+
* endpoint (2026-11-30); the Gateway's list tags zai/glm-5.3 without
|
|
58
|
+
* `vision`. glm-5.4 drops an image without an error.
|
|
59
|
+
*/
|
|
60
|
+
export const ZAI_CODING_PLAN_MODELS = [
|
|
61
|
+
{ id: 'glm-5.4', images: false },
|
|
62
|
+
{ id: 'glm-5.3', images: false },
|
|
63
|
+
{ id: 'glm-5.3-flash', images: true },
|
|
64
|
+
];
|
|
65
|
+
export async function listModels(name, account, env) {
|
|
66
|
+
const head = { account: name, kind: account.kind };
|
|
67
|
+
try {
|
|
68
|
+
switch (account.kind) {
|
|
69
|
+
case 'gateway': {
|
|
70
|
+
const lookup = resolveKey(env, name, account);
|
|
71
|
+
return { ...head, source: 'live', models: await gatewayModels(lookup.found ? lookup.key : undefined) };
|
|
72
|
+
}
|
|
73
|
+
case 'zai-coding-plan':
|
|
74
|
+
return { ...head, source: 'docs', models: ZAI_CODING_PLAN_MODELS };
|
|
75
|
+
case 'chatgpt-plan': {
|
|
76
|
+
const session = await currentSession(env);
|
|
77
|
+
if (session.kind !== 'signed-in')
|
|
78
|
+
return { ...head, error: sessionProblem(session) };
|
|
79
|
+
return { ...head, source: 'live', models: await chatgptPlanModels(session.account.access_token) };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
const label = ACCOUNT_KINDS[account.kind].label;
|
|
85
|
+
const error = err instanceof Error && err.name === 'TimeoutError' ? `no answer from the ${label} within ${LIST_TIMEOUT / 1000} seconds` : err instanceof TypeError ? `could not reach the ${label}` : err.message;
|
|
86
|
+
return { ...head, error };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
export async function readsImages(name, account, model, env) {
|
|
90
|
+
// The ChatGPT plan's model list says nothing about images.
|
|
91
|
+
if (account.kind === 'chatgpt-plan')
|
|
92
|
+
return 'unknown';
|
|
93
|
+
const list = await listModels(name, account, env);
|
|
94
|
+
if ('error' in list)
|
|
95
|
+
return 'unknown';
|
|
96
|
+
return list.models.find((m) => m.id === model)?.images ?? 'unknown';
|
|
97
|
+
}
|
|
98
|
+
export function imageReaderFor(accounts, env) {
|
|
99
|
+
const known = new Map();
|
|
100
|
+
return async (target) => {
|
|
101
|
+
const key = `${target.account}\n${target.model}`;
|
|
102
|
+
const saved = known.get(key);
|
|
103
|
+
if (saved !== undefined)
|
|
104
|
+
return saved;
|
|
105
|
+
const account = accounts[target.account];
|
|
106
|
+
const answer = account ? await readsImages(target.account, account, target.model, env) : 'unknown';
|
|
107
|
+
if (answer !== 'unknown')
|
|
108
|
+
known.set(key, answer);
|
|
109
|
+
return answer;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
export function imageReadersFor(config, env, read = imageReaderFor(config.accounts, env)) {
|
|
113
|
+
return async () => {
|
|
114
|
+
const [standard, frontier] = await Promise.all([read(config.tiers.standard), read(config.tiers.frontier)]);
|
|
115
|
+
return { standard, frontier };
|
|
116
|
+
};
|
|
117
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { Env } from '../core/state.mts';
|
|
2
|
+
import { type Sensitivity, type Tier } from './config.mts';
|
|
3
|
+
type Pick = {
|
|
4
|
+
tier: Tier;
|
|
5
|
+
reason: string;
|
|
6
|
+
};
|
|
7
|
+
export type ReplayReport = {
|
|
8
|
+
since: string | null;
|
|
9
|
+
traces: number;
|
|
10
|
+
warm_up: number;
|
|
11
|
+
skipped: number;
|
|
12
|
+
from: string | null;
|
|
13
|
+
to: string | null;
|
|
14
|
+
settings: {
|
|
15
|
+
sensitivity: Sensitivity | null;
|
|
16
|
+
max_move_up_tokens: number;
|
|
17
|
+
};
|
|
18
|
+
recorded: {
|
|
19
|
+
sensitivity: Sensitivity[];
|
|
20
|
+
router_version: (string | null)[];
|
|
21
|
+
};
|
|
22
|
+
router_version: string | null;
|
|
23
|
+
self_check: {
|
|
24
|
+
differ: number;
|
|
25
|
+
ids: string[];
|
|
26
|
+
};
|
|
27
|
+
frontier: {
|
|
28
|
+
live: number;
|
|
29
|
+
as_recorded: number;
|
|
30
|
+
with_changes: number;
|
|
31
|
+
};
|
|
32
|
+
changed: {
|
|
33
|
+
id: string;
|
|
34
|
+
at: string;
|
|
35
|
+
run: string;
|
|
36
|
+
conversation: string | null;
|
|
37
|
+
before: Pick;
|
|
38
|
+
after: Pick;
|
|
39
|
+
}[];
|
|
40
|
+
scores: {
|
|
41
|
+
id: string;
|
|
42
|
+
score: number | null;
|
|
43
|
+
near: 'under' | 'over' | null;
|
|
44
|
+
}[];
|
|
45
|
+
near_threshold: {
|
|
46
|
+
within: number;
|
|
47
|
+
standard: number;
|
|
48
|
+
frontier: number;
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
export declare function replay(opts: {
|
|
52
|
+
env: Env;
|
|
53
|
+
since: Date | null;
|
|
54
|
+
sensitivity: Sensitivity | null;
|
|
55
|
+
maxMoveUpTokens: number;
|
|
56
|
+
warn: (line: string) => void;
|
|
57
|
+
}): Promise<ReplayReport>;
|
|
58
|
+
export declare function replayText(r: ReplayReport, env: Env): string;
|
|
59
|
+
export {};
|