@phantomcodes/cli 1.4.0 → 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.
Files changed (69) hide show
  1. package/README.md +13 -16
  2. package/dist/agents/command.d.mts +36 -0
  3. package/dist/agents/command.mjs +19 -7
  4. package/dist/agents/proxy.d.mts +44 -0
  5. package/dist/agents/proxy.mjs +4 -2
  6. package/dist/cli/app.d.mts +25 -0
  7. package/dist/cli/app.mjs +0 -2
  8. package/dist/cli/commands.d.mts +19 -0
  9. package/dist/cli/commands.mjs +1 -11
  10. package/dist/cli/help.d.mts +26 -0
  11. package/dist/cli/help.mjs +1 -1
  12. package/dist/cli/run.d.mts +2 -0
  13. package/dist/cli/screens.d.mts +171 -0
  14. package/dist/cli/screens.mjs +0 -31
  15. package/dist/cli/start.d.mts +34 -0
  16. package/dist/cli/start.mjs +0 -1
  17. package/dist/core/brand.d.mts +12 -0
  18. package/dist/core/errors.d.mts +27 -0
  19. package/dist/core/free.d.mts +13 -0
  20. package/dist/core/helpers.d.mts +75 -0
  21. package/dist/core/helpers.mjs +28 -3
  22. package/dist/core/motion.d.mts +47 -0
  23. package/dist/core/node-trust.d.mts +12 -0
  24. package/dist/core/pick.d.mts +86 -0
  25. package/dist/core/request.d.mts +64 -0
  26. package/dist/core/request.mjs +79 -30
  27. package/dist/core/secrets.d.mts +33 -0
  28. package/dist/core/shapes.d.mts +13 -0
  29. package/dist/core/state.d.mts +3 -0
  30. package/dist/core/style.d.mts +49 -0
  31. package/dist/core/version.d.mts +2 -0
  32. package/dist/core/version.mjs +1 -1
  33. package/dist/keys/command.d.mts +16 -0
  34. package/dist/keys/saved.d.mts +88 -0
  35. package/dist/models/choice.d.mts +7 -0
  36. package/dist/models/choice.mjs +1 -1
  37. package/dist/models/command.d.mts +8 -0
  38. package/dist/models/list.d.mts +39 -0
  39. package/dist/phantom.d.mts +45 -0
  40. package/dist/phantom.mjs +0 -1
  41. package/dist/receipts/command.d.mts +7 -0
  42. package/dist/receipts/receipts.d.mts +67 -0
  43. package/dist/receipts/receipts.mjs +15 -11
  44. package/dist/setup/agents.d.mts +149 -0
  45. package/dist/setup/agents.mjs +48 -35
  46. package/dist/setup/apply.d.mts +71 -0
  47. package/dist/setup/apply.mjs +7 -2
  48. package/dist/setup/command.d.mts +12 -0
  49. package/dist/setup/editors.d.mts +101 -0
  50. package/dist/setup/editors.mjs +4 -2
  51. package/dist/setup/legacy.d.mts +13 -0
  52. package/dist/setup/plan.d.mts +104 -0
  53. package/dist/setup/plan.mjs +5 -3
  54. package/dist/setup/screen.d.mts +30 -0
  55. package/dist/setup/shared.d.mts +141 -0
  56. package/dist/setup/shared.mjs +8 -2
  57. package/dist/setup/was.d.mts +42 -0
  58. package/dist/setup/was.mjs +91 -0
  59. package/dist/spend/command.d.mts +5 -0
  60. package/dist/spend/lineup.d.mts +54 -0
  61. package/dist/spend/lineup.mjs +3 -2
  62. package/dist/spend/report.d.mts +105 -0
  63. package/dist/spend/report.mjs +0 -2
  64. package/dist/spend/routing.d.mts +72 -0
  65. package/dist/workspace/command.d.mts +46 -0
  66. package/dist/workspace/command.mjs +83 -37
  67. package/package.json +2 -2
  68. package/skills/phantom-ai/SKILL.md +1 -15
  69. package/dist/plan/command.mjs +0 -91
