@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,30 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import type { SetupResult } from './plan.mts';
3
+ /** Which moment the screen shows. */
4
+ export type ScreenMode =
5
+ /** Before "Make these changes?": what setup is about to do. */
6
+ 'ask'
7
+ /** `--dry-run`: what setup would do; nothing was written. */
8
+ | 'dry'
9
+ /** The user said no at the prompt. */
10
+ | 'declined'
11
+ /** The changes are made. */
12
+ | 'done';
13
+ export type ScreenOptions = {
14
+ /** The environment, for the home folder (shown as ~) and the terminal's colors. */
15
+ env?: Env;
16
+ /** Print color, and the ghost. Off unless asked for, so tests and pipes get plain text. */
17
+ color?: boolean;
18
+ /** Show every line each file gains or loses (`--diff`). */
19
+ diff?: boolean;
20
+ /** Which moment to show. Worked out from the result when left out. */
21
+ mode?: ScreenMode;
22
+ /** The terminal's width, so long lines wrap at a word with an indent. 100 when unknown. */
23
+ columns?: number;
24
+ /** Say how to see every line. Off when a picker offers that as a choice instead. */
25
+ hint?: boolean;
26
+ };
27
+ /** `text` broken at spaces into lines of at most `width` characters; a single longer word stays whole. */
28
+ export declare function wrapWords(text: string, width: number): string[];
29
+ /** `phantom setup`'s screen for one result. See {@link ScreenMode} for the moments it shows. */
30
+ export declare function setupScreen(r: SetupResult, opts?: ScreenOptions): string;
@@ -0,0 +1,141 @@
1
+ import type { Env } from '../core/state.mts';
2
+ import type { JsonWas } from './was.mts';
3
+ /** True when `bin` is a program on PATH. */
4
+ export declare function onPath(bin: string): boolean;
5
+ /**
6
+ * `phantom setup` installs the phantom-ai skill where each agent looks for skills,
7
+ * and points each agent's own model calls at Phantom AI. Every agent here
8
+ * reads the same SKILL.md format, so one file serves all of them.
9
+ *
10
+ * Nothing is written straight away. {@link planSetup} works out each file's
11
+ * text before and after, so `phantom setup` can show the change as a diff and ask
12
+ * first, and {@link applySetup} writes it, keeping a copy of each file it
13
+ * edits beside it as `<file>.phantom.bak`. Lines phantom adds to a TOML, YAML or shell
14
+ * file end with `# phantom setup`, so `--provider off` removes exactly those.
15
+ *
16
+ * The key never goes into an agent's config. Claude Code runs `phantom key show`
17
+ * through `apiKeyHelper`. Agents that read an environment variable get
18
+ * PHANTOM_API_KEY from a block phantom adds to the shell's startup file, which
19
+ * reads the key from the macOS Keychain (or `phantom key show`) each time a shell
20
+ * starts ({@link shellBlock}). Cursor and Cline keep their model settings on
21
+ * their own settings screens, so setup prints the steps.
22
+ */
23
+ /**
24
+ * What {@link planSetup} hands each agent's functions in {@link SETUP_AGENTS}.
25
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
26
+ */
27
+ export type SetupContext = {
28
+ /** The environment phantom runs in. */
29
+ env: Env;
30
+ /** The home folder agents are found in. */
31
+ home: string;
32
+ /** Whether a program is on PATH. Defaults to checking for real. */
33
+ onPath?: (bin: string) => boolean;
34
+ /** The model `--model` asked for, if any. */
35
+ model?: string;
36
+ /** The shell startup file the key block goes in ({@link shellRcFile}). */
37
+ shellRc: string;
38
+ };
39
+ /**
40
+ * One file a setup step changes.
41
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
42
+ */
43
+ export type SetupEdit = {
44
+ /** The file. */
45
+ file: string;
46
+ /** Its text after the change. null removes the file. */
47
+ after: string | null;
48
+ /** The file's mode, for a file that holds a key. */
49
+ mode?: number;
50
+ /** What setup recorded about the JSON keys it wrote, for `--provider off` to put back ({@link JsonWas}). null forgets the record. */
51
+ was?: JsonWas | null;
52
+ };
53
+ /**
54
+ * What {@link SetupAgentSpec.provider} returns.
55
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
56
+ */
57
+ export type ProviderPlan = {
58
+ /** The files to write. Empty for an agent set up on its settings screen or by the shell block alone. */
59
+ edits: SetupEdit[];
60
+ /** What to report. */
61
+ result: ProviderResult;
62
+ };
63
+ /** An agent name `phantom setup --agent` takes, other than `all`. */
64
+ export type SetupAgent = 'pi' | 'codex' | 'claude' | 'cursor' | 'opencode' | 'continue' | 'goose' | 'aider' | 'copilot' | 'cline' | 'gemini' | 'crush' | 'qwen' | 'kilo' | 'kimi' | 'droid' | 'vibe' | 'zed' | 'vscode' | 'jetbrains' | 'warp' | 'trae';
65
+ /**
66
+ * One agent `phantom setup` knows: where to find it, where its skill goes, and what else setup can do for it.
67
+ * @deprecated Compatibility export. Use {@link planSetup}, {@link applySetup}, and {@link restoreSetup} for agent setup.
68
+ */
69
+ export type SetupAgentSpec = {
70
+ /** The agent's name in messages, such as `Claude Code`. */
71
+ label: string;
72
+ /** The folder (or file) in the home directory whose presence means the agent is installed. */
73
+ home: string;
74
+ /** Whether the agent is installed, for one found somewhere other than {@link SetupAgentSpec.home}, such as `$CODEX_HOME`. */
75
+ detect?: (env: Env, home: string) => boolean;
76
+ /** The folder in the home directory the skill goes in. Left out for agents without skills. */
77
+ skills?: string;
78
+ /**
79
+ * Points the agent's own model calls at Phantom AI, or with `off` removes
80
+ * what phantom wrote. Throws a {@link CliError} with code `setup_unreadable` for
81
+ * a config file it can't edit safely, and setup skips that agent.
82
+ */
83
+ provider?: (ctx: SetupContext, off: boolean) => ProviderPlan;
84
+ /**
85
+ * Variables the agent reads, set in the shell block next to
86
+ * PHANTOM_API_KEY. A value may use `$PHANTOM_API_KEY`. Present (even empty)
87
+ * for every agent that reads the key from the environment.
88
+ */
89
+ shellEnv?: (ctx: SetupContext) => Record<string, string>;
90
+ };
91
+ /** The model setup starts each agent on when `--model` is not given. */
92
+ export declare const SETUP_MODEL = "phantom-1";
93
+ /** The coding agents Phantom AI serves at their own base path. */
94
+ export type AgentPath = 'codex' | 'claude-code' | 'cursor' | 'coding-agent' | 'gemini-cli';
95
+ /**
96
+ * The address Phantom AI serves a coding agent at, from PHANTOM_BASE_URL
97
+ * without its `/v1`: `/claude-code` (Claude Code adds `/v1` itself),
98
+ * `/gemini-cli` (Gemini CLI adds Google's `/v1beta`), or `/codex/v1`,
99
+ * `/cursor/v1` and `/coding-agent/v1` for the others.
100
+ * @throws {@link CliError} when PHANTOM_BASE_URL is not https ({@link httpsOnly}).
101
+ */
102
+ export declare function agentBaseUrl(env: Env, agent: AgentPath): string;
103
+ /** The end of every line phantom adds to a TOML, YAML or shell file. */
104
+ export declare const SETUP_MARK = "# phantom setup";
105
+ /** The start of a line phantom turned into a comment because it replaced it. `--provider off` puts it back. */
106
+ export declare const SETUP_WAS = "# phantom setup was: ";
107
+ /** True for a line setup added: it ends with {@link SETUP_MARK}, or the mark pai wrote. */
108
+ export declare function setupMarked(line: string): boolean;
109
+ /** The line without the setup mark on its end. */
110
+ export declare function stripMark(line: string): string;
111
+ /** A line setup turned into a comment, put back as it was. Other lines come back unchanged. */
112
+ export declare function unwas(line: string): string;
113
+ /** A file's text, or null when it does not exist. Other read errors pass through. */
114
+ export declare function readText(file: string): string | null;
115
+ /** Refuses a file setup can't edit safely. Setup skips the agent and says why. */
116
+ export declare function unreadable(file: string, why: string): never;
117
+ /** How to run this phantom from outside this shell: `phantom` if it's installed, else this node and script by absolute path. */
118
+ export declare function phantomCommand(onPathFn: (bin: string) => boolean): string;
119
+ /** `$XDG_CONFIG_HOME` when it is an absolute path, else `~/.config`. */
120
+ export declare function configHome(env: Env, home: string): string;
121
+ /** A writer's `off` result for a file it edits by removing its own lines or entries. */
122
+ export declare function offResult(label: string, file: string, text: string | null, after: string | null, forgetJsonWas?: boolean): ProviderPlan;
123
+ /** What {@link claudeProvider} changed, and what each agent's provider step reports. */
124
+ export type ProviderResult = {
125
+ /** The agent's settings file, or the shell startup file for an agent set up by environment variables alone. */
126
+ settings: string;
127
+ /** True when the agent now runs on Phantom AI; false after `--provider off`, and for an agent set up on its settings screen. */
128
+ on: boolean;
129
+ /** The base URL the agent now calls. */
130
+ base_url?: string;
131
+ /** The model the agent now starts with, if phantom set one. */
132
+ model?: string;
133
+ /** Things the user should know, such as an ANTHROPIC_AUTH_TOKEN in the shell that would win over the Phantom key. */
134
+ warnings: string[];
135
+ /** Steps to follow by hand, for an agent whose model settings live on its settings screen. */
136
+ manual?: string[];
137
+ };
138
+ /** A model as Claude Code names it: `phantom-1:zdr` is `claude-code/phantom-1:zdr`, and one that has the prefix keeps one. */
139
+ export declare function claudeModelName(model: string): string;
140
+ /** The context window Phantom AI's catalog gives phantom-1. Goose and Aider size requests by it. */
141
+ export declare const SETUP_CONTEXT_WINDOW = 1000000;
@@ -71,12 +71,18 @@ export function configHome(env, home) {
71
71
  return env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(home, '.config');
72
72
  }
