@ody./pi-llmgateway 0.0.0-stage → 0.1.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.
- package/README.md +75 -2
- package/package.json +46 -4
- package/src/account/account-status.ts +92 -0
- package/src/account/footer-status.ts +55 -0
- package/src/account/footer-writes.ts +13 -0
- package/src/account/key-info.ts +102 -0
- package/src/account/register-account.ts +28 -0
- package/src/account/usage-command.ts +30 -0
- package/src/catalog/fetch-catalog.ts +76 -0
- package/src/catalog/gateway-models.ts +130 -0
- package/src/catalog/model-mapping.ts +133 -0
- package/src/index.ts +30 -0
- package/src/menu/footer-rows.ts +45 -0
- package/src/menu/menu-summary.ts +18 -0
- package/src/menu/menu-types.ts +44 -0
- package/src/menu/menu-widgets.ts +143 -0
- package/src/menu/model-rows.ts +113 -0
- package/src/menu/register-menu.ts +53 -0
- package/src/menu/routing-rows.ts +57 -0
- package/src/menu/top-rows.ts +75 -0
- package/src/pin/pin-command.ts +83 -0
- package/src/pin/pin-target.ts +61 -0
- package/src/pin/pin-writes.ts +35 -0
- package/src/pin/register-pin.ts +29 -0
- package/src/request/register-provider.ts +37 -0
- package/src/request/served-response.ts +31 -0
- package/src/request/stream-wrapper.ts +159 -0
- package/src/routing/completion-targets.ts +20 -0
- package/src/routing/config-store.ts +84 -0
- package/src/routing/register-routing.ts +30 -0
- package/src/routing/routing-command.ts +88 -0
- package/src/routing/routing-config.ts +96 -0
- package/src/routing/routing-writes.ts +80 -0
package/README.md
CHANGED
|
@@ -1,3 +1,76 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-llmgateway
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A [pi](https://pi.dev) extension that adds [LLM Gateway](https://llmgateway.io) as a model provider for DevPass and pay-as-you-go keys.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pi install npm:@ody./pi-llmgateway
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
To run from a checkout, pass `pi -e ./src/index.ts`.
|
|
12
|
+
|
|
13
|
+
## Authentication
|
|
14
|
+
|
|
15
|
+
Create an API key in the [LLM Gateway dashboard](https://llmgateway.io), then do one of the following:
|
|
16
|
+
|
|
17
|
+
- Run `/login`, choose **LLM Gateway**, and paste the key. pi stores it in `~/.pi/agent/auth.json`.
|
|
18
|
+
- Set `LLMGATEWAY_API_KEY` in your environment.
|
|
19
|
+
|
|
20
|
+
## Model selection
|
|
21
|
+
|
|
22
|
+
Open `/model` and filter by `llmgateway` or by author, such as `anthropic/`. On the command line, pass `--model llmgateway/anthropic/claude-sonnet-4-6`.
|
|
23
|
+
|
|
24
|
+
- **Live catalog:** Includes active text models that stream and call tools. Refreshes at most once an hour or when the API key changes.
|
|
25
|
+
- **Billed cost:** Sets each completed message's total cost to the USD amount LLM Gateway charged instead of the list-price estimate.
|
|
26
|
+
|
|
27
|
+
## Commands
|
|
28
|
+
|
|
29
|
+
Run `/llmgateway` for interactive configuration, or use the typed commands with Tab completion. All settings live in `~/.pi/agent/llmgateway.json` and apply immediately.
|
|
30
|
+
|
|
31
|
+
| Command | Purpose |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| `/llmgateway` | Open the settings menu for routing, per-model overrides, pins, footer statuses, and plan refresh |
|
|
34
|
+
| `/llmgateway-usage` | Show pay-as-you-go spend or DevPass meters and reset timers |
|
|
35
|
+
| `/llmgateway-routing` | Show or set routing strategy, service tier, and cross-provider fallback |
|
|
36
|
+
| `/llmgateway-pin` | Show or pin a model to a serving provider or region |
|
|
37
|
+
|
|
38
|
+
## Routing and provider pins
|
|
39
|
+
|
|
40
|
+
Configure defaults or per-model overrides in `/llmgateway`, or run `/llmgateway-routing` and `/llmgateway-pin`:
|
|
41
|
+
|
|
42
|
+
| Command | Effect |
|
|
43
|
+
| --- | --- |
|
|
44
|
+
| `/llmgateway-routing` | Show effective routing for `default` and configured models |
|
|
45
|
+
| `/llmgateway-routing <default\|model> sort <auto\|price\|throughput\|latency>` | Set the routing strategy |
|
|
46
|
+
| `/llmgateway-routing <default\|model> tier <auto\|default\|flex\|priority>` | Set the service tier |
|
|
47
|
+
| `/llmgateway-routing <default\|model> fallback <on\|off>` | Turn cross-provider failover on or off |
|
|
48
|
+
| `/llmgateway-routing <default\|model> reset` | Remove routing overrides and keep any pin |
|
|
49
|
+
| `/llmgateway-pin [model]` | Show all pins, or one model's pin and pinnable `provider[:region]` options |
|
|
50
|
+
| `/llmgateway-pin <model> <provider[:region]\|off>` | Set or remove a model's pin |
|
|
51
|
+
|
|
52
|
+
Plan and gateway rules apply in both the menu and typed commands:
|
|
53
|
+
|
|
54
|
+
- **DevPass:** Accepts `sort` values `auto` and `price`, `tier` values `auto`, `default`, and `flex`, and no provider pins.
|
|
55
|
+
- **Pay-as-you-go:** Accepts every strategy, every tier, and any provider or `provider:region` listed for the model.
|
|
56
|
+
- **Pinned requests:** Omit `sort` because the gateway rejects combining a strategy with a pin. Set `fallback off` to stop low-uptime failover. Pins can also reach deployments with smaller context windows.
|
|
57
|
+
- **Ignored values:** Requests omit stored settings that your plan or catalog rejects, and show commands mark them `(ignored ...)`.
|
|
58
|
+
|
|
59
|
+
## Footer statuses
|
|
60
|
+
|
|
61
|
+
The extension sets no footer status by default. Toggle keys under **Footer statuses** in `/llmgateway`, or list them in `"footer"` in `~/.pi/agent/llmgateway.json`.
|
|
62
|
+
|
|
63
|
+
| Key | Example | Shows |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `llmgateway-provider` | `aws-bedrock:eu` | Serving provider and region of the last response |
|
|
66
|
+
| `llmgateway-day` | `day 3.10/14.22` | DevPass daily meter |
|
|
67
|
+
| `llmgateway-premium` | `prem 5.00/18.96` | DevPass weekly premium meter |
|
|
68
|
+
| `llmgateway-month` | `mo 25.00/158.00` | DevPass monthly meter |
|
|
69
|
+
| `llmgateway-spend` | `$31.42/$50.00` | Pay-as-you-go spend and key limit |
|
|
70
|
+
| `llmgateway-premium-model` | `★` | Selected model costs at least $5/M input or $15/M output |
|
|
71
|
+
|
|
72
|
+
Only keys that match your active plan render, and switching away from `llmgateway` clears every status.
|
|
73
|
+
|
|
74
|
+
## License
|
|
75
|
+
|
|
76
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ody./pi-llmgateway",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "LLM Gateway as a native pi model provider: live catalog, routing preferences, billed cost and DevPass usage.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi-package",
|
|
9
|
+
"pi-extension"
|
|
10
|
+
],
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "https://codeberg.org/ody/pi-llmgateway.git"
|
|
14
|
+
},
|
|
15
|
+
"pi": {
|
|
16
|
+
"extensions": [
|
|
17
|
+
"./src/index.ts"
|
|
18
|
+
]
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"src",
|
|
22
|
+
"README.md"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"test": "vitest run",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"lint": "biome lint .",
|
|
28
|
+
"lint:fix": "biome lint --write .",
|
|
29
|
+
"check": "npm run lint && npm run typecheck && npm test",
|
|
30
|
+
"test:e2e": "vitest run --config vitest.e2e.config.ts"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@earendil-works/pi-ai": ">=1.0.0",
|
|
34
|
+
"@earendil-works/pi-coding-agent": ">=1.0.0",
|
|
35
|
+
"@earendil-works/pi-tui": ">=1.0.0",
|
|
36
|
+
"typebox": "*"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@biomejs/biome": "^2.6.7",
|
|
40
|
+
"@earendil-works/pi-ai": "^1.5.2",
|
|
41
|
+
"@earendil-works/pi-coding-agent": "^1.5.2",
|
|
42
|
+
"@earendil-works/pi-tui": "^1.5.2",
|
|
43
|
+
"@types/node": "^26.6.6",
|
|
44
|
+
"typebox": "^1.4.7",
|
|
45
|
+
"typescript": "7.0.2",
|
|
46
|
+
"vitest": "^5.1.0"
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ServedResponse } from "../request/served-response.ts";
|
|
3
|
+
import { accountTexts, clearedTexts, modelTexts, STATUS_KEYS, type StatusTexts, servedTexts } from "./footer-status.ts";
|
|
4
|
+
import type { KeyClient, KeyInfo } from "./key-info.ts";
|
|
5
|
+
|
|
6
|
+
export const ACCOUNT_REFRESH_MS = 30_000;
|
|
7
|
+
|
|
8
|
+
const METER_KEYS: readonly string[] = STATUS_KEYS.filter((key) => /-(day|premium|month|spend)$/.test(key));
|
|
9
|
+
|
|
10
|
+
export interface StatusContext {
|
|
11
|
+
hasUI: boolean;
|
|
12
|
+
ui: { setStatus(key: string, text: string | undefined): void };
|
|
13
|
+
modelRegistry: { getApiKeyForProvider(provider: string): Promise<string | undefined> };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface AccountStatusDeps {
|
|
17
|
+
providerId: string;
|
|
18
|
+
client: KeyClient;
|
|
19
|
+
footer: () => string[];
|
|
20
|
+
now: () => number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface AccountStatus {
|
|
24
|
+
select(ctx: StatusContext, model: Model<Api> | undefined): void;
|
|
25
|
+
agentEnd(ctx: StatusContext): void;
|
|
26
|
+
served(served: ServedResponse): void;
|
|
27
|
+
refresh(ctx: StatusContext, signal?: AbortSignal): Promise<KeyInfo>;
|
|
28
|
+
detach(): void;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function accountStatus(deps: AccountStatusDeps): AccountStatus {
|
|
32
|
+
let active: StatusContext | undefined;
|
|
33
|
+
let onGateway = false;
|
|
34
|
+
let lastRefresh = Number.NEGATIVE_INFINITY;
|
|
35
|
+
const shown = new Set<string>();
|
|
36
|
+
|
|
37
|
+
const show = (ctx: StatusContext | undefined, texts: StatusTexts): void => {
|
|
38
|
+
if (!ctx?.hasUI) return;
|
|
39
|
+
const listed = deps.footer();
|
|
40
|
+
try {
|
|
41
|
+
for (const key of [...shown].filter((key) => !listed.includes(key))) {
|
|
42
|
+
ctx.ui.setStatus(key, undefined);
|
|
43
|
+
shown.delete(key);
|
|
44
|
+
}
|
|
45
|
+
for (const [key, text] of Object.entries(texts)) {
|
|
46
|
+
if (!listed.includes(key)) continue;
|
|
47
|
+
ctx.ui.setStatus(key, text);
|
|
48
|
+
if (text === undefined) shown.delete(key);
|
|
49
|
+
else shown.add(key);
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
active = undefined;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const refresh = async (ctx: StatusContext, signal?: AbortSignal): Promise<KeyInfo> => {
|
|
57
|
+
lastRefresh = deps.now();
|
|
58
|
+
const info = await deps.client.fetch(await ctx.modelRegistry.getApiKeyForProvider(deps.providerId), signal);
|
|
59
|
+
if (onGateway && ctx === active) show(ctx, accountTexts(info));
|
|
60
|
+
return info;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
return {
|
|
64
|
+
select: (ctx, model) => {
|
|
65
|
+
active = ctx;
|
|
66
|
+
onGateway = model?.provider === deps.providerId;
|
|
67
|
+
if (!model || !onGateway) {
|
|
68
|
+
show(ctx, clearedTexts());
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
show(ctx, modelTexts(model));
|
|
72
|
+
const info = deps.client.last();
|
|
73
|
+
if (info) show(ctx, accountTexts(info));
|
|
74
|
+
else refresh(ctx).catch(() => {});
|
|
75
|
+
},
|
|
76
|
+
agentEnd: (ctx) => {
|
|
77
|
+
active = ctx;
|
|
78
|
+
if (!onGateway || deps.now() - lastRefresh < ACCOUNT_REFRESH_MS) return;
|
|
79
|
+
const listed = deps.footer();
|
|
80
|
+
if (!METER_KEYS.some((key) => listed.includes(key))) return;
|
|
81
|
+
refresh(ctx).catch(() => {});
|
|
82
|
+
},
|
|
83
|
+
served: (served) => {
|
|
84
|
+
if (onGateway) show(active, servedTexts(served));
|
|
85
|
+
},
|
|
86
|
+
refresh,
|
|
87
|
+
detach: () => {
|
|
88
|
+
active = undefined;
|
|
89
|
+
onGateway = false;
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ServedResponse } from "../request/served-response.ts";
|
|
3
|
+
import type { KeyInfo, Meter } from "./key-info.ts";
|
|
4
|
+
|
|
5
|
+
export const STATUS_KEYS = [
|
|
6
|
+
"llmgateway-provider",
|
|
7
|
+
"llmgateway-day",
|
|
8
|
+
"llmgateway-premium",
|
|
9
|
+
"llmgateway-month",
|
|
10
|
+
"llmgateway-spend",
|
|
11
|
+
"llmgateway-premium-model",
|
|
12
|
+
] as const;
|
|
13
|
+
|
|
14
|
+
export type StatusKey = (typeof STATUS_KEYS)[number];
|
|
15
|
+
export type StatusTexts = Partial<Record<StatusKey, string | undefined>>;
|
|
16
|
+
|
|
17
|
+
export function isPremium(model: Pick<Model<Api>, "cost">): boolean {
|
|
18
|
+
return model.cost.output >= 15 || model.cost.input >= 5;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function meterText(prefix: string, meter: Meter): string {
|
|
22
|
+
const used = meter.used.toFixed(2);
|
|
23
|
+
return meter.limit === undefined ? `${prefix}${used}` : `${prefix}${used}/${meter.limit.toFixed(2)}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function servedTexts(served: ServedResponse): StatusTexts {
|
|
27
|
+
const provider = served.provider && served.region ? `${served.provider}:${served.region}` : served.provider;
|
|
28
|
+
return { "llmgateway-provider": provider };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function accountTexts(info: KeyInfo): StatusTexts {
|
|
32
|
+
if (info.plan === "payg") {
|
|
33
|
+
const spend = info.spend.limit === undefined ? `$${info.spend.used.toFixed(2)}` : meterText("$", info.spend);
|
|
34
|
+
return {
|
|
35
|
+
"llmgateway-spend": spend.replace("/", "/$"),
|
|
36
|
+
"llmgateway-day": undefined,
|
|
37
|
+
"llmgateway-premium": undefined,
|
|
38
|
+
"llmgateway-month": undefined,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
"llmgateway-spend": undefined,
|
|
43
|
+
"llmgateway-day": meterText("day ", info.day),
|
|
44
|
+
"llmgateway-premium": meterText("prem ", info.premium),
|
|
45
|
+
"llmgateway-month": meterText("mo ", info.month),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function modelTexts(model: Pick<Model<Api>, "cost">): StatusTexts {
|
|
50
|
+
return { "llmgateway-premium-model": isPremium(model) ? "★" : undefined };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function clearedTexts(): StatusTexts {
|
|
54
|
+
return Object.fromEntries(STATUS_KEYS.map((key) => [key, undefined]));
|
|
55
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type ConfigStore, type Refusal, writeConfig } from "../routing/config-store.ts";
|
|
2
|
+
import { STATUS_KEYS } from "./footer-status.ts";
|
|
3
|
+
|
|
4
|
+
export function toggleFooterKey(store: ConfigStore, key: string, on: boolean): Promise<Refusal | undefined> {
|
|
5
|
+
if (on && !(STATUS_KEYS as readonly string[]).includes(key)) {
|
|
6
|
+
return Promise.resolve({ message: `Unknown footer status: ${key}`, level: "warning" });
|
|
7
|
+
}
|
|
8
|
+
return writeConfig(store, (raw) => {
|
|
9
|
+
const listed: unknown[] = Array.isArray(raw.footer) ? raw.footer : [];
|
|
10
|
+
if (!on) raw.footer = listed.filter((entry) => entry !== key);
|
|
11
|
+
else if (!listed.includes(key)) raw.footer = [...listed, key];
|
|
12
|
+
});
|
|
13
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { Plan } from "../routing/routing-config.ts";
|
|
2
|
+
|
|
3
|
+
export interface Meter {
|
|
4
|
+
used: number;
|
|
5
|
+
limit: number | undefined;
|
|
6
|
+
resetsAt: Date | undefined;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface KeyInfo {
|
|
10
|
+
label: string;
|
|
11
|
+
plan: Exclude<Plan, undefined>;
|
|
12
|
+
planName: string;
|
|
13
|
+
spend: Meter;
|
|
14
|
+
month: Meter;
|
|
15
|
+
day: Meter;
|
|
16
|
+
premium: Meter;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface KeyClientDeps {
|
|
20
|
+
fetchImpl: typeof fetch;
|
|
21
|
+
baseUrl: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const BACKGROUND_TIMEOUT_MS = 10_000;
|
|
25
|
+
|
|
26
|
+
type Json = Record<string, unknown>;
|
|
27
|
+
|
|
28
|
+
function isObject(value: unknown): value is Json {
|
|
29
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function amount(value: unknown): number | undefined {
|
|
33
|
+
if (typeof value !== "string" && typeof value !== "number") return undefined;
|
|
34
|
+
const parsed = Number(value);
|
|
35
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function date(value: unknown): Date | undefined {
|
|
39
|
+
if (typeof value !== "string") return undefined;
|
|
40
|
+
const parsed = new Date(value);
|
|
41
|
+
return Number.isNaN(parsed.getTime()) ? undefined : parsed;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function meter(used: unknown, limit: unknown, resetsAt?: unknown): Meter {
|
|
45
|
+
return { used: amount(used) ?? 0, limit: amount(limit), resetsAt: date(resetsAt) };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function parseKeyInfo(body: unknown): KeyInfo {
|
|
49
|
+
const data = isObject(body) && isObject(body.data) ? body.data : undefined;
|
|
50
|
+
if (!data || typeof data.devPlan !== "string") throw new Error("Invalid LLM Gateway key response");
|
|
51
|
+
return {
|
|
52
|
+
label: typeof data.label === "string" ? data.label : "",
|
|
53
|
+
plan: data.devPlan === "none" ? "payg" : "devpass",
|
|
54
|
+
planName: data.devPlan,
|
|
55
|
+
spend: meter(data.usage, data.limit),
|
|
56
|
+
month: meter(data.devPlanCreditsUsed, data.devPlanCreditsLimit),
|
|
57
|
+
day: meter(data.devPlanDailyCreditsUsed, data.devPlanDailyLimit, data.devPlanDayResetsAt),
|
|
58
|
+
premium: meter(data.devPlanPremiumCreditsUsed, data.devPlanPremiumWeeklyLimit, data.devPlanPremiumWeekResetsAt),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface KeyClient {
|
|
63
|
+
plan(): Plan;
|
|
64
|
+
last(): KeyInfo | undefined;
|
|
65
|
+
fetch(apiKey: string | undefined, signal?: AbortSignal): Promise<KeyInfo>;
|
|
66
|
+
fetchPlan(apiKey: string | undefined): Promise<KeyInfo>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function keyClient(deps: KeyClientDeps): KeyClient {
|
|
70
|
+
let cached: KeyInfo | undefined;
|
|
71
|
+
let started = 0;
|
|
72
|
+
let applied = 0;
|
|
73
|
+
let inflight: Promise<KeyInfo> | undefined;
|
|
74
|
+
const fetchKey = async (apiKey: string | undefined, signal?: AbortSignal): Promise<KeyInfo> => {
|
|
75
|
+
if (!apiKey) throw new Error("No LLM Gateway API key. Run /login or set LLMGATEWAY_API_KEY.");
|
|
76
|
+
const sequence = ++started;
|
|
77
|
+
const response = await deps.fetchImpl(`${deps.baseUrl.replace(/\/+$/, "")}/key`, {
|
|
78
|
+
headers: { accept: "application/json", authorization: `Bearer ${apiKey}`, "x-source": "pi" },
|
|
79
|
+
signal: signal ?? AbortSignal.timeout(BACKGROUND_TIMEOUT_MS),
|
|
80
|
+
});
|
|
81
|
+
if (!response.ok) throw new Error(`LLM Gateway key request failed: ${response.status}`);
|
|
82
|
+
const info = parseKeyInfo(await response.json());
|
|
83
|
+
if (sequence > applied) {
|
|
84
|
+
applied = sequence;
|
|
85
|
+
cached = info;
|
|
86
|
+
}
|
|
87
|
+
return info;
|
|
88
|
+
};
|
|
89
|
+
return {
|
|
90
|
+
plan: () => cached?.plan,
|
|
91
|
+
last: () => cached,
|
|
92
|
+
fetch: fetchKey,
|
|
93
|
+
fetchPlan: (apiKey) => {
|
|
94
|
+
if (inflight) return inflight;
|
|
95
|
+
const call = fetchKey(apiKey).finally(() => {
|
|
96
|
+
if (inflight === call) inflight = undefined;
|
|
97
|
+
});
|
|
98
|
+
inflight = call;
|
|
99
|
+
return call;
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { redactKeys } from "../catalog/fetch-catalog.ts";
|
|
3
|
+
import type { AccountStatus } from "./account-status.ts";
|
|
4
|
+
import { formatUsage } from "./usage-command.ts";
|
|
5
|
+
|
|
6
|
+
export interface RegisterAccountDeps {
|
|
7
|
+
status: AccountStatus;
|
|
8
|
+
now: () => number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function registerAccount(pi: ExtensionAPI, deps: RegisterAccountDeps): void {
|
|
12
|
+
const { status } = deps;
|
|
13
|
+
pi.on("session_start", (_event, ctx) => status.select(ctx, ctx.model));
|
|
14
|
+
pi.on("model_select", (event, ctx) => status.select(ctx, event.model));
|
|
15
|
+
pi.on("agent_end", (_event, ctx) => status.agentEnd(ctx));
|
|
16
|
+
pi.on("session_shutdown", () => status.detach());
|
|
17
|
+
|
|
18
|
+
pi.registerCommand("llmgateway-usage", {
|
|
19
|
+
description: "Show LLM Gateway plan usage and limits for the current key",
|
|
20
|
+
handler: async (_args, ctx) => {
|
|
21
|
+
try {
|
|
22
|
+
ctx.ui.notify(formatUsage(await status.refresh(ctx, ctx.signal), deps.now()), "info");
|
|
23
|
+
} catch (error) {
|
|
24
|
+
ctx.ui.notify(redactKeys((error as Error).message), "error");
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { KeyInfo, Meter } from "./key-info.ts";
|
|
2
|
+
|
|
3
|
+
function duration(ms: number): string {
|
|
4
|
+
const minutes = Math.max(0, Math.round(ms / 60_000));
|
|
5
|
+
const days = Math.floor(minutes / 1440);
|
|
6
|
+
const hours = Math.floor((minutes % 1440) / 60);
|
|
7
|
+
const rest = minutes % 60;
|
|
8
|
+
if (days > 0) return `${days}d ${hours}h`;
|
|
9
|
+
if (hours > 0) return `${hours}h ${rest}m`;
|
|
10
|
+
return `${rest}m`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function line(name: string, meter: Meter, now: number, windowed: boolean): string {
|
|
14
|
+
const amounts =
|
|
15
|
+
meter.limit === undefined ? `$${meter.used.toFixed(2)}` : `$${meter.used.toFixed(2)} of $${meter.limit.toFixed(2)}`;
|
|
16
|
+
if (!windowed) return `${name}: ${amounts}`;
|
|
17
|
+
const reset = meter.resetsAt ? `resets in ${duration(meter.resetsAt.getTime() - now)}` : "not started";
|
|
18
|
+
return `${name}: ${amounts}, ${reset}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function formatUsage(info: KeyInfo, now: number): string {
|
|
22
|
+
const title = info.label ? `LLM Gateway key "${info.label}"` : "LLM Gateway key";
|
|
23
|
+
if (info.plan === "payg") return [`${title}, pay-as-you-go`, line("Spend", info.spend, now, false)].join("\n");
|
|
24
|
+
return [
|
|
25
|
+
`${title}, DevPass ${info.planName}`,
|
|
26
|
+
line("Month", info.month, now, false),
|
|
27
|
+
line("Day", info.day, now, true),
|
|
28
|
+
line("Premium week", info.premium, now, true),
|
|
29
|
+
].join("\n");
|
|
30
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { Provider, RefreshModelsContext } from "@earendil-works/pi-ai";
|
|
3
|
+
import { parseGatewayModels } from "./gateway-models.ts";
|
|
4
|
+
import { BASE_URL, type GatewayChatModel, toPiModels } from "./model-mapping.ts";
|
|
5
|
+
|
|
6
|
+
export const API_KEY_ENV = "LLMGATEWAY_API_KEY";
|
|
7
|
+
export const CATALOG_FRESH_MS = 60 * 60 * 1000;
|
|
8
|
+
const CATALOG_TIMEOUT_MS = 15_000;
|
|
9
|
+
|
|
10
|
+
export interface CatalogDeps {
|
|
11
|
+
fetchImpl: typeof fetch;
|
|
12
|
+
env: (name: string) => string | undefined;
|
|
13
|
+
now: () => number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function redactKeys(text: string): string {
|
|
17
|
+
return text.replace(/llmgtwy_[A-Za-z0-9_-]+/g, "llmgtwy_***");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function keyHash(key: string | undefined): string {
|
|
21
|
+
return key ? createHash("sha256").update(key).digest("hex").slice(0, 16) : "";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function credentialKey(context: RefreshModelsContext, env: CatalogDeps["env"]): string | undefined {
|
|
25
|
+
const stored = context.credential?.type === "api_key" ? context.credential.key : undefined;
|
|
26
|
+
return stored || env(API_KEY_ENV) || undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function fetchCatalog(
|
|
30
|
+
context: RefreshModelsContext,
|
|
31
|
+
deps: CatalogDeps,
|
|
32
|
+
): Promise<(GatewayChatModel & { llmgatewayKeyHash: string })[]> {
|
|
33
|
+
const key = credentialKey(context, deps.env);
|
|
34
|
+
const headers: Record<string, string> = { accept: "application/json", "x-source": "pi" };
|
|
35
|
+
if (key) headers.authorization = `Bearer ${key}`;
|
|
36
|
+
const baseUrl = (context.baseUrl ?? BASE_URL).replace(/\/+$/, "");
|
|
37
|
+
const response = await deps.fetchImpl(`${baseUrl}/models`, {
|
|
38
|
+
headers,
|
|
39
|
+
signal: AbortSignal.any([context.signal, AbortSignal.timeout(CATALOG_TIMEOUT_MS)]),
|
|
40
|
+
});
|
|
41
|
+
if (!response.ok) {
|
|
42
|
+
throw new Error(`LLM Gateway model list request failed: ${response.status} ${response.statusText}`.trim());
|
|
43
|
+
}
|
|
44
|
+
const llmgatewayKeyHash = keyHash(key);
|
|
45
|
+
return toPiModels(parseGatewayModels(await response.json()), deps.now()).map((model) => ({
|
|
46
|
+
...model,
|
|
47
|
+
llmgatewayKeyHash,
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function withCatalogFreshness<TApi extends string>(
|
|
52
|
+
provider: Provider<TApi>,
|
|
53
|
+
now: () => number,
|
|
54
|
+
env: CatalogDeps["env"] = (name) => process.env[name],
|
|
55
|
+
): Provider<TApi> {
|
|
56
|
+
const refresh = provider.refreshModels;
|
|
57
|
+
if (!refresh) return provider;
|
|
58
|
+
return {
|
|
59
|
+
...provider,
|
|
60
|
+
refreshModels: (context) => {
|
|
61
|
+
const checkedAt = context.stored?.checkedAt;
|
|
62
|
+
const models = context.stored?.models ?? [];
|
|
63
|
+
const hash = keyHash(credentialKey(context, env));
|
|
64
|
+
const complete =
|
|
65
|
+
models.length > 0 &&
|
|
66
|
+
models.every(
|
|
67
|
+
(model) =>
|
|
68
|
+
"llmgatewayUpstreamId" in model &&
|
|
69
|
+
Array.isArray((model as { llmgatewayProviders?: unknown }).llmgatewayProviders) &&
|
|
70
|
+
(model as { llmgatewayKeyHash?: unknown }).llmgatewayKeyHash === hash,
|
|
71
|
+
);
|
|
72
|
+
const fresh = !context.force && complete && checkedAt !== undefined && now() - checkedAt < CATALOG_FRESH_MS;
|
|
73
|
+
return refresh.call(provider, fresh ? { ...context, allowNetwork: false } : context);
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
export interface GatewayProvider {
|
|
2
|
+
id: string;
|
|
3
|
+
streaming: boolean;
|
|
4
|
+
tools: boolean;
|
|
5
|
+
deactivatedAt: number | undefined;
|
|
6
|
+
reasoningEfforts: string[];
|
|
7
|
+
regions: string[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface GatewayRates {
|
|
11
|
+
prompt: number;
|
|
12
|
+
completion: number;
|
|
13
|
+
cacheRead: number;
|
|
14
|
+
cacheWrite: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface GatewayTier extends Partial<GatewayRates> {
|
|
18
|
+
upToTokens: number | undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface GatewayPricing extends GatewayRates {
|
|
22
|
+
tiers: GatewayTier[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface GatewayModel {
|
|
26
|
+
id: string;
|
|
27
|
+
name: string;
|
|
28
|
+
family: string;
|
|
29
|
+
contextLength: number;
|
|
30
|
+
maxOutput: number | undefined;
|
|
31
|
+
inputModalities: string[];
|
|
32
|
+
outputModalities: string[];
|
|
33
|
+
supportedParameters: string[];
|
|
34
|
+
deactivatedAt: number | undefined;
|
|
35
|
+
providers: GatewayProvider[];
|
|
36
|
+
pricing: GatewayPricing;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type Json = Record<string, unknown>;
|
|
40
|
+
|
|
41
|
+
function isObject(value: unknown): value is Json {
|
|
42
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function strings(value: unknown): string[] {
|
|
46
|
+
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function positive(value: unknown): number | undefined {
|
|
50
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function optionalPrice(value: unknown): number | undefined {
|
|
54
|
+
const parsed = typeof value === "string" || typeof value === "number" ? Number(value) : Number.NaN;
|
|
55
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function price(value: unknown): number {
|
|
59
|
+
return optionalPrice(value) ?? 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function timestamp(value: unknown): number | undefined {
|
|
63
|
+
if (typeof value !== "string") return undefined;
|
|
64
|
+
const parsed = Date.parse(value);
|
|
65
|
+
return Number.isNaN(parsed) ? undefined : parsed;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function regionIds(value: unknown): string[] {
|
|
69
|
+
if (!Array.isArray(value)) return [];
|
|
70
|
+
return value.flatMap((region) => (isObject(region) && typeof region.id === "string" && region.id !== "" ? [region.id] : []));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function parseProvider(value: unknown): GatewayProvider | undefined {
|
|
74
|
+
if (!isObject(value) || typeof value.providerId !== "string") return undefined;
|
|
75
|
+
return {
|
|
76
|
+
id: value.providerId,
|
|
77
|
+
streaming: value.streaming !== false,
|
|
78
|
+
tools: value.tools === true,
|
|
79
|
+
deactivatedAt: timestamp(value.deactivated_at),
|
|
80
|
+
reasoningEfforts: strings(value.reasoning_efforts),
|
|
81
|
+
regions: regionIds(value.regions),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function parseTier(value: unknown): GatewayTier | undefined {
|
|
86
|
+
if (!isObject(value)) return undefined;
|
|
87
|
+
return {
|
|
88
|
+
upToTokens: positive(value.up_to_tokens),
|
|
89
|
+
prompt: optionalPrice(value.prompt),
|
|
90
|
+
completion: optionalPrice(value.completion),
|
|
91
|
+
cacheRead: optionalPrice(value.input_cache_read),
|
|
92
|
+
cacheWrite: optionalPrice(value.input_cache_write),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function parsePricing(value: unknown): GatewayPricing {
|
|
97
|
+
const source = isObject(value) ? value : {};
|
|
98
|
+
const tiers = Array.isArray(source.tiers) ? source.tiers : [];
|
|
99
|
+
return {
|
|
100
|
+
prompt: price(source.prompt),
|
|
101
|
+
completion: price(source.completion),
|
|
102
|
+
cacheRead: price(source.input_cache_read),
|
|
103
|
+
cacheWrite: price(source.input_cache_write),
|
|
104
|
+
tiers: tiers.flatMap((tier) => parseTier(tier) ?? []),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function parseGatewayModel(value: unknown): GatewayModel | undefined {
|
|
109
|
+
if (!isObject(value) || typeof value.id !== "string" || value.id === "") return undefined;
|
|
110
|
+
const architecture = isObject(value.architecture) ? value.architecture : {};
|
|
111
|
+
const providers = Array.isArray(value.providers) ? value.providers : [];
|
|
112
|
+
return {
|
|
113
|
+
id: value.id,
|
|
114
|
+
name: typeof value.name === "string" && value.name !== "" ? value.name : value.id,
|
|
115
|
+
family: typeof value.family === "string" && value.family !== "" ? value.family : "unknown",
|
|
116
|
+
contextLength: positive(value.context_length) ?? 0,
|
|
117
|
+
maxOutput: positive(value.max_output),
|
|
118
|
+
inputModalities: strings(architecture.input_modalities),
|
|
119
|
+
outputModalities: strings(architecture.output_modalities),
|
|
120
|
+
supportedParameters: strings(value.supported_parameters),
|
|
121
|
+
deactivatedAt: timestamp(value.deactivated_at),
|
|
122
|
+
providers: providers.flatMap((provider) => parseProvider(provider) ?? []),
|
|
123
|
+
pricing: parsePricing(value.pricing),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function parseGatewayModels(body: unknown): GatewayModel[] {
|
|
128
|
+
if (!isObject(body) || !Array.isArray(body.data)) throw new Error("Invalid LLM Gateway model list response");
|
|
129
|
+
return body.data.flatMap((entry) => parseGatewayModel(entry) ?? []);
|
|
130
|
+
}
|