@@ -0,0 +1,27 @@
1
+ /** An error answer from the Phantom AI API: 401 or 403 maps to exit code 2. */
2
+ export declare class PhantomApiError extends Error {
3
+ /** The HTTP status code of the answer. */
4
+ readonly status: number;
5
+ /** The API's error code, or the status code as text when the answer carries none. */
6
+ readonly code: string;
7
+ constructor(status: number, code: string, message: string);
8
+ }
9
+ /** An error phantom raises itself, such as a missing flag or a refused payment. */
10
+ export declare class CliError extends Error {
11
+ /** A short code for the error, such as `keychain_failed`. `cli_error` when none is given. */
12
+ readonly code: string;
13
+ /** The process exit code {@link run} returns for it. 1 unless given. */
14
+ readonly exitCode: number;
15
+ constructor(message: string, code?: string, exitCode?: number);
16
+ }
17
+ /**
18
+ * Throws a {@link CliError}. Every refusal in phantom goes through here.
19
+ * @param msg The message the user sees.
20
+ * @param code The error code, printed in the JSON error.
21
+ * @param exitCode The process exit code.
22
+ */
23
+ export declare function die(msg: string, code?: string, exitCode?: number): never;
24
+ /** How to get a key, for every message about a missing one. */
25
+ export declare const GET_A_KEY = "Run phantom login to sign in, or set PHANTOM_API_KEY.";
26
+ /** The message for a command that needs a key and has none. */
27
+ export declare const NO_KEY = "No Phantom key yet. Run phantom login to sign in, or set PHANTOM_API_KEY.";
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Free phantom-1 requests a workspace gets each UTC day, before it has had $10
3
+ * of credit. Phantom's own limit is `FREE_ROUTER_CAPS.perDay` in the Phantom
4
+ * repo's `lib/config.ts`; change both together.
5
+ */
6
+ export declare const FREE_REQUESTS_A_DAY = 50;
7
+ /** The same, for requests a coding agent sends (`FREE_ROUTER_CAPS.perDayAgent` in the Phantom repo). */
8
+ export declare const FREE_AGENT_REQUESTS_A_DAY = 200;
9
+ /**
10
+ * The free offer in one line short enough for an 80-column terminal. It names
11
+ * the coding-agent limit, since the CLI sets up and starts agents.
12
+ */
13
+ export declare const FREE_LINE = "phantom-1 runs free models, 200 a day from agents, no card";
@@ -0,0 +1,75 @@
1
+ import type { Env } from './state.mts';
2
+ import { type KeySource, type PickIo } from './pick.mts';
3
+ /**
4
+ * Where a picker draws and reads, when this run can show one: a person at a
5
+ * terminal (or keys a test scripted), not CI. Null means use flags and the
6
+ * plain prompts instead.
7
+ */
8
+ export declare function pickIo(input: Pick<CommandInput, 'io' | 'env'>): PickIo | null;
9
+ /**
10
+ * Whether a command should draw its screen rather than print JSON: with
11
+ * `--table`, or when stdout is a terminal, unless `--json` asks for JSON.
12
+ * Scripts and agents read stdout through a pipe, so they keep getting JSON.
13
+ */
14
+ export declare function showsScreen(input: Pick<CommandInput, 'table' | 'io' | 'flags'>): boolean;
15
+ /**
16
+ * Prints an error to stderr as one line of JSON, `{"error":{...}}`, and
17
+ * returns the exit code: 2 for a key the API rejected (401 or 403), the
18
+ * {@link CliError}'s own code, or 1 for anything else.
19
+ */
20
+ export declare function handleError(err: unknown, stderr?: (s: string) => void, opts?: {
21
+ human?: boolean;
22
+ env?: Env;
23
+ }): number;
24
+ /**
25
+ * Reads `--name value`, `--name=value` and bare `--name` (true) from the
26
+ * arguments. A value that starts with `--` counts as the next flag. Anything
27
+ * not after a `--name` is skipped.
28
+ */
29
+ export declare function parseFlags(args: string[]): Record<string, string | true>;
30
+ /**
31
+ * A flag's value as a number, or undefined when the flag is absent.
32
+ * @throws {@link CliError} when the flag has no value or the value is not a number.
33
+ */
34
+ export declare function flagNum(flags: Record<string, string | true>, name: string): number | undefined;
35
+ /**
36
+ * A spending control's value for a key: a number of zero or more, `none` for no limit (null), or
37
+ * undefined when the flag is absent. A mistyped value stops the command, because a number that
38
+ * silently became "no limit" would remove the key's cap.
39
+ * @param dollars True for money flags, which may start with `$`.
40
+ * @throws {@link CliError} `key_usage` when the flag has no value, or the value is not a finite number of zero or more.
41
+ */
42
+ export declare function limitFlag(flags: Record<string, string | true>, name: string, dollars?: boolean): number | null | undefined;
43
+ /** Opens a URL in the user's default browser. */
44
+ export declare function openUrl(url: string): void;
45
+ /** Prints a result: JSON by default, or `render(data)` with `--table`. */
46
+ export declare function out(data: unknown, table: boolean, render: (d: unknown) => string, stdout?: (s: string) => void): void;
47
+ /** What `run()` hands the handler of each command: the parsed command line, and where output goes. */
48
+ export type CommandInput = {
49
+ /** The arguments after `phantom`. */
50
+ argv: string[];
51
+ /** The environment to read settings from. */
52
+ env: Env;
53
+ /** Where output goes, whether stderr and stdout are terminals, and how to ask a question. */
54
+ io: {
55
+ stdout: (s: string) => void;
56
+ stderr: (s: string) => void;
57
+ isTTY?: boolean;
58
+ stdoutIsTTY?: boolean;
59
+ /** The terminal's width. When set, screen text wider than it breaks at a word (`fitText`); JSON never does. */
60
+ columns?: number;
61
+ ask?: (question: string) => Promise<string>;
62
+ keys?: () => KeySource;
63
+ fromMenu?: boolean;
64
+ };
65
+ /** The key the command runs as. Empty for a command that needs none. */
66
+ apiKey: string;
67
+ /** The word after the command, when it is not a flag. */
68
+ subcommand: string | undefined;
69
+ /** The flags, from {@link parseFlags}. */
70
+ flags: Record<string, string | true>;
71
+ /** True with `--table`. */
72
+ table: boolean;
73
+ /** PHANTOM_BASE_URL, when set. */
74
+ baseUrl: string | undefined;
75
+ };
@@ -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
@@ -27,7 +28,7 @@ export function showsScreen(input) {
27
28
  * the commands that take one (`phantom key show`), then any flags. For
28
29
  * example "Run phantom setup to sign in" matches `phantom setup` only.
29
30
  */
30
- const COMMAND_IN_TEXT = /\bphantom [a-z][a-z-]*(?:(?<=(?:key|keys|workspace|plan|route|route rule)) [a-z][a-z-]*)?(?: --?[a-z][a-z-]*(?: <[^>]+>)?)*/g;
31
+ const COMMAND_IN_TEXT = /\bphantom [a-z][a-z-]*(?:(?<=(?:key|keys|workspace|route|route rule)) [a-z][a-z-]*)?(?: --?[a-z][a-z-]*(?: <[^>]+>)?)*/g;
31
32
  /**
32
33
  * Prints an error to stderr as one line of JSON, `{"error":{...}}`, and
33
34
  * returns the exit code: 2 for a key the API rejected (401 or 403), the
@@ -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
- const code = api ? api.code : err instanceof CliError ? err.code : 'unknown';
42
- const message = err instanceof Error ? err.message : String(err);
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>;
@@ -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 url = `${apiBase(baseUrl)}${path}`;
21
- const signal = AbortSignal.timeout(timeoutMs);
22
- let res;
23
- let json;
24
- try {
25
- res = await fetch(url, {
26
- method,
27
- headers: {
28
- Authorization: `Bearer ${apiKey}`,
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 apiError(res.status, json);
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 ||
@@ -81,7 +130,7 @@ export function apiError(status, json) {
81
130
  msg = typeof e.message === 'string' ? e.message : msg;
82
131
  }
83
132
  else if (typeof err === 'string') {
84
- // The plan routes answer { error: <code>, detail: <words> }.
133
+ // Some routes answer { error: <words> }; a detail, when one is sent, reads better.
85
134
  const detail = json.detail;
86
135
  msg = typeof detail === 'string' && detail ? detail : err;
87
136
  code = err;
@@ -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,3 @@
1
+ /** Environment variables, as `process.env` holds them. */
2
+ export type Env = Record<string, string | undefined>;
3
+ export declare function stateDir(env: Env): string;
@@ -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;
@@ -0,0 +1,2 @@
1
+ /** This release of phantom. `npm version` keeps it equal to the version in package.json. */
2
+ export declare const VERSION = "1.4.2";
@@ -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.0';
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>;