73
73
  /** A writer's `off` result for a file it edits by removing its own lines or entries. */
74
- export function offResult(label, file, text, after) {
74
+ export function offResult(label, file, text, after, forgetJsonWas = false) {
75
75
  const changed = text !== null && after !== text;
76
76
  return {
77
- edits: changed ? [{ file, after: after || null }] : [],
77
+ edits: changed ? [{ file, after: after || null, ...(forgetJsonWas ? { was: null } : {}) }] : [],
78
78
  result: { settings: file, on: false, warnings: changed ? [] : [`${label} was not set to Phantom AI by phantom; nothing changed`] },
79
79
  };
80
80
  }
81
+ /** The prefix Claude Code's `/model` picker needs to keep a model: it drops ids without "claude" in them. The server strips it again. */
82
+ const CLAUDE_CODE_PREFIX = 'claude-code/';
83
+ /** A model as Claude Code names it: `phantom-1:zdr` is `claude-code/phantom-1:zdr`, and one that has the prefix keeps one. */
84
+ export function claudeModelName(model) {
85
+ return CLAUDE_CODE_PREFIX + (model.startsWith(CLAUDE_CODE_PREFIX) ? model.slice(CLAUDE_CODE_PREFIX.length) : model);
86
+ }
81
87
  /** The context window Phantom AI's catalog gives phantom-1. Goose and Aider size requests by it. */
82
88
  export const SETUP_CONTEXT_WINDOW = 1_000_000;
@@ -0,0 +1,42 @@
1
+ import { type Env } from '../core/state.mts';
2
+ import { type JsonChange } from './editors.mts';
3
+ /**
4
+ * What `phantom setup` replaced in a JSON settings file, so `--provider off` can put it back.
5
+ *
6
+ * TOML and YAML files keep this in the file itself: the replaced line stays as a `# phantom setup was:`
7
+ * comment. JSON has no comments, and Claude Code and the other agents read these files strictly, so
8
+ * the record lives in `setup-json-was.json` in the state folder instead (mode 600, because a replaced
9
+ * value can be a key the user had in the file).
10
+ */
11
+ /** One key setup wrote in a JSON file. */
12
+ export type JsonWasEntry = {
13
+ /** The keys from the top of the file down to the value, such as `['env', 'ANTHROPIC_MODEL']`. */
14
+ path: string[];
15
+ /** True when the key held a value before setup wrote it. */
16
+ had: boolean;
17
+ /** The value before setup wrote the key. Missing when `had` is false. */
18
+ was?: unknown;
19
+ /** What setup wrote. Off puts the old value back only while the key still holds this. */
20
+ wrote: unknown;
21
+ };
22
+ /** Every key setup wrote in one file. */
23
+ export type JsonWas = JsonWasEntry[];
24
+ /** What setup recorded for `file`, or an empty list. */
25
+ export declare function readJsonWas(env: Env, file: string): JsonWas;
26
+ /** Saves what setup recorded for `file`. null forgets it. */
27
+ export declare function writeJsonWas(env: Env, file: string, entries: JsonWas | null): void;
28
+ /**
29
+ * The record after setup writes `changes` to a file whose parsed content is `settings`. Each key remembers
30
+ * the value that was there. When setup runs again over its own value, the older record stays, so the
31
+ * user's first value survives any number of runs.
32
+ * @param previous What setup recorded for this file before.
33
+ * @param tracked The paths to record. Other changes are not remembered (a key setup adds to a list, say).
34
+ */
35
+ export declare function trackJsonChanges(settings: Record<string, unknown>, previous: JsonWas, changes: JsonChange[], tracked: string[][]): JsonWas;
36
+ /**
37
+ * The changes for `--provider off`. `removals` are what an agent's own off step would do (it knows which
38
+ * values look like phantom's); this swaps in the record: a key still holding what setup wrote gets its old
39
+ * value back, or goes if setup added it, and a key the user changed since is left alone. A container
40
+ * that a removal of a key setup added leaves empty goes too, and so does each one in `tidy` that ends up empty.
41
+ */
42
+ export declare function restoreJsonChanges(settings: Record<string, unknown>, record: JsonWas, removals: JsonChange[], tidy?: string[][]): JsonChange[];
@@ -0,0 +1,91 @@
1
+ import path from 'node:path';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { stateDir } from "../core/state.mjs";
5
+ import { jsonGet, jsonSet } from "./editors.mjs";
6
+ const recordFile = (env) => path.join(stateDir(env), 'setup-json-was.json');
7
+ function readAll(env) {
8
+ try {
9
+ return JSON.parse(readFileSync(recordFile(env), 'utf-8'));
10
+ }
11
+ catch {
12
+ return {};
13
+ }
14
+ }
15
+ /** What setup recorded for `file`, or an empty list. */
16
+ export function readJsonWas(env, file) {
17
+ return readAll(env)[file] ?? [];
18
+ }
19
+ /** Saves what setup recorded for `file`. null forgets it. */
20
+ export function writeJsonWas(env, file, entries) {
21
+ const all = readAll(env);
22
+ if (entries === null || entries.length === 0)
23
+ delete all[file];
24
+ else
25
+ all[file] = entries;
26
+ mkdirSync(stateDir(env), { recursive: true, mode: 0o700 });
27
+ writeFileSync(recordFile(env), JSON.stringify(all, null, 2) + '\n', { mode: 0o600 });
28
+ chmodSync(recordFile(env), 0o600);
29
+ }
30
+ const same = (a, b) => a.length === b.length && a.every((k, i) => k === b[i]);
31
+ const startsWith = (path, prefix) => prefix.length <= path.length && prefix.every((k, i) => k === path[i]);
32
+ /**
33
+ * The record after setup writes `changes` to a file whose parsed content is `settings`. Each key remembers
34
+ * the value that was there. When setup runs again over its own value, the older record stays, so the
35
+ * user's first value survives any number of runs.
36
+ * @param previous What setup recorded for this file before.
37
+ * @param tracked The paths to record. Other changes are not remembered (a key setup adds to a list, say).
38
+ */
39
+ export function trackJsonChanges(settings, previous, changes, tracked) {
40
+ const next = [...previous];
41
+ for (const [path, value] of changes) {
42
+ if (value === undefined || !tracked.some((t) => same(t, path)))
43
+ continue;
44
+ const current = jsonGet(settings, path);
45
+ const at = next.findIndex((e) => same(e.path, path));
46
+ // Setup's own value from an earlier run: the record of what came before it still holds.
47
+ if (at !== -1 && isDeepStrictEqual(current, next[at].wrote)) {
48
+ next[at] = { ...next[at], wrote: value };
49
+ continue;
50
+ }
51
+ const entry = { path, had: current !== undefined, ...(current !== undefined ? { was: current } : {}), wrote: value };
52
+ if (at === -1)
53
+ next.push(entry);
54
+ else
55
+ next[at] = entry;
56
+ }
57
+ return next;
58
+ }
59
+ /**
60
+ * The changes for `--provider off`. `removals` are what an agent's own off step would do (it knows which
61
+ * values look like phantom's); this swaps in the record: a key still holding what setup wrote gets its old
62
+ * value back, or goes if setup added it, and a key the user changed since is left alone. A container
63
+ * that a removal of a key setup added leaves empty goes too, and so does each one in `tidy` that ends up empty.
64
+ */
65
+ export function restoreJsonChanges(settings, record, removals, tidy = []) {
66
+ const restores = [];
67
+ for (const e of record) {
68
+ if (isDeepStrictEqual(jsonGet(settings, e.path), e.wrote))
69
+ restores.push([e.path, e.had ? e.was : undefined]);
70
+ }
71
+ // A removal at a tracked key, or above one, is the record's to decide.
72
+ const rest = removals.filter(([p]) => !record.some((e) => startsWith(e.path, p)));
73
+ const changes = [...restores, ...rest];
74
+ // Remove what setup created and left empty, starting from the nearest container.
75
+ const after = structuredClone(settings);
76
+ for (const [p, v] of changes)
77
+ jsonSet(after, p, v);
78
+ // The containers to check, nearest first: where a removed key lived, and each one asked for in `tidy`.
79
+ const containers = [...restores.filter(([, v]) => v === undefined).map(([p]) => p.slice(0, -1)), ...tidy].filter((c) => c.length > 0);
80
+ for (const container of containers) {
81
+ for (let depth = container.length; depth >= 1; depth--) {
82
+ const parent = container.slice(0, depth);
83
+ const node = jsonGet(after, parent);
84
+ if (!node || typeof node !== 'object' || Object.keys(node).length > 0)
85
+ break;
86
+ jsonSet(after, parent, undefined);
87
+ changes.push([parent, undefined]);
88
+ }
89
+ }
90
+ return changes;
91
+ }
@@ -0,0 +1,5 @@
1
+ import { type CommandInput } from '../core/helpers.mts';
2
+ /** `phantom route`: the key's route policy, its rules, and a dry run. Run by `run()`. */
3
+ export declare function routeCommand(input: CommandInput): Promise<number>;
4
+ /** `phantom lineup`: the model phantom-1 runs in each tier, and a fallback for each. Run by `run()`. */
5
+ export declare function lineupCommand(input: CommandInput): Promise<number>;
@@ -0,0 +1,54 @@
1
+ /**
2
+ * A key's lineup decides which model `phantom-1` runs in each tier. The server
3
+ * checks every pick against the tier's choices
4
+ * (routers/phantom-1/runtime/src/lineup.ts in the Phantom repo), so the CLI
5
+ * passes model ids through.
6
+ */
7
+ /** The three tiers `phantom-1` picks between, cheapest first. */
8
+ export declare const LINEUP_TIERS: readonly ["economy", "standard", "frontier"];
9
+ /** One of {@link LINEUP_TIERS}. */
10
+ export type LineupTier = (typeof LINEUP_TIERS)[number];
11
+ /** A model id for each tier that has one. */
12
+ export type LineupPicks = Partial<Record<LineupTier, string>>;
13
+ /** A key's lineup as the server stores it. A tier left out runs its default. */
14
+ export type Lineup = LineupPicks & {
15
+ /** The model to try when the tier's model fails. A tier left out keeps the usual fallback. */
16
+ fallbacks?: LineupPicks;
17
+ };
18
+ /** One model a tier can run, with its price per million tokens. */
19
+ export type LineupChoice = {
20
+ /** Model id. */
21
+ model: string;
22
+ /** Display name. */
23
+ name: string;
24
+ /** USD per million input tokens. null when the catalog doesn't list the model right now. */
25
+ input_per_m: number | null;
26
+ /** USD per million output tokens. null when the catalog doesn't list the model right now. */
27
+ output_per_m: number | null;
28
+ /** Context window in tokens. */
29
+ context: number | null;
30
+ /** True for the tier's default. */
31
+ default: boolean;
32
+ };
33
+ /** The model a tier runs. */
34
+ export type LineupTierModel = {
35
+ /** Model id. */
36
+ model: string;
37
+ /** Display name. */
38
+ name: string;
39
+ };
40
+ /** The answer from the /key/lineup calls. */
41
+ export type LineupResult = {
42
+ /** What the key changed from the defaults. null means every tier runs its default. */
43
+ lineup: Lineup | null;
44
+ /** The model each tier runs now. */
45
+ tiers: Record<LineupTier, LineupTierModel>;
46
+ /** Each tier's choices, default first. Only GET sends them. */
47
+ choices?: Record<LineupTier, LineupChoice[]>;
48
+ };
49
+ /** The key's lineup, the model each tier runs, and each tier's choices (GET /key/lineup). */
50
+ export declare function getLineup(apiKey: string, baseUrl?: string): Promise<LineupResult>;
51
+ /** Replaces the key's whole lineup (PUT /key/lineup). The server checks it before saving. */
52
+ export declare function putLineup(apiKey: string, lineup: Lineup, baseUrl?: string): Promise<LineupResult>;
53
+ /** Puts every tier back to its default (DELETE /key/lineup). */
54
+ export declare function resetLineup(apiKey: string, baseUrl?: string): Promise<LineupResult>;
@@ -1,8 +1,9 @@
1
1
  import { request } from "../core/request.mjs";
2
2
  /**
3
3
  * A key's lineup decides which model `phantom-1` runs in each tier. The server
4
- * checks every pick against the tier's choices (lib/lineup.ts in the Phantom
5
- * repo), so the CLI passes model ids through.
4
+ * checks every pick against the tier's choices
5
+ * (routers/phantom-1/runtime/src/lineup.ts in the Phantom repo), so the CLI
6
+ * passes model ids through.
6
7
  */
7
8
  /** The three tiers `phantom-1` picks between, cheapest first. */
8
9
  export const LINEUP_TIERS = ['economy', 'standard', 'frontier'];
@@ -0,0 +1,105 @@
1
+ import { type CommandInput } from '../core/helpers.mts';
2
+ /** One key or model's calls and cost. */
3
+ export type SpendLine = {
4
+ /** Calls, free ones included. */
5
+ calls: number;
6
+ /** What they cost, in US dollars. */
7
+ spent_usd: number;
8
+ };
9
+ /** Everything a spend report covers. */
10
+ export type SpendTotal = SpendLine & {
11
+ /** Prompt tokens, cached ones included. */
12
+ prompt_tokens: number;
13
+ /** Completion tokens. */
14
+ completion_tokens: number;
15
+ };
16
+ /** One model a key ran. */
17
+ export type SpendKeyModel = SpendLine & {
18
+ /** The model that ran. */
19
+ model: string;
20
+ };
21
+ /** One key's spend. */
22
+ export type SpendKey = SpendLine & {
23
+ /** The name the workspace gave the key, or `This key`. */
24
+ name: string;
25
+ /** The key's first characters, only in a workspace report; null otherwise. */
26
+ prefix: string | null;
27
+ /** False once the key was revoked or rotated away. */
28
+ active: boolean;
29
+ /** What phantom-1 saved on this key's calls, in US dollars; null when it can't be worked out. */
30
+ saved_usd: number | null;
31
+ /** The models the key ran, biggest spender first. */
32
+ models: SpendKeyModel[];
33
+ };
34
+ /** One model's spend across the keys in the report. */
35
+ export type SpendModel = SpendLine & {
36
+ /** The model that ran. */
37
+ model: string;
38
+ /** Prompt tokens. */
39
+ prompt_tokens: number;
40
+ /** Completion tokens. */
41
+ completion_tokens: number;
42
+ };
43
+ /** One UTC day's spend. */
44
+ export type SpendDay = SpendLine & {
45
+ /** The day, `YYYY-MM-DD`, UTC. */
46
+ date: string;
47
+ };
48
+ /** What phantom-1 routing saved: a figure, or the reason there is none. */
49
+ export type SpendRouting = {
50
+ /** True when the figures below are given. */
51
+ available: true;
52
+ /** Calls sent to a phantom-1 router. */
53
+ calls: number;
54
+ /** What those calls cost, in US dollars. */
55
+ spent_usd: number;
56
+ /** The model the same calls are priced on. */
57
+ baseline_model: string;
58
+ /** What the same calls would have cost on it, in US dollars. */
59
+ baseline_usd: number;
60
+ /** `baseline_usd` less `spent_usd`. */
61
+ saved_usd: number;
62
+ /** How `baseline_usd` is worked out, in words. */
63
+ basis: string;
64
+ } | {
65
+ /** False when the frontier model's price isn't listed. */
66
+ available: false;
67
+ /** Why there is no figure. */
68
+ reason: string;
69
+ };
70
+ /** The answer from `/key/spend` and `/workspaces/{id}/spend`. */
71
+ export type SpendResult = {
72
+ /** `key` for the calling key alone, `workspace` for every key in it. */
73
+ scope: 'key' | 'workspace';
74
+ /** First day, UTC, inclusive. */
75
+ from: string;
76
+ /** Last day, UTC, inclusive. */
77
+ to: string;
78
+ /** Everything in the range. */
79
+ total: SpendTotal;
80
+ /** Each key by name, biggest spender first. */
81
+ keys: SpendKey[];
82
+ /** Each model that ran, biggest spender first. */
83
+ models: SpendModel[];
84
+ /** Every day in the range, oldest first. */
85
+ days: SpendDay[];
86
+ /** What phantom-1 routing saved. */
87
+ routing: SpendRouting;
88
+ };
89
+ /** The `--from` and `--to` values, as parseFlags read them. */
90
+ export type SpendDates = {
91
+ /** The `--from` value. */
92
+ from?: string | true;
93
+ /** The `--to` value. */
94
+ to?: string | true;
95
+ };
96
+ /** What the key spent (GET /key/spend). */
97
+ export declare function getSpend(apiKey: string, dates?: SpendDates, baseUrl?: string): Promise<SpendResult>;
98
+ /** `--table` output for `spend`. */
99
+ export declare function tableSpend(d: unknown): string;
100
+ /**
101
+ * `phantom spend`: what the key spent, by model and day, and what phantom-1
102
+ * saved. `--workspace` shows every key in the workspace by name, with the
103
+ * workspace connection `phantom login` saved. Run by `run()`.
104
+ */
105
+ export declare function spendCommand(input: CommandInput): Promise<number>;
@@ -30,8 +30,6 @@ export function tableSpend(d) {
30
30
  `range ${s.from} to ${s.to} (UTC)`,
31
31
  `spent ${dollars(s.total.spent_usd)} (${calls(s.total.calls)})`,
32
32
  ];
33
- if (s.total.plan_usd > 0)
34
- lines.push(`paid by plan ${dollars(s.total.plan_usd)}`);
35
33
  if (!s.routing.available)
36
34
  lines.push(`phantom-1 saved not available: ${s.routing.reason}`);
37
35
  else if (s.routing.calls === 0)
@@ -0,0 +1,72 @@
1
+ /**
2
+ * A key's route policy decides which model `model: "auto"` runs. The server
3
+ * validates it and owns the list of conditions and actions
4
+ * (routers/phantom-1/runtime/src/route-policy.ts in the Phantom repo), so the
5
+ * CLI passes it through as JSON.
6
+ */
7
+ /** One routing rule: when the condition in `if` holds, run the model `use` names. */
8
+ export type RouteRule = {
9
+ /** Exactly one condition, such as `{ pace: 'ahead' }` or `{ input_tokens_over: 50000 }`. */
10
+ if: Record<string, string | number | boolean>;
11
+ /** A model from the policy's `models`, or `cheapest`, `first` or `next`. */
12
+ use: string;
13
+ };
14
+ /** A key's route policy, as the server stores and validates it. */
15
+ export type RoutePolicy = {
16
+ /** The models routing may pick from. The first is the default for `auto`. Empty: the policy holds preferences only (such as `sort`) and routes nothing. */
17
+ models: string[];
18
+ /** `auto` routes only requests for model `auto`; `all` routes every request. Default `auto`. */
19
+ applies_to?: 'auto' | 'all';
20
+ /** Rules checked in order. The first that matches picks the model. */
21
+ rules?: RouteRule[];
22
+ /** When the key's cap for the period is used up: `stop` refuses requests, `cheapest` keeps running on the cheapest model in `models`. Default `stop`. */
23
+ on_empty?: 'stop' | 'cheapest';
24
+ /** When true, the other models in `models` are tried if the picked one fails. Default false. */
25
+ fallback_on_error?: boolean;
26
+ /** Minutes a conversation stays on the model it started on after its last request, so its prompt cache stays warm. 0 turns it off. Default 5. */
27
+ stick_minutes?: number;
28
+ /** When true, a conversation without an x-phantom-session header is recognised by its opening messages. false: only the header counts. Default true. */
29
+ stick_by_prompt?: boolean;
30
+ /** Which providers serve this key's requests first: `cost` (cheapest, the default), `ttft` (quickest to start answering) or `tps` (most tokens a second). */
31
+ sort?: ProviderSort;
32
+ /** Only providers that delete prompts right away. */
33
+ zdr?: boolean;
34
+ /** Only providers that don't train on prompts. */
35
+ no_training?: boolean;
36
+ };
37
+ /** The provider orders the server takes for `sort`. */
38
+ export type ProviderSort = 'cost' | 'ttft' | 'tps';
39
+ /** The words `phantom route set --sort` takes, and the server's name for each. The server's own names work too. */
40
+ export declare const SORT_WORDS: Record<string, ProviderSort>;
41
+ /** The answer from the /key/route calls. */
42
+ export type RouteResult = {
43
+ /** The key's policy. null means none, and model `auto` is refused. */
44
+ route_policy: RoutePolicy | null;
45
+ };
46
+ /** The answer from POST /key/route/test. */
47
+ export type RouteTestResult = {
48
+ /** The model the request would run on. The server sends null when the key's cap is used up and the request would be refused. */
49
+ model: string | null;
50
+ /** What decided it: `<condition>:<value>` for a rule, or `default`, `requested`, `cache`, `on_empty` or `budget_exceeded`. The server sends null when the request is not routed and runs the model it named. */
51
+ reason: string | null;
52
+ /** True when the route policy picked the model, false when the request runs the model it named or is refused. */
53
+ routed: boolean;
54
+ /** Models tried next if this one fails, when `fallback_on_error` is on. */
55
+ fallbacks?: string[];
56
+ };
57
+ /** The key's route policy (GET /key/route). */
58
+ export declare function getRoute(apiKey: string, baseUrl?: string): Promise<RouteResult>;
59
+ /** Replaces the key's route policy (PUT /key/route). The server checks it before saving. */
60
+ export declare function putRoute(apiKey: string, policy: RoutePolicy, baseUrl?: string): Promise<RouteResult>;
61
+ /** Changes some top-level fields of the route policy and keeps the rest (PATCH /key/route). A list sent here replaces the whole list. */
62
+ export declare function patchRoute(apiKey: string, fields: Partial<RoutePolicy>, baseUrl?: string): Promise<RouteResult>;
63
+ /** Removes the key's route policy (DELETE /key/route). */
64
+ export declare function clearRoute(apiKey: string, baseUrl?: string): Promise<RouteResult>;
65
+ /** Which model a request would run on now, and why (POST /key/route/test). Nothing is charged. A route policy picks without calling a model; `phantom-1`, `phantom-1:zdr`, or `auto` on a key with no policy can call the model that picks the tier. `phantom-1:free` never does. */
66
+ export declare function testRoute(apiKey: string, opts: {
67
+ model: string;
68
+ messages?: unknown;
69
+ tools?: unknown;
70
+ }, baseUrl?: string): Promise<RouteTestResult>;
71
+ /** `pace=ahead` or `input_tokens_over=50000` into one rule condition. */
72
+ export declare function parseCondition(raw: string): Record<string, string | number | boolean>;
@@ -0,0 +1,46 @@
1
+ import { type Env } from '../core/state.mts';
2
+ import { type CommandInput } from '../core/helpers.mts';
3
+ /**
4
+ * One call to the workspace API, with the limits every call shares ({@link fetchAnswer}): 30 seconds
5
+ * unless `timeoutMs` says less, and a plain message for a web page, an empty answer or no connection.
6
+ * @throws {@link PhantomApiError} when the API answers with an error status.
7
+ */
8
+ export declare function wire<T>(url: string, method: string, endpoint: string, body?: unknown, token?: string, timeoutMs?: number): Promise<T>;
9
+ /** The management credential `phantom login` saved for this API address, or null when it saved none. */
10
+ export declare function savedManagement(input: CommandInput): string | null;
11
+ /** A read from the saved workspace, such as `/spend`, with its management credential. */
12
+ export declare function workspaceGet(input: CommandInput, path: string): Promise<unknown>;
13
+ /**
14
+ * Device authorization for accounts or guests, saving keys locally without copying a secret through the browser.
15
+ * With `inSetup`, `phantom setup` carries on once it is signed in, so it says that instead of printing the
16
+ * saved key's details and the next commands.
17
+ */
18
+ export declare function workspaceLogin(input: CommandInput, opts?: {
19
+ inSetup?: boolean;
20
+ }): Promise<number>;
21
+ /** Manage a workspace from the terminal: balance, keys, funding, recovery and revocation. */
22
+ export declare function workspaceCommand(input: CommandInput): Promise<number>;
23
+ /** Forget local management credentials and revoke server management access, leaving server-side keys and recovery files valid. True when there was a workspace sign-in to forget. */
24
+ export declare function forgetWorkspace(env: Env, baseUrl?: string): Promise<boolean>;
25
+ /**
26
+ * `--amount` as dollars: `10`, `10.50` or `$10`. A bare `--amount` is
27
+ * usually `--amount $5` after the shell has replaced `$5` with nothing, so
28
+ * the message says to leave out the $.
29
+ */
30
+ export declare function dollarsFlag(flags: Record<string, string | true>): number | undefined;
31
+ /** A workspace key as the view lists it: the parts used to find it by what people type. */
32
+ type ListedKey = {
33
+ id: string;
34
+ name?: string;
35
+ prefix?: string;
36
+ spent_usd?: number;
37
+ limit_usd?: number | null;
38
+ /** False for a key turned off by a rotate or revoke. Missing counts as on. */
39
+ is_active?: boolean;
40
+ };
41
+ /**
42
+ * Finds one key by id, the start of its id, its name, or the start of the key itself. Refuses when none or more than one matches.
43
+ * Keys that are turned off never match: after a rotate, the old key and the new one share a name.
44
+ */
45
+ export declare function findKey(allKeys: ListedKey[], typed: string): string;
46
+ export {};