@phantomcodes/cli 1.4.1 → 1.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -2
- package/dist/agents/command.d.mts +36 -0
- package/dist/agents/command.mjs +19 -7
- package/dist/agents/proxy.d.mts +44 -0
- package/dist/agents/proxy.mjs +4 -2
- package/dist/cli/app.d.mts +25 -0
- package/dist/cli/commands.d.mts +19 -0
- package/dist/cli/commands.mjs +1 -1
- package/dist/cli/help.d.mts +26 -0
- package/dist/cli/run.d.mts +2 -0
- package/dist/cli/screens.d.mts +171 -0
- package/dist/cli/start.d.mts +34 -0
- package/dist/core/brand.d.mts +12 -0
- package/dist/core/errors.d.mts +27 -0
- package/dist/core/free.d.mts +13 -0
- package/dist/core/helpers.d.mts +75 -0
- package/dist/core/helpers.mjs +27 -2
- package/dist/core/motion.d.mts +47 -0
- package/dist/core/node-trust.d.mts +12 -0
- package/dist/core/pick.d.mts +86 -0
- package/dist/core/request.d.mts +64 -0
- package/dist/core/request.mjs +78 -29
- package/dist/core/secrets.d.mts +33 -0
- package/dist/core/shapes.d.mts +13 -0
- package/dist/core/state.d.mts +3 -0
- package/dist/core/style.d.mts +49 -0
- package/dist/core/version.d.mts +2 -0
- package/dist/core/version.mjs +1 -1
- package/dist/keys/command.d.mts +16 -0
- package/dist/keys/saved.d.mts +88 -0
- package/dist/models/choice.d.mts +7 -0
- package/dist/models/choice.mjs +1 -1
- package/dist/models/command.d.mts +8 -0
- package/dist/models/list.d.mts +39 -0
- package/dist/phantom.d.mts +45 -0
- package/dist/receipts/command.d.mts +7 -0
- package/dist/receipts/receipts.d.mts +67 -0
- package/dist/receipts/receipts.mjs +15 -11
- package/dist/setup/agents.d.mts +149 -0
- package/dist/setup/agents.mjs +48 -35
- package/dist/setup/apply.d.mts +71 -0
- package/dist/setup/apply.mjs +7 -2
- package/dist/setup/command.d.mts +12 -0
- package/dist/setup/editors.d.mts +101 -0
- package/dist/setup/editors.mjs +4 -2
- package/dist/setup/legacy.d.mts +13 -0
- package/dist/setup/plan.d.mts +104 -0
- package/dist/setup/plan.mjs +5 -3
- package/dist/setup/screen.d.mts +30 -0
- package/dist/setup/shared.d.mts +141 -0
- package/dist/setup/shared.mjs +8 -2
- package/dist/setup/was.d.mts +42 -0
- package/dist/setup/was.mjs +91 -0
- package/dist/spend/command.d.mts +5 -0
- package/dist/spend/lineup.d.mts +54 -0
- package/dist/spend/lineup.mjs +3 -2
- package/dist/spend/report.d.mts +105 -0
- package/dist/spend/routing.d.mts +72 -0
- package/dist/workspace/command.d.mts +46 -0
- package/dist/workspace/command.mjs +83 -37
- package/package.json +2 -2
|
@@ -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>;
|
package/dist/spend/lineup.mjs
CHANGED
|
@@ -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
|
|
5
|
-
* repo), so the CLI
|
|
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>;
|
|
@@ -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 {};
|
|
@@ -2,12 +2,12 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import { hostname } from 'node:os';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
5
|
-
import { DEFAULT_BASE_URL,
|
|
5
|
+
import { DEFAULT_BASE_URL, REQUEST_TIMEOUT_MS, answerError, fetchAnswer, httpsOnly } from "../core/request.mjs";
|
|
6
6
|
import { stateDir } from "../core/state.mjs";
|
|
7
7
|
import { writeSecret, readSecret, removeSecret, keychainOn } from "../core/secrets.mjs";
|
|
8
8
|
import { keyCommand, loginCommand } from "../keys/command.mjs";
|
|
9
9
|
import { die } from "../core/errors.mjs";
|
|
10
|
-
import {
|
|
10
|
+
import { limitFlag, openUrl, pickIo, showsScreen } from "../core/helpers.mjs";
|
|
11
11
|
import { BackToMenu, Cancelled, askText, cancelKeys, choose, keyboard } from "../core/pick.mjs";
|
|
12
12
|
import { spawnSync } from 'node:child_process';
|
|
13
13
|
import { onPath } from "../setup/shared.mjs";
|
|
@@ -16,8 +16,13 @@ import { alreadySignedInScreen, fundScreen, keyChangeScreen, keysScreen, payment
|
|
|
16
16
|
import { keyId, keyPath, listNamedKeys, namedKeyPath, readNamedKey, resolveApiKey, saveApiKey, saveNamedKey } from "../keys/saved.mjs";
|
|
17
17
|
const credentialPath = (env) => path.join(stateDir(env), 'workspace');
|
|
18
18
|
const base = (input) => httpsOnly(input.baseUrl || input.env.PHANTOM_BASE_URL || DEFAULT_BASE_URL).replace(/\/$/, '');
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
/**
|
|
20
|
+
* One call to the workspace API, with the limits every call shares ({@link fetchAnswer}): 30 seconds
|
|
21
|
+
* unless `timeoutMs` says less, and a plain message for a web page, an empty answer or no connection.
|
|
22
|
+
* @throws {@link PhantomApiError} when the API answers with an error status.
|
|
23
|
+
*/
|
|
24
|
+
export async function wire(url, method, endpoint, body, token, timeoutMs) {
|
|
25
|
+
const { res, answer } = await fetchAnswer(url + endpoint, {
|
|
21
26
|
method,
|
|
22
27
|
redirect: 'error',
|
|
23
28
|
headers: {
|
|
@@ -25,11 +30,12 @@ async function wire(url, method, endpoint, body, token) {
|
|
|
25
30
|
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
26
31
|
},
|
|
27
32
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
+
}, `${method} ${endpoint}`, timeoutMs);
|
|
34
|
+
if (!res.ok)
|
|
35
|
+
throw answerError(res.status, answer);
|
|
36
|
+
if (answer.kind === 'text')
|
|
37
|
+
die('Phantom AI sent a web page instead of data. Check PHANTOM_BASE_URL, and try again in a minute.', 'bad_answer');
|
|
38
|
+
return answer.json;
|
|
33
39
|
}
|
|
34
40
|
function credentials(input) {
|
|
35
41
|
const file = credentialPath(input.env);
|
|
@@ -194,15 +200,18 @@ async function pollForApproval(input, opts, ctx) {
|
|
|
194
200
|
io.stderr(' Sign-in cancelled. Nothing was saved.\n');
|
|
195
201
|
return 0;
|
|
196
202
|
}
|
|
203
|
+
// The sleep may have used up the time. One stuck request must not carry the wait past the deadline.
|
|
204
|
+
const left = deadline - Date.now();
|
|
205
|
+
if (left <= 0)
|
|
206
|
+
break;
|
|
197
207
|
let token;
|
|
198
208
|
try {
|
|
199
|
-
token = await wire(url, 'POST', '/auth/device/token', {
|
|
200
|
-
device_code: start.device_code,
|
|
201
|
-
});
|
|
209
|
+
token = await wire(url, 'POST', '/auth/device/token', { device_code: start.device_code }, undefined, Math.min(REQUEST_TIMEOUT_MS, left));
|
|
202
210
|
}
|
|
203
211
|
catch (error) {
|
|
204
212
|
const code = error.code;
|
|
205
|
-
|
|
213
|
+
// One poll that got no answer is not the end: ask again until the deadline.
|
|
214
|
+
if (code === 'authorization_pending' || code === 'request_timeout')
|
|
206
215
|
continue;
|
|
207
216
|
if (code === 'slow_down') {
|
|
208
217
|
interval += 5000;
|
|
@@ -298,6 +307,8 @@ export async function workspaceCommand(input) {
|
|
|
298
307
|
if (command === 'create' || command === 'rotate') {
|
|
299
308
|
if (flags.save === true)
|
|
300
309
|
die('--save requires a key name.');
|
|
310
|
+
// Checked before anything is sent: a mistyped limit must not turn into "no limit".
|
|
311
|
+
const typedLimit = limitFlag(flags, 'limit', true);
|
|
301
312
|
// keys create at a terminal with nothing given: a short form (name, then limit), and the key to hand over.
|
|
302
313
|
if (command === 'create' && flags.save === undefined && flags.limit === undefined) {
|
|
303
314
|
const pick = pickIo(input);
|
|
@@ -315,12 +326,9 @@ export async function workspaceCommand(input) {
|
|
|
315
326
|
const replacing = existsSync(target);
|
|
316
327
|
if (replacing && name !== mine)
|
|
317
328
|
die(`A key is already saved here as "${name}". Pick another name with --save <name>.`, 'key_exists');
|
|
318
|
-
const limit =
|
|
329
|
+
const limit = typedLimit ?? null;
|
|
319
330
|
const result = await wire(saved.base_url, 'POST', command === 'create' ? endpoint + '/keys' : endpoint + '/keys/' + String(id), command === 'create' ? { name, limit_usd: limit } : { action: 'rotate' }, saved.management_credential);
|
|
320
|
-
|
|
321
|
-
saveApiKey(env, result.api_key);
|
|
322
|
-
else
|
|
323
|
-
saveNamedKey(env, name, result.api_key, { replace: replacing });
|
|
331
|
+
saveIssuedKey(input, name, result.api_key, { replace: replacing, rotated: command === 'rotate' });
|
|
324
332
|
io.stdout(showsScreen(input)
|
|
325
333
|
? keyChangeScreen(command === 'create' ? 'created' : 'rotated', name, {
|
|
326
334
|
env,
|
|
@@ -361,6 +369,13 @@ export async function workspaceCommand(input) {
|
|
|
361
369
|
return 0;
|
|
362
370
|
}
|
|
363
371
|
if (command === 'set') {
|
|
372
|
+
// Every value is checked before the server is asked anything, so a typo changes nothing.
|
|
373
|
+
const typed = {
|
|
374
|
+
limit_usd: limitFlag(flags, 'limit', true),
|
|
375
|
+
budget_usd: limitFlag(flags, 'budget', true),
|
|
376
|
+
period_days: limitFlag(flags, 'period'),
|
|
377
|
+
rate_usd_per_min: limitFlag(flags, 'rate', true),
|
|
378
|
+
};
|
|
364
379
|
const which = await whichKey(input, saved, endpoint, 'change');
|
|
365
380
|
if (which === null)
|
|
366
381
|
return 0;
|
|
@@ -372,18 +387,12 @@ export async function workspaceCommand(input) {
|
|
|
372
387
|
const limit = await chooseLimit(pick);
|
|
373
388
|
if (limit === undefined)
|
|
374
389
|
return 0;
|
|
375
|
-
|
|
390
|
+
typed.limit_usd = limit;
|
|
376
391
|
}
|
|
377
392
|
const body = {};
|
|
378
|
-
const
|
|
379
|
-
limit_usd: flags.limit,
|
|
380
|
-
budget_usd: flags.budget,
|
|
381
|
-
period_days: flags.period,
|
|
382
|
-
rate_usd_per_min: flags.rate,
|
|
383
|
-
};
|
|
384
|
-
for (const [field, value] of Object.entries(controls))
|
|
393
|
+
for (const [field, value] of Object.entries(typed))
|
|
385
394
|
if (value !== undefined)
|
|
386
|
-
body[field] = value
|
|
395
|
+
body[field] = value;
|
|
387
396
|
if (typeof flags.name === 'string')
|
|
388
397
|
body.name = flags.name;
|
|
389
398
|
if (typeof flags['policy-file'] === 'string')
|
|
@@ -542,6 +551,8 @@ function leaveFund(input) {
|
|
|
542
551
|
input.io.stderr(' Nothing was charged.\n');
|
|
543
552
|
return 0;
|
|
544
553
|
}
|
|
554
|
+
/** Keys that still work. A rotate or revoke leaves the old key in the list, turned off. */
|
|
555
|
+
const stillOn = (keys) => keys.filter((k) => k.is_active !== false);
|
|
545
556
|
/**
|
|
546
557
|
* The key a key command acts on. --id may be the id, its first few
|
|
547
558
|
* characters, the key's name, or the start of the key, the way people
|
|
@@ -560,7 +571,7 @@ async function whichKey(input, saved, endpoint, verb) {
|
|
|
560
571
|
const pick = pickIo(input);
|
|
561
572
|
if (!pick)
|
|
562
573
|
die(`Say which key with --id: its id, name or start. For example: phantom keys ${verb === 'change' ? 'set' : verb} --id CI${verb === 'change' ? ' --limit 5' : ''}`, 'key_usage');
|
|
563
|
-
const chosen = await choose(pick, `Which key do you want to ${verb}?`, view.keys.map((k) => ({
|
|
574
|
+
const chosen = await choose(pick, `Which key do you want to ${verb}?`, stillOn(view.keys).map((k) => ({
|
|
564
575
|
label: k.name ?? 'Key',
|
|
565
576
|
hint: `${k.prefix ?? ''} · id ${k.id.slice(0, 8)} · spent $${(k.spent_usd ?? 0).toFixed(2)}`,
|
|
566
577
|
value: k.id,
|
|
@@ -571,17 +582,28 @@ async function whichKey(input, saved, endpoint, verb) {
|
|
|
571
582
|
input.io.stderr(' Nothing was changed.\n');
|
|
572
583
|
return chosen === null ? null : named(chosen);
|
|
573
584
|
}
|
|
574
|
-
/**
|
|
575
|
-
|
|
585
|
+
/**
|
|
586
|
+
* 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.
|
|
587
|
+
* Keys that are turned off never match: after a rotate, the old key and the new one share a name.
|
|
588
|
+
*/
|
|
589
|
+
export function findKey(allKeys, typed) {
|
|
590
|
+
const keys = stillOn(allKeys);
|
|
576
591
|
const t = typed.trim().toLowerCase();
|
|
577
|
-
const
|
|
578
|
-
|
|
579
|
-
|
|
592
|
+
const matching = (list) => {
|
|
593
|
+
const hits = list.filter((k) => k.id.toLowerCase() === t);
|
|
594
|
+
return hits.length ? hits : list.filter((k) => (t.length >= 4 && k.id.toLowerCase().startsWith(t)) || k.name?.toLowerCase() === t || (t.length >= 8 && k.prefix?.toLowerCase().startsWith(t)));
|
|
595
|
+
};
|
|
596
|
+
const loose = matching(keys);
|
|
597
|
+
const label = (k) => `${k.name ?? 'Key'} (${k.id.slice(0, 8)})`;
|
|
580
598
|
if (loose.length === 1)
|
|
581
599
|
return loose[0].id;
|
|
582
|
-
if (!loose.length)
|
|
583
|
-
|
|
584
|
-
|
|
600
|
+
if (!loose.length) {
|
|
601
|
+
const off = matching(allKeys.filter((k) => k.is_active === false));
|
|
602
|
+
if (off.length)
|
|
603
|
+
die(`"${typed}" is a key that is turned off (${off.map(label).join(', ')}). Your keys that work: ${keys.map(label).join(', ') || 'none'}.`, 'key_not_found');
|
|
604
|
+
die(`No key matches "${typed}". Your keys: ${keys.map(label).join(', ') || 'none yet'}.`, 'key_not_found');
|
|
605
|
+
}
|
|
606
|
+
die(`"${typed}" matches more than one key: ${loose.map(label).join(', ')}. Use more of the id.`, 'key_ambiguous');
|
|
585
607
|
}
|
|
586
608
|
/** The name a key with this id is saved under on this computer, if any: `default` for the login key. */
|
|
587
609
|
function savedNameFor(env, id) {
|
|
@@ -632,7 +654,7 @@ async function newKeyForm(input, pick, saved, endpoint) {
|
|
|
632
654
|
if (limit === undefined)
|
|
633
655
|
return leaveKeys(input);
|
|
634
656
|
const result = await wire(saved.base_url, 'POST', endpoint + '/keys', { name, limit_usd: limit }, saved.management_credential);
|
|
635
|
-
|
|
657
|
+
saveIssuedKey(input, name, result.api_key, { rotated: false });
|
|
636
658
|
const style = {
|
|
637
659
|
env,
|
|
638
660
|
color: colorOn(env, io.stdoutIsTTY),
|
|
@@ -656,6 +678,30 @@ async function newKeyForm(input, pick, saved, endpoint) {
|
|
|
656
678
|
}
|
|
657
679
|
return 0;
|
|
658
680
|
}
|
|
681
|
+
/**
|
|
682
|
+
* Saves a key the server has just made. When the save fails (a read-only file, a locked Keychain over
|
|
683
|
+
* SSH), this computer is the only place the key ever exists, so it goes to stderr once with how to
|
|
684
|
+
* save it, and the command exits 1. After a rotate the old key is already off, and the message says so.
|
|
685
|
+
*/
|
|
686
|
+
function saveIssuedKey(input, name, key, opts) {
|
|
687
|
+
const { env, io } = input;
|
|
688
|
+
try {
|
|
689
|
+
if (name === 'default')
|
|
690
|
+
saveApiKey(env, key);
|
|
691
|
+
else
|
|
692
|
+
saveNamedKey(env, name, key, { replace: opts.replace });
|
|
693
|
+
}
|
|
694
|
+
catch (error) {
|
|
695
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
696
|
+
const how = name === 'default' ? 'phantom login --paste (paste the key when it asks)' : `phantom keys save ${name} (paste the key when it asks)`;
|
|
697
|
+
io.stderr(`\nphantom made your new key but could not save it on this computer: ${why}\n` +
|
|
698
|
+
(opts.rotated ? 'Your old key is turned off, so this new key is the only one that works.\n' : '') +
|
|
699
|
+
'This is the only time it is shown. Copy it somewhere private now; it works like a password:\n\n' +
|
|
700
|
+
` ${key}\n\n` +
|
|
701
|
+
`Save it once the problem is fixed with: ${how}\n`);
|
|
702
|
+
die('The new key was not saved here.', 'key_not_saved');
|
|
703
|
+
}
|
|
704
|
+
}
|
|
659
705
|
/** Esc out of a key form: back to the menu if it started this, otherwise say nothing changed. */
|
|
660
706
|
function leaveKeys(input) {
|
|
661
707
|
if (input.io.fromMenu)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@phantomcodes/cli",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.2",
|
|
4
4
|
"description": "AI inference for your coding agents. Route models, control spending, and fund your workspace.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"phantom",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"repository": {
|
|
26
26
|
"type": "git",
|
|
27
27
|
"url": "git+https://github.com/connortessaro/phantom.git",
|
|
28
|
-
"directory": "
|
|
28
|
+
"directory": "cli"
|
|
29
29
|
},
|
|
30
30
|
"type": "module",
|
|
31
31
|
"bin": {
|