@phantomcodes/cli 1.4.1 → 1.4.2
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 +13 -2
- package/dist/agents/command.d.mts +36 -0
- package/dist/agents/command.mjs +19 -7
- package/dist/agents/proxy.d.mts +44 -0
- package/dist/agents/proxy.mjs +4 -2
- package/dist/cli/app.d.mts +25 -0
- package/dist/cli/commands.d.mts +19 -0
- package/dist/cli/commands.mjs +1 -1
- package/dist/cli/help.d.mts +26 -0
- package/dist/cli/run.d.mts +2 -0
- package/dist/cli/screens.d.mts +171 -0
- package/dist/cli/start.d.mts +34 -0
- package/dist/core/brand.d.mts +12 -0
- package/dist/core/errors.d.mts +27 -0
- package/dist/core/free.d.mts +13 -0
- package/dist/core/helpers.d.mts +75 -0
- package/dist/core/helpers.mjs +27 -2
- package/dist/core/motion.d.mts +47 -0
- package/dist/core/node-trust.d.mts +12 -0
- package/dist/core/pick.d.mts +86 -0
- package/dist/core/request.d.mts +64 -0
- package/dist/core/request.mjs +78 -29
- package/dist/core/secrets.d.mts +33 -0
- package/dist/core/shapes.d.mts +13 -0
- package/dist/core/state.d.mts +3 -0
- package/dist/core/style.d.mts +49 -0
- package/dist/core/version.d.mts +2 -0
- package/dist/core/version.mjs +1 -1
- package/dist/keys/command.d.mts +16 -0
- package/dist/keys/saved.d.mts +88 -0
- package/dist/models/choice.d.mts +7 -0
- package/dist/models/choice.mjs +1 -1
- package/dist/models/command.d.mts +8 -0
- package/dist/models/list.d.mts +39 -0
- package/dist/phantom.d.mts +45 -0
- package/dist/receipts/command.d.mts +7 -0
- package/dist/receipts/receipts.d.mts +67 -0
- package/dist/receipts/receipts.mjs +15 -11
- package/dist/setup/agents.d.mts +149 -0
- package/dist/setup/agents.mjs +48 -35
- package/dist/setup/apply.d.mts +71 -0
- package/dist/setup/apply.mjs +7 -2
- package/dist/setup/command.d.mts +12 -0
- package/dist/setup/editors.d.mts +101 -0
- package/dist/setup/editors.mjs +4 -2
- package/dist/setup/legacy.d.mts +13 -0
- package/dist/setup/plan.d.mts +104 -0
- package/dist/setup/plan.mjs +5 -3
- package/dist/setup/screen.d.mts +30 -0
- package/dist/setup/shared.d.mts +141 -0
- package/dist/setup/shared.mjs +8 -2
- package/dist/setup/was.d.mts +42 -0
- package/dist/setup/was.mjs +91 -0
- package/dist/spend/command.d.mts +5 -0
- package/dist/spend/lineup.d.mts +54 -0
- package/dist/spend/lineup.mjs +3 -2
- package/dist/spend/report.d.mts +105 -0
- package/dist/spend/routing.d.mts +72 -0
- package/dist/workspace/command.d.mts +46 -0
- package/dist/workspace/command.mjs +83 -37
- package/package.json +2 -2
package/dist/core/helpers.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { PhantomApiError, CliError, die } from "./errors.mjs";
|
|
3
3
|
import { colorOn, paint } from "./style.mjs";
|
|
4
|
+
import { explainNetworkError } from "./request.mjs";
|
|
4
5
|
import { Cancelled, canPick } from "./pick.mjs";
|
|
5
6
|
/**
|
|
6
7
|
* Where a picker draws and reads, when this run can show one: a person at a
|
|
@@ -38,8 +39,10 @@ export function handleError(err, stderr = (s) => process.stderr.write(s), opts =
|
|
|
38
39
|
if (err instanceof Cancelled)
|
|
39
40
|
return 130;
|
|
40
41
|
const api = err instanceof PhantomApiError ? err : null;
|
|
41
|
-
|
|
42
|
-
const
|
|
42
|
+
// node's bare "fetch failed" from any caller reads as a sentence about the connection.
|
|
43
|
+
const offline = explainNetworkError(err);
|
|
44
|
+
const code = api ? api.code : err instanceof CliError ? err.code : offline ? 'network_error' : 'unknown';
|
|
45
|
+
const message = offline ?? (err instanceof Error ? err.message : String(err));
|
|
43
46
|
if (opts.human) {
|
|
44
47
|
// A person at a terminal reads a sentence; the code stays for support, dimmed.
|
|
45
48
|
const p = paint(opts.env ?? {}, colorOn(opts.env ?? {}, true));
|
|
@@ -95,6 +98,28 @@ export function flagNum(flags, name) {
|
|
|
95
98
|
die(`--${name} must be a number`);
|
|
96
99
|
return n;
|
|
97
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* A spending control's value for a key: a number of zero or more, `none` for no limit (null), or
|
|
103
|
+
* undefined when the flag is absent. A mistyped value stops the command, because a number that
|
|
104
|
+
* silently became "no limit" would remove the key's cap.
|
|
105
|
+
* @param dollars True for money flags, which may start with `$`.
|
|
106
|
+
* @throws {@link CliError} `key_usage` when the flag has no value, or the value is not a finite number of zero or more.
|
|
107
|
+
*/
|
|
108
|
+
export function limitFlag(flags, name, dollars = false) {
|
|
109
|
+
const raw = flags[name];
|
|
110
|
+
if (raw === undefined)
|
|
111
|
+
return undefined;
|
|
112
|
+
const example = dollars ? `--${name} 5 or --${name} none` : `--${name} 30 or --${name} none`;
|
|
113
|
+
if (raw === true)
|
|
114
|
+
die(`--${name} needs a value, such as ${example}.`, 'key_usage');
|
|
115
|
+
const text = raw.trim();
|
|
116
|
+
if (text === 'none')
|
|
117
|
+
return null;
|
|
118
|
+
const n = text === '' ? NaN : Number(dollars ? text.replace(/^\$/, '') : text);
|
|
119
|
+
if (!Number.isFinite(n) || n < 0)
|
|
120
|
+
die(`--${name} must be ${dollars ? 'a number of dollars' : 'a number'} (0 or more) or none, such as ${example}. You gave "${raw}".`, 'key_usage');
|
|
121
|
+
return n;
|
|
122
|
+
}
|
|
98
123
|
/** Opens a URL in the user's default browser. */
|
|
99
124
|
export function openUrl(url) {
|
|
100
125
|
try {
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Env } from './state.mts';
|
|
2
|
+
/** Whether to animate: color is on for that stream (a terminal, no NO_COLOR), it isn't CI, and PHANTOM_NO_MOTION isn't set. */
|
|
3
|
+
export declare function motionOn(env: Env, isTTY: boolean | undefined): boolean;
|
|
4
|
+
/** Fast at first, then easing to a stop: the curve for things that arrive. */
|
|
5
|
+
export declare const easeOut: (t: number) => number;
|
|
6
|
+
/** A flipbook: each frame is the whole block of lines, and each delay is how long to wait before drawing that frame. */
|
|
7
|
+
export type Flipbook = {
|
|
8
|
+
frames: string[][];
|
|
9
|
+
delays: number[];
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Lines appearing top to bottom: frame k shows the first k lines and keeps the
|
|
13
|
+
* rest blank, so the block's height never changes. `delay(line)` is how long
|
|
14
|
+
* the line waits before it appears; 0 lets it come with the one before.
|
|
15
|
+
*/
|
|
16
|
+
export declare function reveal(lines: string[], delay: (line: string, index: number) => number): Flipbook;
|
|
17
|
+
/**
|
|
18
|
+
* Every bar in `lines` (a run of ━ followed by its ─ track) drawn at
|
|
19
|
+
* `progress` of its length, 0 to 1. The track grows to fill what the bar gives
|
|
20
|
+
* up, so each line keeps its width.
|
|
21
|
+
*/
|
|
22
|
+
export declare function growBars(lines: string[], progress: number): string[];
|
|
23
|
+
/** Bars growing from nothing to their length over `ms`, easing out. */
|
|
24
|
+
export declare function barsGrowing(lines: string[], ms?: number, steps?: number): Flipbook;
|
|
25
|
+
/** The ghost's eye row with the eyes closed: the two gaps filled with a low half block, like lids. */
|
|
26
|
+
export declare const CLOSED_EYES: string;
|
|
27
|
+
/**
|
|
28
|
+
* The brand header drawing in, for a screen whose lines start with it
|
|
29
|
+
* (setup): PHANTOM appears letter by letter, the rest of the screen follows
|
|
30
|
+
* row by row, then the ghost blinks once.
|
|
31
|
+
*/
|
|
32
|
+
export declare function brandIntro(lines: string[], opts?: {
|
|
33
|
+
letterMs?: number;
|
|
34
|
+
rowMs?: number;
|
|
35
|
+
blinkMs?: number;
|
|
36
|
+
}): Flipbook;
|
|
37
|
+
/**
|
|
38
|
+
* Plays a flipbook on a stream: writes the first frame, then moves the cursor
|
|
39
|
+
* back up and redraws each next one in place. Ends on the last frame with a
|
|
40
|
+
* newline. A key press (on a terminal) or `rows` too few to fit the block
|
|
41
|
+
* skips straight to the last frame.
|
|
42
|
+
*/
|
|
43
|
+
export declare function play(write: (s: string) => void, book: Flipbook, opts?: {
|
|
44
|
+
sleep?: (ms: number) => Promise<void>;
|
|
45
|
+
rows?: number;
|
|
46
|
+
skipOnKey?: boolean;
|
|
47
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Node before 24.22.1 still trusts certificates chained to the eMudhra CA
|
|
3
|
+
* keys found guessable in October 2026, so on a network someone controls, a
|
|
4
|
+
* forged phantom.codes could read the key this CLI sends. 24.22.1 rejects
|
|
5
|
+
* those chains ("tls: reject chains containing blocked public keys").
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* A warning for stderr when `version` (`process.versions.node`) is a Node 24
|
|
9
|
+
* older than 24.22.1, or null. Other majors get none: the CLI needs 24 or newer,
|
|
10
|
+
* and the newer lines carry the fix.
|
|
11
|
+
*/
|
|
12
|
+
export declare function nodeTrustWarning(version: string): string | null;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { Env } from './state.mts';
|
|
2
|
+
/** One option in a list: what it says, a few words beside it, and what choosing it returns. */
|
|
3
|
+
export type Choice<T> = {
|
|
4
|
+
label: string;
|
|
5
|
+
hint?: string;
|
|
6
|
+
value: T;
|
|
7
|
+
};
|
|
8
|
+
/** One row of a checklist, and whether it starts ticked. */
|
|
9
|
+
export type CheckItem<T> = Choice<T> & {
|
|
10
|
+
checked?: boolean;
|
|
11
|
+
};
|
|
12
|
+
/** Where keys come from: the real keyboard, or a list of key names in tests. */
|
|
13
|
+
export type KeySource = {
|
|
14
|
+
next(): Promise<string>;
|
|
15
|
+
close(): void;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Where a picker draws and reads: the stream it writes to, its environment,
|
|
19
|
+
* its keys, and what Esc does on this screen (`back` to the step before,
|
|
20
|
+
* `quit` the app, or `cancel` a command started on its own), for the hint
|
|
21
|
+
* line and the answer shown after Esc.
|
|
22
|
+
*/
|
|
23
|
+
export type PickIo = {
|
|
24
|
+
write: (s: string) => void;
|
|
25
|
+
env: Env;
|
|
26
|
+
keys?: () => KeySource;
|
|
27
|
+
esc?: 'back' | 'quit' | 'cancel';
|
|
28
|
+
columns?: number;
|
|
29
|
+
};
|
|
30
|
+
/** Thrown by a picker when Ctrl+C is pressed: stop the whole command, wherever it is. */
|
|
31
|
+
export declare class Cancelled extends Error {
|
|
32
|
+
constructor();
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Thrown by a command started from the start menu when Esc is pressed on its
|
|
36
|
+
* first step, so the menu shows again instead of the command ending.
|
|
37
|
+
*/
|
|
38
|
+
export declare class BackToMenu extends Error {
|
|
39
|
+
constructor();
|
|
40
|
+
}
|
|
41
|
+
/** Whether this run can show a picker: a person at a terminal on both ends, and not CI. */
|
|
42
|
+
export declare function canPick(env: Env, stderrIsTTY: boolean | undefined, stdinIsTTY?: boolean): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* The keyboard, one key at a time, named the way pickers read them: `up`,
|
|
45
|
+
* `down`, `return`, `space`, `escape`, `ctrl-c`, or the letter itself.
|
|
46
|
+
*/
|
|
47
|
+
export declare function keyboard(): KeySource;
|
|
48
|
+
/**
|
|
49
|
+
* Keys from a list, for tests: each `next()` returns the next name, and `end`
|
|
50
|
+
* once the list runs out (which pickers treat as Esc). Every picker in a run reads from the same list, as
|
|
51
|
+
* they would from one keyboard.
|
|
52
|
+
*/
|
|
53
|
+
export declare function scriptedKeys(names: string[]): () => KeySource;
|
|
54
|
+
/**
|
|
55
|
+
* Asks a question with a list of answers. ↑ and ↓ (or k and j, or Tab and
|
|
56
|
+
* Shift+Tab) move and Enter chooses. Esc or q returns null, which the caller
|
|
57
|
+
* reads as "go back a step"; Ctrl+C throws {@link Cancelled} to stop the
|
|
58
|
+
* whole command. `start` is where the marker begins.
|
|
59
|
+
*/
|
|
60
|
+
export declare function choose<T>(io: PickIo, question: string, choices: Choice<T>[], start?: number): Promise<T | null>;
|
|
61
|
+
/**
|
|
62
|
+
* A checklist: ↑ and ↓ (or Tab) move, Space ticks or unticks, `a` ticks all,
|
|
63
|
+
* Enter goes on with the ticked items (it waits while none is ticked). Esc
|
|
64
|
+
* or q returns null (go back); Ctrl+C throws {@link Cancelled}.
|
|
65
|
+
*/
|
|
66
|
+
export declare function checklist<T>(io: PickIo, question: string, items: CheckItem<T>[]): Promise<T[] | null>;
|
|
67
|
+
/**
|
|
68
|
+
* Listens for Esc or Ctrl+C while something waits (sign-in waiting for
|
|
69
|
+
* approval), without taking over the screen. `pressed` settles with the key;
|
|
70
|
+
* other keys are ignored, and the end of a test's keys never settles it.
|
|
71
|
+
*/
|
|
72
|
+
export declare function cancelKeys(source: KeySource): {
|
|
73
|
+
pressed: Promise<'escape' | 'ctrl-c'>;
|
|
74
|
+
close: () => void;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Asks for a short piece of text, such as a key's name or an amount: type it,
|
|
78
|
+
* Backspace to fix it, Enter to go on (it waits while `check` refuses the
|
|
79
|
+
* text, and shows why), Esc to go back (null), Ctrl+C to stop. Keys longer
|
|
80
|
+
* than one character that aren't named keys are typed as text, so a test can
|
|
81
|
+
* send "sam" as one key.
|
|
82
|
+
*/
|
|
83
|
+
export declare function askText(io: PickIo, question: string, opts?: {
|
|
84
|
+
placeholder?: string;
|
|
85
|
+
check?: (text: string) => string | null;
|
|
86
|
+
}): Promise<string | null>;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { PhantomApiError } from './errors.mts';
|
|
2
|
+
import type { BalanceResult } from './shapes.mts';
|
|
3
|
+
/** The Phantom AI API address phantom calls when PHANTOM_BASE_URL is unset. */
|
|
4
|
+
export declare const DEFAULT_BASE_URL = "https://phantom.codes/v1";
|
|
5
|
+
/** How long {@link request} waits for the whole answer, in milliseconds, before it gives up. */
|
|
6
|
+
export declare const REQUEST_TIMEOUT_MS = 30000;
|
|
7
|
+
/**
|
|
8
|
+
* What an answer's body held. `json` is the parsed value, or `{}` when the body was empty or not JSON, so
|
|
9
|
+
* callers can read fields without checking. `kind` says which of the three it was.
|
|
10
|
+
*/
|
|
11
|
+
export type Answer = {
|
|
12
|
+
json: unknown;
|
|
13
|
+
kind: 'json' | 'empty' | 'text';
|
|
14
|
+
};
|
|
15
|
+
/** Reads an answer's body as text and parses it only when it is JSON. A web page or an empty body never throws. */
|
|
16
|
+
export declare function readAnswer(res: Response): Promise<Answer>;
|
|
17
|
+
/**
|
|
18
|
+
* The error for a failed answer. A JSON body goes through {@link apiError}. A web page or an empty body, such as a
|
|
19
|
+
* 502 from a proxy in front of Phantom AI, gets a sentence a person can act on instead of `Unexpected token '<'`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function answerError(status: number, answer: Answer): PhantomApiError;
|
|
22
|
+
/**
|
|
23
|
+
* A sentence for node's `fetch failed`, which says nothing about why. Offline, a DNS failure and a refused
|
|
24
|
+
* connection read as "check that you are online"; a certificate problem says so. Returns null for any other error.
|
|
25
|
+
*/
|
|
26
|
+
export declare function explainNetworkError(err: unknown, host?: string): string | null;
|
|
27
|
+
/**
|
|
28
|
+
* One HTTP call with the limits every call to Phantom AI shares. It gives up after `timeoutMs`, counting the
|
|
29
|
+
* body as well as the headers, because a server can send headers and then stall. It reads the body as text,
|
|
30
|
+
* and turns a failed connection into a sentence. It returns the answer whatever the status; the caller
|
|
31
|
+
* decides what a status means.
|
|
32
|
+
* @param label What the call is, for the timeout message, such as `GET /key/balance`.
|
|
33
|
+
* @throws {@link CliError} `request_timeout` when no full answer arrives in time, `network_error` when the connection fails.
|
|
34
|
+
*/
|
|
35
|
+
export declare function fetchAnswer(url: string, init: RequestInit, label: string, timeoutMs?: number): Promise<{
|
|
36
|
+
res: Response;
|
|
37
|
+
answer: Answer;
|
|
38
|
+
}>;
|
|
39
|
+
/**
|
|
40
|
+
* Calls the Phantom AI API with the key as a Bearer token and returns the
|
|
41
|
+
* JSON answer. Every client function in phantom goes through it.
|
|
42
|
+
* @param method The HTTP method.
|
|
43
|
+
* @param path The path after the base URL, such as `/key/balance`.
|
|
44
|
+
* @param apiKey The key sent in the Authorization header.
|
|
45
|
+
* @param body Sent as JSON when given.
|
|
46
|
+
* @param baseUrl The API base. Defaults to PHANTOM_BASE_URL, then {@link DEFAULT_BASE_URL}. Must be https ({@link httpsOnly}).
|
|
47
|
+
* @param headers Extra headers to send.
|
|
48
|
+
* @param timeoutMs How long to wait for the answer. Defaults to {@link REQUEST_TIMEOUT_MS}.
|
|
49
|
+
* @throws {@link PhantomApiError} when the API answers with an error status.
|
|
50
|
+
* @throws {@link CliError} with code `request_timeout` when no answer arrives in time.
|
|
51
|
+
*/
|
|
52
|
+
export declare function request<T>(method: string, path: string, apiKey: string, body?: unknown, baseUrl?: string, headers?: Record<string, string>, timeoutMs?: number): Promise<T>;
|
|
53
|
+
export declare function apiBase(baseUrl?: string): string;
|
|
54
|
+
/**
|
|
55
|
+
* The API base must be https. The key goes to it on every call, so plain http
|
|
56
|
+
* is refused, localhost included.
|
|
57
|
+
*/
|
|
58
|
+
export declare function httpsOnly(baseUrl: string): string;
|
|
59
|
+
export declare function apiError(status: number, json: unknown): PhantomApiError;
|
|
60
|
+
/**
|
|
61
|
+
* Credit left, credit spent and expiry of a key (GET /key/balance).
|
|
62
|
+
* @throws {@link CliError} with code `balance_unreadable` when the answer has no numbers, such as a sign-in page that came back with status 200.
|
|
63
|
+
*/
|
|
64
|
+
export declare function getBalance(apiKey: string, baseUrl?: string): Promise<BalanceResult>;
|
package/dist/core/request.mjs
CHANGED
|
@@ -3,6 +3,73 @@ import { PhantomApiError, die } from "./errors.mjs";
|
|
|
3
3
|
export const DEFAULT_BASE_URL = 'https://phantom.codes/v1';
|
|
4
4
|
/** How long {@link request} waits for the whole answer, in milliseconds, before it gives up. */
|
|
5
5
|
export const REQUEST_TIMEOUT_MS = 30_000;
|
|
6
|
+
/** Reads an answer's body as text and parses it only when it is JSON. A web page or an empty body never throws. */
|
|
7
|
+
export async function readAnswer(res) {
|
|
8
|
+
const text = await res.text();
|
|
9
|
+
if (text.trim() === '')
|
|
10
|
+
return { json: {}, kind: 'empty' };
|
|
11
|
+
try {
|
|
12
|
+
return { json: JSON.parse(text), kind: 'json' };
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return { json: {}, kind: 'text' };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The error for a failed answer. A JSON body goes through {@link apiError}. A web page or an empty body, such as a
|
|
20
|
+
* 502 from a proxy in front of Phantom AI, gets a sentence a person can act on instead of `Unexpected token '<'`.
|
|
21
|
+
*/
|
|
22
|
+
export function answerError(status, answer) {
|
|
23
|
+
if (answer.kind === 'json')
|
|
24
|
+
return apiError(status, answer.json);
|
|
25
|
+
if (status === 502 || status === 503 || status === 504) {
|
|
26
|
+
return new PhantomApiError(status, String(status), `Phantom AI is not answering right now (HTTP ${status}). Wait a minute and try again.`);
|
|
27
|
+
}
|
|
28
|
+
const what = answer.kind === 'empty' ? 'an empty answer' : 'an error page instead of data';
|
|
29
|
+
return new PhantomApiError(status, String(status), `Phantom AI sent ${what} (HTTP ${status}). Check PHANTOM_BASE_URL, and try again in a minute.`);
|
|
30
|
+
}
|
|
31
|
+
/** The error codes node gives when a connection never reached Phantom AI. */
|
|
32
|
+
const UNREACHABLE = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_SOCKET']);
|
|
33
|
+
/**
|
|
34
|
+
* A sentence for node's `fetch failed`, which says nothing about why. Offline, a DNS failure and a refused
|
|
35
|
+
* connection read as "check that you are online"; a certificate problem says so. Returns null for any other error.
|
|
36
|
+
*/
|
|
37
|
+
export function explainNetworkError(err, host = 'Phantom AI') {
|
|
38
|
+
if (!(err instanceof TypeError) || err.message !== 'fetch failed')
|
|
39
|
+
return null;
|
|
40
|
+
const cause = (err.cause ?? {});
|
|
41
|
+
const code = cause.code ?? '';
|
|
42
|
+
if (/CERT|SELF_SIGNED|UNABLE_TO_VERIFY/.test(code)) {
|
|
43
|
+
return `phantom could not make a secure connection to ${host} (${code}). A work network or a VPN can cause this. Try another network.`;
|
|
44
|
+
}
|
|
45
|
+
if (UNREACHABLE.has(code) || !cause.message)
|
|
46
|
+
return `phantom could not reach ${host}. Check that you are online, then try again.`;
|
|
47
|
+
return `phantom could not reach ${host} (${cause.message}). Check that you are online, then try again.`;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* One HTTP call with the limits every call to Phantom AI shares. It gives up after `timeoutMs`, counting the
|
|
51
|
+
* body as well as the headers, because a server can send headers and then stall. It reads the body as text,
|
|
52
|
+
* and turns a failed connection into a sentence. It returns the answer whatever the status; the caller
|
|
53
|
+
* decides what a status means.
|
|
54
|
+
* @param label What the call is, for the timeout message, such as `GET /key/balance`.
|
|
55
|
+
* @throws {@link CliError} `request_timeout` when no full answer arrives in time, `network_error` when the connection fails.
|
|
56
|
+
*/
|
|
57
|
+
export async function fetchAnswer(url, init, label, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
58
|
+
const signal = AbortSignal.timeout(Math.max(1, timeoutMs));
|
|
59
|
+
try {
|
|
60
|
+
const res = await fetch(url, { ...init, signal });
|
|
61
|
+
return { res, answer: await readAnswer(res) };
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
if (signal.aborted) {
|
|
65
|
+
die(`Phantom AI did not answer ${label} within ${Math.max(1, Math.round(timeoutMs / 1000))} seconds. Check your connection and try again.`, 'request_timeout');
|
|
66
|
+
}
|
|
67
|
+
const sentence = explainNetworkError(err, new URL(url).host);
|
|
68
|
+
if (sentence)
|
|
69
|
+
die(sentence, 'network_error');
|
|
70
|
+
throw err;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
6
73
|
/**
|
|
7
74
|
* Calls the Phantom AI API with the key as a Bearer token and returns the
|
|
8
75
|
* JSON answer. Every client function in phantom goes through it.
|
|
@@ -17,36 +84,18 @@ export const REQUEST_TIMEOUT_MS = 30_000;
|
|
|
17
84
|
* @throws {@link CliError} with code `request_timeout` when no answer arrives in time.
|
|
18
85
|
*/
|
|
19
86
|
export async function request(method, path, apiKey, body, baseUrl, headers = {}, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
30
|
-
...headers,
|
|
31
|
-
},
|
|
32
|
-
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
33
|
-
signal,
|
|
34
|
-
});
|
|
35
|
-
// The deadline covers the body too: a server can send headers and then stall.
|
|
36
|
-
json = await res.json().catch((err) => {
|
|
37
|
-
if (signal.aborted)
|
|
38
|
-
throw err;
|
|
39
|
-
return {};
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
catch (err) {
|
|
43
|
-
if (signal.aborted)
|
|
44
|
-
die(`Phantom AI did not answer ${method} ${path} within ${Math.round(timeoutMs / 1000)} seconds. Check your connection and try again.`, 'request_timeout');
|
|
45
|
-
throw err;
|
|
46
|
-
}
|
|
87
|
+
const { res, answer } = await fetchAnswer(`${apiBase(baseUrl)}${path}`, {
|
|
88
|
+
method,
|
|
89
|
+
headers: {
|
|
90
|
+
Authorization: `Bearer ${apiKey}`,
|
|
91
|
+
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
92
|
+
...headers,
|
|
93
|
+
},
|
|
94
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
95
|
+
}, `${method} ${path}`, timeoutMs);
|
|
47
96
|
if (!res.ok)
|
|
48
|
-
throw
|
|
49
|
-
return json;
|
|
97
|
+
throw answerError(res.status, answer);
|
|
98
|
+
return answer.json;
|
|
50
99
|
}
|
|
51
100
|
export function apiBase(baseUrl) {
|
|
52
101
|
return httpsOnly(baseUrl ||
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Env } from './state.mts';
|
|
2
|
+
/**
|
|
3
|
+
* On macOS, saved keys and wallets live in the login Keychain rather than in
|
|
4
|
+
* files. The file stays, holding only a pointer (`pai-keychain:<id>`), so
|
|
5
|
+
* listing and existence checks work the same on every system. Elsewhere, or with PHANTOM_KEYCHAIN=0, the file holds the secret,
|
|
6
|
+
* readable by this user only.
|
|
7
|
+
*
|
|
8
|
+
* Items are written through /usr/bin/security, which the Keychain then trusts
|
|
9
|
+
* to read them back, so there is no prompt. That also means any program
|
|
10
|
+
* running as this user can read them the same way: the Keychain keeps secrets
|
|
11
|
+
* out of files, backups and sync folders, not away from local programs.
|
|
12
|
+
*
|
|
13
|
+
* A secret file written before this is moved into the Keychain the first time
|
|
14
|
+
* it is read, and replaced with a pointer only after the Keychain returns it
|
|
15
|
+
* intact.
|
|
16
|
+
*/
|
|
17
|
+
export declare const KEYCHAIN_SERVICE = "pai";
|
|
18
|
+
export declare const KEYCHAIN_POINTER = "pai-keychain:";
|
|
19
|
+
/** Reads and writes phantom's items in the macOS login Keychain through /usr/bin/security, under the service name `pai`, the CLI's old name. */
|
|
20
|
+
export declare const keychain: {
|
|
21
|
+
/** The secret saved under `id`, or null when there is none or the Keychain can't be read. */
|
|
22
|
+
get(id: string): string | null;
|
|
23
|
+
/** Saves `value` under `id`, replacing what was there. Returns false when the Keychain refuses, as it does when locked. */
|
|
24
|
+
set(id: string, label: string, value: string): boolean;
|
|
25
|
+
/** Removes the item saved under `id`, if any. */
|
|
26
|
+
delete(id: string): void;
|
|
27
|
+
};
|
|
28
|
+
export declare function keychainOn(env: Env): boolean;
|
|
29
|
+
export declare function writeSecret(env: Env, file: string, value: string, opts?: {
|
|
30
|
+
flag?: string;
|
|
31
|
+
}): void;
|
|
32
|
+
export declare function readSecret(env: Env, file: string): string;
|
|
33
|
+
export declare function removeSecret(file: string): void;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The answer from GET /key/balance. */
|
|
2
|
+
export type BalanceResult = {
|
|
3
|
+
/** True while the key is switched on and not past its expiry. */
|
|
4
|
+
active: boolean;
|
|
5
|
+
/** The kind of key the server stores: `credit`, `pass` or `faucet`. */
|
|
6
|
+
kind: string;
|
|
7
|
+
/** Credit left on the key, in USD. */
|
|
8
|
+
credit_balance_usd: number;
|
|
9
|
+
/** Credit the key has spent, in USD. */
|
|
10
|
+
credit_spent_usd: number;
|
|
11
|
+
/** When the key stops working, as an ISO 8601 time. */
|
|
12
|
+
expires_at: string;
|
|
13
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Env } from './state.mts';
|
|
2
|
+
/**
|
|
3
|
+
* Whether to print color: only to a terminal, never with `NO_COLOR` set
|
|
4
|
+
* (https://no-color.org) or on a `dumb` terminal. `FORCE_COLOR` turns it on
|
|
5
|
+
* anywhere, and `FORCE_COLOR=0` turns it off.
|
|
6
|
+
*/
|
|
7
|
+
export declare function colorOn(env: Env, isTTY: boolean | undefined): boolean;
|
|
8
|
+
/** The styles a screen uses. Each wraps text in its color, or returns it as is when color is off. */
|
|
9
|
+
export type Paint = {
|
|
10
|
+
/** Phantom's lime (#3ee6a8, `--lime` on the site), for marks such as ◆ and ✓. */
|
|
11
|
+
lime: (s: string) => string;
|
|
12
|
+
bold: (s: string) => string;
|
|
13
|
+
/** Bright white, for the ghost's body. */
|
|
14
|
+
white: (s: string) => string;
|
|
15
|
+
/** Night text on a lime block, like the site's lime tags (`Meet phantom-1`). */
|
|
16
|
+
pill: (s: string) => string;
|
|
17
|
+
/** Paths, counts and other detail the eye can skip. */
|
|
18
|
+
dim: (s: string) => string;
|
|
19
|
+
/** Phantom's cyan (#00d1ff, `--cyan` on the site), for actions and commands people can type. */
|
|
20
|
+
cyan: (s: string) => string;
|
|
21
|
+
/** Lines a file gains. */
|
|
22
|
+
green: (s: string) => string;
|
|
23
|
+
/** Lines a file loses, and agents setup skipped. */
|
|
24
|
+
red: (s: string) => string;
|
|
25
|
+
/** Warnings and steps to do by hand. */
|
|
26
|
+
yellow: (s: string) => string;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* The styles for one screen. Lime and cyan use 24-bit color when the terminal says it
|
|
30
|
+
* has it (`COLORTERM=truecolor`), and the nearest of the 256 standard colors otherwise.
|
|
31
|
+
*/
|
|
32
|
+
export declare function paint(env: Env, on: boolean): Paint;
|
|
33
|
+
/** `text` without color codes, to measure how wide it prints. */
|
|
34
|
+
export declare const unstyled: (text: string) => string;
|
|
35
|
+
/**
|
|
36
|
+
* One line of a screen, fitted to a terminal `columns` wide: a longer line
|
|
37
|
+
* breaks at spaces, and each piece after the first starts under the text it
|
|
38
|
+
* continues. That is the second column for a table row or a help entry
|
|
39
|
+
* (text after a run of two spaces), the words after a mark such as `✓ ` or
|
|
40
|
+
* `→ `, or else the line's own indent. A word longer than the room, such as
|
|
41
|
+
* a URL, stays whole. Color codes don't count toward the width.
|
|
42
|
+
*/
|
|
43
|
+
export declare function fitLine(line: string, columns: number): string;
|
|
44
|
+
/**
|
|
45
|
+
* Text fitted to `columns` with {@link fitLine}, line by line. JSON (text
|
|
46
|
+
* that starts with `{` or `[`) and anything drawn in place come back as they
|
|
47
|
+
* are, since a break there would change what they mean.
|
|
48
|
+
*/
|
|
49
|
+
export declare function fitText(text: string, columns: number): string;
|
package/dist/core/version.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This release of phantom. `npm version` keeps it equal to the version in package.json. */
|
|
2
|
-
export const VERSION = '1.4.
|
|
2
|
+
export const VERSION = '1.4.2';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type CommandInput } from '../core/helpers.mts';
|
|
2
|
+
/** `--table` output for `balance`. */
|
|
3
|
+
export declare function tableBalance(d: unknown): string;
|
|
4
|
+
/** `--table` output for `key list`. */
|
|
5
|
+
export declare function tableKeys(d: unknown): string;
|
|
6
|
+
/** `phantom balance`: the key's credit and expiry. Run by `run()`. */
|
|
7
|
+
export declare function balanceCommand(input: CommandInput): Promise<number>;
|
|
8
|
+
/** `phantom key list|save|show|rm`: keys saved by name. Run by `run()`. */
|
|
9
|
+
export declare function keyCommand({ argv, env, io, subcommand, flags, table, baseUrl }: CommandInput): Promise<number>;
|
|
10
|
+
/** `phantom login`: checks a key and saves it as the login key. Run by `run()`. */
|
|
11
|
+
export declare function loginCommand({ env, io, subcommand, table, baseUrl }: CommandInput): Promise<number>;
|
|
12
|
+
/**
|
|
13
|
+
* `phantom logout`: forgets the login key. `forgotWorkspace` says whether the
|
|
14
|
+
* workspace sign-in was forgotten too, so the screen doesn't say nothing changed. Run by `run()`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function logoutCommand({ env, io, table, flags }: CommandInput, forgotWorkspace?: boolean): Promise<number>;
|
|
@@ -0,0 +1,88 @@
|
|
|
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
|
+
/** A key's id: the start of its SHA-256 hash, safe to print. */
|
|
5
|
+
export declare function keyId(key: string): string;
|
|
6
|
+
/** Where the key a command runs as comes from. */
|
|
7
|
+
export type KeySource = {
|
|
8
|
+
/** PHANTOM_API_KEY. */
|
|
9
|
+
from: 'env';
|
|
10
|
+
} | {
|
|
11
|
+
/** A key saved by name, chosen with PHANTOM_KEY_NAME. */
|
|
12
|
+
from: 'named';
|
|
13
|
+
/** The saved key's name. */
|
|
14
|
+
name: string;
|
|
15
|
+
} | {
|
|
16
|
+
/** The default key, saved by `phantom keys create` or `phantom keys save default`. */
|
|
17
|
+
from: 'login';
|
|
18
|
+
} | {
|
|
19
|
+
/** No key at all. */
|
|
20
|
+
from: 'none';
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Which key a command runs as: the saved key named by PHANTOM_KEY_NAME, then
|
|
24
|
+
* PHANTOM_API_KEY, then the default key. It only looks; {@link resolveApiKey}
|
|
25
|
+
* reads the key.
|
|
26
|
+
*/
|
|
27
|
+
export declare function keySource(env: Env): KeySource;
|
|
28
|
+
/** The key a command runs as, chosen by {@link keySource}. An empty string when there is none. */
|
|
29
|
+
export declare function resolveApiKey(env: Env): string;
|
|
30
|
+
/**
|
|
31
|
+
* A key saved by name.
|
|
32
|
+
* @throws {@link CliError} when no key has that name, or the name is not valid.
|
|
33
|
+
*/
|
|
34
|
+
export declare function readNamedKey(env: Env, name: string): string;
|
|
35
|
+
/**
|
|
36
|
+
* Saves a key by name, in the Keychain or a mode 600 file (see {@link keychain}).
|
|
37
|
+
* Refuses a name already in use unless `replace` is set, and anything that
|
|
38
|
+
* doesn't start with `sk-phantom-`.
|
|
39
|
+
* @returns The name, and the key's {@link keyId}.
|
|
40
|
+
*/
|
|
41
|
+
export declare function saveNamedKey(env: Env, name: string, key: string, opts?: {
|
|
42
|
+
replace?: boolean;
|
|
43
|
+
}): {
|
|
44
|
+
/** The name the key was saved under. */
|
|
45
|
+
name: string;
|
|
46
|
+
/** The key's id, as {@link keyId} computes it. */
|
|
47
|
+
id: string;
|
|
48
|
+
};
|
|
49
|
+
/** Forgets a saved key. The key itself keeps working. */
|
|
50
|
+
export declare function removeNamedKey(env: Env, name: string): {
|
|
51
|
+
/** The name asked for. */
|
|
52
|
+
name: string;
|
|
53
|
+
/** False when no key was saved under that name. */
|
|
54
|
+
removed: boolean;
|
|
55
|
+
};
|
|
56
|
+
/** Every key saved by name, sorted, with its id. Never returns the keys. */
|
|
57
|
+
export declare function listNamedKeys(env: Env): {
|
|
58
|
+
/** One entry per saved key. */
|
|
59
|
+
keys: Array<{
|
|
60
|
+
/** The saved name. */
|
|
61
|
+
name: string;
|
|
62
|
+
/** The key's id, as {@link keyId} computes it. */
|
|
63
|
+
id: string;
|
|
64
|
+
}>;
|
|
65
|
+
};
|
|
66
|
+
/** The default key, the one `phantom keys create` saves when no name is given, or null when none is saved. */
|
|
67
|
+
export declare function defaultKey(env: Env): string | null;
|
|
68
|
+
/** Saves the default key, the one used when neither PHANTOM_KEY_NAME nor PHANTOM_API_KEY is set. */
|
|
69
|
+
export declare function saveApiKey(env: Env, key: string): {
|
|
70
|
+
/** The path of the file that holds the key or its Keychain pointer. */
|
|
71
|
+
saved: string;
|
|
72
|
+
};
|
|
73
|
+
/** Forgets the default key. */
|
|
74
|
+
export declare function removeApiKey(env: Env): {
|
|
75
|
+
/** False when no default key was saved. */
|
|
76
|
+
removed: boolean;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Where a new key will be saved: the name in `save` (`--save`), or `default`.
|
|
80
|
+
* Run it before anything is asked for: it refuses a name already in use and,
|
|
81
|
+
* with no name, a default key that is saved already.
|
|
82
|
+
* @throws {@link CliError} `key_exists`, or `cli_error` for `--save` with no name.
|
|
83
|
+
*/
|
|
84
|
+
export declare function saveTarget(env: Env, save: string | true | undefined): string;
|
|
85
|
+
/** Saves a key under a {@link saveTarget}: `default`, or a name. */
|
|
86
|
+
export declare function saveKeyAs(env: Env, target: string, key: string): void;
|
|
87
|
+
/** Forgets a key saved under a {@link saveTarget}. */
|
|
88
|
+
export declare function forgetKeyAs(env: Env, target: string): void;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Env } from '../core/state.mts';
|
|
2
|
+
/** The model you picked with `phantom models`, or undefined when you never picked one. */
|
|
3
|
+
export declare function savedModel(env: Env): string | undefined;
|
|
4
|
+
/** Saves the model your agents start on. */
|
|
5
|
+
export declare function saveModel(env: Env, id: string): void;
|
|
6
|
+
/** The model agents start on: the one you picked, or phantom-1. */
|
|
7
|
+
export declare function startModel(env: Env): string;
|
package/dist/models/choice.mjs
CHANGED
|
@@ -18,7 +18,7 @@ export function savedModel(env) {
|
|
|
18
18
|
}
|
|
19
19
|
/** Saves the model your agents start on. */
|
|
20
20
|
export function saveModel(env, id) {
|
|
21
|
-
mkdirSync(stateDir(env), { recursive: true });
|
|
21
|
+
mkdirSync(stateDir(env), { recursive: true, mode: 0o700 });
|
|
22
22
|
writeFileSync(choiceFile(env), `${id}\n`);
|
|
23
23
|
}
|
|
24
24
|
/** The model agents start on: the one you picked, or phantom-1. */
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type CommandInput } from '../core/helpers.mts';
|
|
2
|
+
/**
|
|
3
|
+
* `phantom models`: phantom-1, phantom-1:free and phantom-1:zdr side by side,
|
|
4
|
+
* with the jobs each can do and the model behind each job. At a terminal you
|
|
5
|
+
* pick one, and your agents start on it (`./choice.mts`).
|
|
6
|
+
* `phantom models use <id>` picks without the menu.
|
|
7
|
+
*/
|
|
8
|
+
export declare function modelsCommand(input: CommandInput): Promise<number>;
|