@phantomcodes/cli 1.6.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +138 -117
  2. package/bin/phantom.mjs +37 -2
  3. package/dist/agents/command.d.mts +8 -27
  4. package/dist/agents/command.mjs +323 -59
  5. package/dist/agents/login.d.mts +3 -0
  6. package/dist/agents/login.mjs +97 -0
  7. package/dist/agents/opencode-check.d.mts +15 -0
  8. package/dist/agents/opencode-check.mjs +193 -0
  9. package/dist/agents/phantom-key.d.mts +7 -0
  10. package/dist/agents/phantom-key.mjs +40 -0
  11. package/dist/agents/proxy.d.mts +26 -28
  12. package/dist/agents/proxy.mjs +225 -33
  13. package/dist/chatgpt/command.d.mts +2 -0
  14. package/dist/chatgpt/command.mjs +119 -0
  15. package/dist/chatgpt/session.d.mts +87 -0
  16. package/dist/chatgpt/session.mjs +253 -0
  17. package/dist/cli/accounts.d.mts +21 -0
  18. package/dist/cli/accounts.mjs +96 -0
  19. package/dist/cli/app.d.mts +4 -24
  20. package/dist/cli/app.mjs +224 -139
  21. package/dist/cli/commands.d.mts +1 -16
  22. package/dist/cli/commands.mjs +144 -239
  23. package/dist/cli/help.d.mts +0 -19
  24. package/dist/cli/help.mjs +30 -55
  25. package/dist/cli/run.mjs +35 -79
  26. package/dist/cli/start.d.mts +2 -31
  27. package/dist/cli/start.mjs +13 -116
  28. package/dist/core/brand.d.mts +0 -7
  29. package/dist/core/brand.mjs +0 -8
  30. package/dist/core/errors.d.mts +0 -16
  31. package/dist/core/errors.mjs +0 -16
  32. package/dist/core/helpers.d.mts +0 -46
  33. package/dist/core/helpers.mjs +1 -64
  34. package/dist/core/node-trust.d.mts +0 -5
  35. package/dist/core/node-trust.mjs +0 -6
  36. package/dist/core/pick.d.mts +7 -55
  37. package/dist/core/pick.mjs +49 -106
  38. package/dist/core/request.d.mts +0 -46
  39. package/dist/core/request.mjs +1 -60
  40. package/dist/core/secrets.d.mts +0 -4
  41. package/dist/core/secrets.mjs +0 -10
  42. package/dist/core/state.d.mts +3 -1
  43. package/dist/core/state.mjs +147 -4
  44. package/dist/core/style.d.mts +0 -27
  45. package/dist/core/style.mjs +0 -20
  46. package/dist/core/version.d.mts +1 -2
  47. package/dist/core/version.mjs +1 -2
  48. package/dist/local/accounts.d.mts +25 -0
  49. package/dist/local/accounts.mjs +40 -0
  50. package/dist/local/agent-headers.d.mts +7 -0
  51. package/dist/local/agent-headers.mjs +44 -0
  52. package/dist/local/chatgpt-plan.d.mts +147 -0
  53. package/dist/local/chatgpt-plan.mjs +384 -0
  54. package/dist/local/command.d.mts +24 -0
  55. package/dist/local/command.mjs +211 -0
  56. package/dist/local/config.d.mts +49 -0
  57. package/dist/local/config.mjs +168 -0
  58. package/dist/local/decide.d.mts +37 -0
  59. package/dist/local/decide.mjs +201 -0
  60. package/dist/local/failure-signs.d.mts +4 -0
  61. package/dist/local/failure-signs.mjs +99 -0
  62. package/dist/local/keys.d.mts +32 -0
  63. package/dist/local/keys.mjs +239 -0
  64. package/dist/local/models.d.mts +53 -0
  65. package/dist/local/models.mjs +117 -0
  66. package/dist/local/replay.d.mts +59 -0
  67. package/dist/local/replay.mjs +143 -0
  68. package/dist/local/report.d.mts +43 -0
  69. package/dist/local/report.mjs +153 -0
  70. package/dist/local/request-log.d.mts +53 -0
  71. package/dist/local/request-log.mjs +69 -0
  72. package/dist/local/retry-after.d.mts +3 -0
  73. package/dist/local/retry-after.mjs +28 -0
  74. package/dist/local/rust-router.d.mts +39 -0
  75. package/dist/local/rust-router.mjs +54 -0
  76. package/dist/local/server.d.mts +27 -0
  77. package/dist/local/server.mjs +449 -0
  78. package/dist/local/status-line.d.mts +17 -0
  79. package/dist/local/status-line.mjs +81 -0
  80. package/dist/local/tiers.d.mts +3 -0
  81. package/dist/local/tiers.mjs +137 -0
  82. package/dist/local/traces.d.mts +69 -0
  83. package/dist/local/traces.mjs +341 -0
  84. package/dist/phantom.d.mts +0 -37
  85. package/dist/phantom.mjs +0 -31
  86. package/package.json +15 -9
  87. package/skills/phantom-ai/SKILL.md +28 -97
  88. package/dist/cli/screens.d.mts +0 -177
  89. package/dist/cli/screens.mjs +0 -398
  90. package/dist/core/free.d.mts +0 -13
  91. package/dist/core/free.mjs +0 -14
  92. package/dist/core/motion.d.mts +0 -47
  93. package/dist/core/motion.mjs +0 -156
  94. package/dist/core/shapes.d.mts +0 -13
  95. package/dist/core/shapes.mjs +0 -1
  96. package/dist/keys/command.d.mts +0 -16
  97. package/dist/keys/command.mjs +0 -143
  98. package/dist/keys/saved.d.mts +0 -96
  99. package/dist/keys/saved.mjs +0 -169
  100. package/dist/models/choice.d.mts +0 -7
  101. package/dist/models/choice.mjs +0 -27
  102. package/dist/models/command.d.mts +0 -8
  103. package/dist/models/command.mjs +0 -66
  104. package/dist/models/list.d.mts +0 -39
  105. package/dist/models/list.mjs +0 -39
  106. package/dist/receipts/command.d.mts +0 -7
  107. package/dist/receipts/command.mjs +0 -41
  108. package/dist/receipts/receipts.d.mts +0 -76
  109. package/dist/receipts/receipts.mjs +0 -114
  110. package/dist/setup/agents.d.mts +0 -149
  111. package/dist/setup/agents.mjs +0 -886
  112. package/dist/setup/apply.d.mts +0 -85
  113. package/dist/setup/apply.mjs +0 -301
  114. package/dist/setup/command.d.mts +0 -12
  115. package/dist/setup/command.mjs +0 -307
  116. package/dist/setup/editors.d.mts +0 -108
  117. package/dist/setup/editors.mjs +0 -500
  118. package/dist/setup/legacy.d.mts +0 -13
  119. package/dist/setup/legacy.mjs +0 -36
  120. package/dist/setup/plan.d.mts +0 -104
  121. package/dist/setup/plan.mjs +0 -132
  122. package/dist/setup/screen.d.mts +0 -30
  123. package/dist/setup/screen.mjs +0 -260
  124. package/dist/setup/shared.d.mts +0 -141
  125. package/dist/setup/shared.mjs +0 -88
  126. package/dist/setup/was.d.mts +0 -42
  127. package/dist/setup/was.mjs +0 -91
  128. package/dist/spend/command.d.mts +0 -5
  129. package/dist/spend/command.mjs +0 -235
  130. package/dist/spend/lineup.d.mts +0 -61
  131. package/dist/spend/lineup.mjs +0 -39
  132. package/dist/spend/reason.d.mts +0 -5
  133. package/dist/spend/reason.mjs +0 -60
  134. package/dist/spend/report.d.mts +0 -105
  135. package/dist/spend/report.mjs +0 -68
  136. package/dist/spend/routing.d.mts +0 -74
  137. package/dist/spend/routing.mjs +0 -57
  138. package/dist/workspace/command.d.mts +0 -59
  139. package/dist/workspace/command.mjs +0 -871
@@ -3,52 +3,23 @@ import { PhantomApiError, CliError, die } from "./errors.mjs";
3
3
  import { colorOn, paint } from "./style.mjs";
4
4
  import { explainNetworkError } from "./request.mjs";
5
5
  import { Cancelled, canPick } from "./pick.mjs";
6
- /**
7
- * Where a picker draws and reads, when this run can show one: a person at a
8
- * terminal (or keys a test scripted), not CI. Null means use flags and the
9
- * plain prompts instead.
10
- */
11
6
  export function pickIo(input) {
12
7
  const { io, env } = input;
13
8
  if (!(io.keys ? io.isTTY : canPick(env, io.isTTY)))
14
9
  return null;
15
- // A command started from the menu goes back to it on Esc; one typed on its own quits.
16
10
  return { write: io.stderr, env, keys: io.keys, esc: io.fromMenu ? 'back' : 'cancel', columns: process.stderr.columns };
17
11
  }
18
- /**
19
- * Whether a command should draw its screen rather than print JSON: with
20
- * `--table`, or when stdout is a terminal, unless `--json` asks for JSON.
21
- * Scripts and agents read stdout through a pipe, so they keep getting JSON.
22
- */
23
- export function showsScreen(input) {
24
- return input.table || (Boolean(input.io.stdoutIsTTY) && !input.flags['json']);
25
- }
26
- /**
27
- * A phantom command inside a sentence: `phantom`, its name, a second word for
28
- * the commands that take one (`phantom key show`), then any flags. For
29
- * example "Run phantom setup to sign in" matches `phantom setup` only.
30
- */
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;
32
- /**
33
- * Prints an error to stderr as one line of JSON, `{"error":{...}}`, and
34
- * returns the exit code: 2 for a key the API rejected (401 or 403), the
35
- * {@link CliError}'s own code, or 1 for anything else.
36
- */
12
+ const COMMAND_IN_TEXT = /\bphantom (?:config(?: (?:show|models|key(?: (?:set|use-keychain|rm))?|chatgpt(?: (?:login|logout))?))?|[a-z][a-z-]*)(?: --?[a-z][a-z-]*(?: <[^>]+>)?)*/g;
37
13
  export function handleError(err, stderr = (s) => process.stderr.write(s), opts = {}) {
38
- // Ctrl+C in a picker: stop, with the code shells use for it (128 + SIGINT), and no error to read.
39
14
  if (err instanceof Cancelled)
40
15
  return 130;
41
16
  const api = err instanceof PhantomApiError ? err : null;
42
- // node's bare "fetch failed" from any caller reads as a sentence about the connection.
43
17
  const offline = explainNetworkError(err);
44
18
  const code = api ? api.code : err instanceof CliError ? err.code : offline ? 'network_error' : 'unknown';
45
19
  const message = offline ?? (err instanceof Error ? err.message : String(err));
46
20
  if (opts.human) {
47
- // A person at a terminal reads a sentence; the code stays for support, dimmed.
48
21
  const p = paint(opts.env ?? {}, colorOn(opts.env ?? {}, true));
49
22
  const lit = message.replace(COMMAND_IN_TEXT, (cmd) => p.cyan(cmd));
50
- // The server's answer keeps its status and code for support (HTTP 401, invalid_key). The CLI's own
51
- // errors already say what happened in the sentence, and their code is for scripts, which get it as JSON.
52
23
  const detail = api ? `HTTP ${api.status}, ${code}` : '';
53
24
  stderr(`\n ${p.red('✗')} ${lit}\n${detail ? p.dim(` ${detail}`) + '\n' : ''}\n`);
54
25
  }
@@ -59,11 +30,6 @@ export function handleError(err, stderr = (s) => process.stderr.write(s), opts =
59
30
  return api.status === 401 || api.status === 403 ? 2 : 1;
60
31
  return err instanceof CliError ? err.exitCode : 1;
61
32
  }
62
- /**
63
- * Reads `--name value`, `--name=value` and bare `--name` (true) from the
64
- * arguments. A value that starts with `--` counts as the next flag. Anything
65
- * not after a `--name` is skipped.
66
- */
67
33
  export function parseFlags(args) {
68
34
  const flags = {};
69
35
  for (let i = 0; i < args.length; i++) {
@@ -83,10 +49,6 @@ export function parseFlags(args) {
83
49
  }
84
50
  return flags;
85
51
  }
86
- /**
87
- * A flag's value as a number, or undefined when the flag is absent.
88
- * @throws {@link CliError} when the flag has no value or the value is not a number.
89
- */
90
52
  export function flagNum(flags, name) {
91
53
  const v = flags[name];
92
54
  if (v === undefined)
@@ -99,29 +61,6 @@ export function flagNum(flags, name) {
99
61
  die(`--${name} must be a number`);
100
62
  return n;
101
63
  }
102
- /**
103
- * A spending control's value for a key: a number above zero, `none` for no limit (null), or
104
- * undefined when the flag is absent. A mistyped value stops the command, because a number that
105
- * silently became "no limit" would remove the key's cap.
106
- * @param dollars True for money flags, which may start with `$`.
107
- * @throws {@link CliError} `key_usage` when the flag has no value, or the value is not a finite number above zero. The server refuses 0 for every one of these, and `setup --limit` does too.
108
- */
109
- export function limitFlag(flags, name, dollars = false) {
110
- const raw = flags[name];
111
- if (raw === undefined)
112
- return undefined;
113
- const example = dollars ? `--${name} 5 or --${name} none` : `--${name} 30 or --${name} none`;
114
- if (raw === true)
115
- die(`--${name} needs a value, such as ${example}.`, 'key_usage');
116
- const text = raw.trim();
117
- if (text === 'none')
118
- return null;
119
- const n = text === '' ? NaN : Number(dollars ? text.replace(/^\$/, '') : text);
120
- if (!Number.isFinite(n) || n <= 0)
121
- die(`--${name} must be ${dollars ? 'a number of dollars' : 'a number'} above 0, or none, such as ${example}. You gave "${raw}".`, 'key_usage');
122
- return n;
123
- }
124
- /** Opens a URL in the user's default browser. */
125
64
  export function openUrl(url) {
126
65
  try {
127
66
  if (new URL(url).protocol !== 'https:')
@@ -130,10 +69,8 @@ export function openUrl(url) {
130
69
  spawn(cmd, args, { detached: true, stdio: 'ignore' }).on('error', () => { }).unref();
131
70
  }
132
71
  catch {
133
- // The address is on stderr already.
134
72
  }
135
73
  }
136
- /** Prints a result: JSON by default, or `render(data)` with `--table`. */
137
74
  export function out(data, table, render, stdout = (s) => process.stdout.write(s)) {
138
75
  if (table) {
139
76
  stdout(render(data) + '\n');
@@ -4,9 +4,4 @@
4
4
  * forged phantom.codes could read the key this CLI sends. 24.22.1 rejects
5
5
  * those chains ("tls: reject chains containing blocked public keys").
6
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
7
  export declare function nodeTrustWarning(version: string): string | null;
@@ -4,13 +4,7 @@
4
4
  * forged phantom.codes could read the key this CLI sends. 24.22.1 rejects
5
5
  * those chains ("tls: reject chains containing blocked public keys").
6
6
  */
7
- /** The first Node 24 that rejects the compromised chains. */
8
7
  const FIXED = [24, 22, 1];
9
- /**
10
- * A warning for stderr when `version` (`process.versions.node`) is a Node 24
11
- * older than 24.22.1, or null. Other majors get none: the CLI needs 24 or newer,
12
- * and the newer lines carry the fix.
13
- */
14
8
  export function nodeTrustWarning(version) {
15
9
  const [major, minor, patch] = version.split('.').map(Number);
16
10
  if (major !== FIXED[0])
@@ -1,25 +1,13 @@
1
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
2
  export type Choice<T> = {
4
3
  label: string;
5
4
  hint?: string;
6
5
  value: T;
7
6
  };
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
7
  export type KeySource = {
14
8
  next(): Promise<string>;
15
9
  close(): void;
16
10
  };
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
11
  export type PickIo = {
24
12
  write: (s: string) => void;
25
13
  env: Env;
@@ -27,59 +15,23 @@ export type PickIo = {
27
15
  esc?: 'back' | 'quit' | 'cancel';
28
16
  columns?: number;
29
17
  };
30
- /** Thrown by a picker when Ctrl+C is pressed: stop the whole command, wherever it is. */
31
18
  export declare class Cancelled extends Error {
32
19
  constructor();
33
20
  }
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
21
  export declare class BackToMenu extends Error {
39
22
  constructor();
40
23
  }
41
- /** Whether this run can show a picker: a person at a terminal on both ends, and not CI. */
42
24
  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
25
  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
26
  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
27
  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
- */
28
+ export declare function matching<T>(choices: Choice<T>[], text: string): Choice<T>[];
29
+ export declare function chooseOrType(io: PickIo, question: string, choices: Choice<string>[], opts?: {
30
+ check?: (text: string) => string | null;
31
+ rows?: number;
32
+ start?: number;
33
+ placeholder?: string;
34
+ }): Promise<string | null>;
83
35
  export declare function askText(io: PickIo, question: string, opts?: {
84
36
  placeholder?: string;
85
37
  check?: (text: string) => string | null;
@@ -1,33 +1,21 @@
1
- // Choosing with the keyboard: a list you move through with ↑ and ↓ (or j and
2
- // k) and pick with Enter, and a checklist you tick with Space. Drawn on
3
- // stderr in phantom's style, redrawn in place as you move, and folded into
4
- // one line (the question and your answer) once you choose. Only for a person
5
- // at a terminal: scripts, pipes and CI get the plain prompts or flags instead.
6
1
  import { emitKeypressEvents } from 'node:readline';
7
2
  import { colorOn, paint } from "./style.mjs";
8
- /** A hint cut to the room left on the line, so a row never wraps in a narrow window. */
9
3
  const fitHint = (hint, used, columns) => {
10
4
  const room = (columns ?? process.stderr.columns ?? 100) - used - 1;
11
5
  return hint.length <= room ? hint : room > 3 ? hint.slice(0, room - 1) + '…' : '';
12
6
  };
13
- /** Thrown by a picker when Ctrl+C is pressed: stop the whole command, wherever it is. */
14
7
  export class Cancelled extends Error {
15
8
  constructor() {
16
9
  super('Cancelled.');
17
10
  this.name = 'Cancelled';
18
11
  }
19
12
  }
20
- /**
21
- * Thrown by a command started from the start menu when Esc is pressed on its
22
- * first step, so the menu shows again instead of the command ending.
23
- */
24
13
  export class BackToMenu extends Error {
25
14
  constructor() {
26
15
  super('Back to the menu.');
27
16
  this.name = 'BackToMenu';
28
17
  }
29
18
  }
30
- /** Which way a key moves the marker: -1 up, 1 down, 0 not at all. */
31
19
  function step(key) {
32
20
  if (key === 'up' || key === 'k' || key === 'shift-tab')
33
21
  return -1;
@@ -35,16 +23,11 @@ function step(key) {
35
23
  return 1;
36
24
  return 0;
37
25
  }
38
- /** Whether this run can show a picker: a person at a terminal on both ends, and not CI. */
39
26
  export function canPick(env, stderrIsTTY, stdinIsTTY = Boolean(process.stdin.isTTY)) {
40
27
  if (env.CI && env.CI !== 'false' && env.CI !== '0')
41
28
  return false;
42
29
  return Boolean(stderrIsTTY) && stdinIsTTY;
43
30
  }
44
- /**
45
- * The keyboard, one key at a time, named the way pickers read them: `up`,
46
- * `down`, `return`, `space`, `escape`, `ctrl-c`, or the letter itself.
47
- */
48
31
  export function keyboard() {
49
32
  const input = process.stdin;
50
33
  emitKeypressEvents(input);
@@ -54,7 +37,6 @@ export function keyboard() {
54
37
  const waiting = [];
55
38
  const queued = [];
56
39
  const onKey = (text, key = {}) => {
57
- // A printable character comes through as itself, capitals and all, so the text box gets "Dana", not "dana".
58
40
  const printable = Boolean(text && text.length === 1 && text >= ' ' && !key.ctrl && (key.name === undefined || key.name.length === 1));
59
41
  const name = key.ctrl && key.name === 'c' ? 'ctrl-c' : key.name === 'enter' ? 'return' : key.shift && key.name === 'tab' ? 'shift-tab' : printable ? text : (key.name ?? text ?? '');
60
42
  const resolve = waiting.shift();
@@ -73,39 +55,22 @@ export function keyboard() {
73
55
  },
74
56
  };
75
57
  }
76
- /**
77
- * Keys from a list, for tests: each `next()` returns the next name, and `end`
78
- * once the list runs out (which pickers treat as Esc). Every picker in a run reads from the same list, as
79
- * they would from one keyboard.
80
- */
81
58
  export function scriptedKeys(names) {
82
59
  const left = [...names];
83
- // `end` when the list runs out: pickers read it as Esc; a wait that only listens for Esc ignores it.
84
60
  const source = { next: async () => left.shift() ?? 'end', close: () => { } };
85
61
  return () => source;
86
62
  }
87
- /** A block of lines that redraws itself in place: the first draw prints it, each later one moves up and writes over it. */
88
63
  function block(write) {
89
64
  let height = 0;
90
65
  return (lines) => {
91
66
  const up = height > 1 ? `\x1b[${height - 1}A` : '';
92
- // \x1b[J clears whatever the last draw left below, when the new one is shorter.
93
67
  write((height ? `\r${up}\x1b[J` : '') + lines.join('\n'));
94
68
  height = lines.length;
95
69
  };
96
70
  }
97
- /** The question line: a lime ? and the question in bold, then the answer once there is one. */
98
71
  const asked = (p, question, answer = '') => ` ${p.lime('?')} ${p.bold(question)}${answer ? ` ${p.cyan(answer)}` : ''}`;
99
- /** The answer a question shows after Esc: back, quit, or cancelled. */
100
72
  const escAnswer = (esc) => (esc === 'quit' ? 'quit' : esc === 'cancel' ? 'cancelled' : 'back');
101
- /** The hint under a picker: which keys do what. */
102
73
  const keysHint = (p, words) => ` ${p.dim(words)}`;
103
- /**
104
- * Asks a question with a list of answers. ↑ and ↓ (or k and j, or Tab and
105
- * Shift+Tab) move and Enter chooses. Esc or q returns null, which the caller
106
- * reads as "go back a step"; Ctrl+C throws {@link Cancelled} to stop the
107
- * whole command. `start` is where the marker begins.
108
- */
109
74
  export async function choose(io, question, choices, start = 0) {
110
75
  const p = paint(io.env, colorOn(io.env, true));
111
76
  const draw = block(io.write);
@@ -148,50 +113,57 @@ export async function choose(io, question, choices, start = 0) {
148
113
  keys.close();
149
114
  }
150
115
  }
151
- /**
152
- * A checklist: ↑ and ↓ (or Tab) move, Space ticks or unticks, `a` ticks all,
153
- * Enter goes on with the ticked items (it waits while none is ticked). Esc
154
- * or q returns null (go back); Ctrl+C throws {@link Cancelled}.
155
- */
156
- export async function checklist(io, question, items) {
116
+ const NAMED_KEYS = new Set(['up', 'down', 'left', 'right', 'tab', 'shift-tab', 'space', 'return', 'escape', 'ctrl-c', 'backspace', 'delete', 'end']);
117
+ export function matching(choices, text) {
118
+ const needle = text.trim().toLowerCase();
119
+ if (!needle)
120
+ return choices;
121
+ const hits = choices.filter((c) => c.label.toLowerCase().includes(needle) || (c.hint ?? '').toLowerCase().includes(needle));
122
+ return [...hits.filter((c) => c.label.toLowerCase() === needle), ...hits.filter((c) => c.label.toLowerCase() !== needle)];
123
+ }
124
+ export async function chooseOrType(io, question, choices, opts = {}) {
157
125
  const p = paint(io.env, colorOn(io.env, true));
158
126
  const draw = block(io.write);
159
- const ticked = items.map((i) => i.checked !== false);
160
- const width = Math.max(...items.map((i) => i.label.length)) + 3;
161
- let at = 0;
162
- let nudge = '';
163
- const frame = () => [
164
- asked(p, question),
165
- ...items.map((item, k) => {
166
- const box = ticked[k] ? p.lime('◉') : p.dim('◯');
167
- const label = k === at ? p.bold(item.label.padEnd(width)) : item.label.padEnd(width);
168
- return ` ${k === at ? p.lime('❯') : ' '} ${box} ${label}${p.dim(fitHint(item.hint ?? '', width + 6, io.columns))}`;
169
- }),
170
- nudge ? ` ${p.yellow(nudge)}` : keysHint(p, `↑↓ or tab move · space tick · a all · enter go on · esc ${io.esc ?? 'back'}`),
171
- ];
127
+ const rows = opts.rows ?? 8;
128
+ let text = '';
129
+ let at = Math.min(Math.max(0, opts.start ?? 0), Math.max(0, choices.length - 1));
130
+ let problem = '';
131
+ const frame = () => {
132
+ const hits = matching(choices, text);
133
+ const top = Math.max(0, Math.min(at - rows + 1, hits.length - rows));
134
+ const shown = hits.slice(top, top + rows);
135
+ const width = Math.max(0, ...shown.map((c) => c.label.length)) + 3;
136
+ return [
137
+ asked(p, question),
138
+ ` ${p.lime('›')} ${text ? p.bold(text) : p.dim(opts.placeholder ?? 'type to filter, or any id')}${p.lime('▏')}`,
139
+ ...shown.map((c, k) => top + k === at ? ` ${p.lime('❯')} ${p.bold(c.label.padEnd(width))}${p.dim(fitHint(c.hint ?? '', width + 4, io.columns))}` : ` ${c.label.padEnd(width)}${p.dim(fitHint(c.hint ?? '', width + 4, io.columns))}`),
140
+ ...(hits.length > top + rows ? [p.dim(` … ${hits.length - top - rows} more`)] : []),
141
+ ...(hits.length === 0 && text ? [p.dim(' no match: enter uses what you typed')] : []),
142
+ problem ? ` ${p.yellow(problem)}` : keysHint(p, `type to filter · ↑↓ move · enter choose · esc ${io.esc ?? 'back'}`),
143
+ ];
144
+ };
172
145
  const keys = (io.keys ?? keyboard)();
173
146
  io.write('\x1b[?25l');
174
147
  try {
175
148
  draw(frame());
176
149
  for (;;) {
177
150
  const key = await keys.next();
178
- nudge = '';
179
- if (step(key))
180
- at = (at + items.length + step(key)) % items.length;
181
- else if (key === 'space')
182
- ticked[at] = !ticked[at];
183
- else if (key === 'a')
184
- ticked.fill(!ticked.every(Boolean));
151
+ const hits = matching(choices, text);
152
+ problem = '';
153
+ if (key === 'up' || key === 'shift-tab')
154
+ at = hits.length ? (at + hits.length - 1) % hits.length : 0;
155
+ else if (key === 'down' || key === 'tab')
156
+ at = hits.length ? (at + 1) % hits.length : 0;
185
157
  else if (key === 'return') {
186
- if (!ticked.some(Boolean))
187
- nudge = 'Tick at least one, or press esc to go back.';
188
- else {
189
- const chosen = items.filter((_, k) => ticked[k]);
190
- draw([asked(p, question, chosen.map((i) => i.label).join(', '))]);
191
- return chosen.map((i) => i.value);
158
+ const answer = hits.length ? hits[at].value : text.trim();
159
+ const why = answer ? (opts.check?.(answer) ?? null) : 'Type a model id, or press esc.';
160
+ if (!why) {
161
+ draw([asked(p, question, answer)]);
162
+ return answer;
192
163
  }
164
+ problem = why;
193
165
  }
194
- else if (key === 'escape' || key === 'q' || key === 'end') {
166
+ else if (key === 'escape' || key === 'end') {
195
167
  draw([asked(p, question, escAnswer(io.esc))]);
196
168
  return null;
197
169
  }
@@ -199,6 +171,14 @@ export async function checklist(io, question, items) {
199
171
  draw([asked(p, question, 'cancelled')]);
200
172
  throw new Cancelled();
201
173
  }
174
+ else if (key === 'backspace' || key === 'delete') {
175
+ text = text.slice(0, -1);
176
+ at = 0;
177
+ }
178
+ else if (!NAMED_KEYS.has(key)) {
179
+ text += key;
180
+ at = 0;
181
+ }
202
182
  else
203
183
  continue;
204
184
  draw(frame());
@@ -209,48 +189,11 @@ export async function checklist(io, question, items) {
209
189
  keys.close();
210
190
  }
211
191
  }
212
- /**
213
- * Listens for Esc or Ctrl+C while something waits (sign-in waiting for
214
- * approval), without taking over the screen. `pressed` settles with the key;
215
- * other keys are ignored, and the end of a test's keys never settles it.
216
- */
217
- export function cancelKeys(source) {
218
- let closed = false;
219
- const pressed = new Promise((resolve) => {
220
- const listen = async () => {
221
- while (!closed) {
222
- const key = await source.next();
223
- if (key === 'end')
224
- return;
225
- if (key === 'escape' || key === 'q')
226
- return resolve('escape');
227
- if (key === 'ctrl-c')
228
- return resolve('ctrl-c');
229
- }
230
- };
231
- void listen();
232
- });
233
- return {
234
- pressed,
235
- close: () => {
236
- closed = true;
237
- source.close();
238
- },
239
- };
240
- }
241
- /**
242
- * Asks for a short piece of text, such as a key's name or an amount: type it,
243
- * Backspace to fix it, Enter to go on (it waits while `check` refuses the
244
- * text, and shows why), Esc to go back (null), Ctrl+C to stop. Keys longer
245
- * than one character that aren't named keys are typed as text, so a test can
246
- * send "sam" as one key.
247
- */
248
192
  export async function askText(io, question, opts = {}) {
249
193
  const p = paint(io.env, colorOn(io.env, true));
250
194
  const draw = block(io.write);
251
195
  let text = '';
252
196
  let problem = '';
253
- const NAMED = new Set(['up', 'down', 'left', 'right', 'tab', 'shift-tab', 'space', 'return', 'escape', 'ctrl-c', 'backspace', 'delete', 'end']);
254
197
  const frame = () => [
255
198
  asked(p, question),
256
199
  ` ${p.lime('❯')} ${text ? p.bold(text) : p.dim(opts.placeholder ?? '')}${p.lime('▏')}`,
@@ -283,7 +226,7 @@ export async function askText(io, question, opts = {}) {
283
226
  text = text.slice(0, -1);
284
227
  else if (key === 'space')
285
228
  text += ' ';
286
- else if (!NAMED.has(key))
229
+ else if (!NAMED_KEYS.has(key))
287
230
  text += key;
288
231
  draw(frame());
289
232
  }
@@ -1,64 +1,18 @@
1
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
2
  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
3
  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
4
  export type Answer = {
12
5
  json: unknown;
13
6
  kind: 'json' | 'empty' | 'text';
14
7
  };
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
8
  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
9
  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
10
  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
11
  export declare function fetchAnswer(url: string, init: RequestInit, label: string, timeoutMs?: number): Promise<{
36
12
  res: Response;
37
13
  answer: Answer;
38
14
  }>;
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
15
  export declare function request<T>(method: string, path: string, apiKey: string, body?: unknown, baseUrl?: string, headers?: Record<string, string>, timeoutMs?: number): Promise<T>;
53
16
  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
17
  export declare function httpsOnly(baseUrl: string): string;
59
18
  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>;