@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
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { redactKeys } from "../catalog/fetch-catalog.ts";
|
|
2
|
+
import type { Plan } from "../routing/routing-config.ts";
|
|
3
|
+
import { footerCount, footerRows } from "./footer-rows.ts";
|
|
4
|
+
import { currentConfig, type MenuDeps, type Row, row, type Widgets } from "./menu-types.ts";
|
|
5
|
+
import { modelRows, pickerItems, storedModelCount } from "./model-rows.ts";
|
|
6
|
+
import { routingRow } from "./routing-rows.ts";
|
|
7
|
+
|
|
8
|
+
export function planLabel(plan: Plan, name: string | undefined): string {
|
|
9
|
+
if (plan === "payg") return "pay-as-you-go";
|
|
10
|
+
if (plan === "devpass") return name ? `DevPass ${name}` : "DevPass";
|
|
11
|
+
return "unknown";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function modelSettingsRow(deps: MenuDeps, widgets: Widgets): Row {
|
|
15
|
+
return row({
|
|
16
|
+
id: "models",
|
|
17
|
+
label: "Model settings",
|
|
18
|
+
description: "Routing and pin settings per model. A ● marks a model with stored settings.",
|
|
19
|
+
currentValue: storedModelCount(deps),
|
|
20
|
+
submenu: (_current, done) => {
|
|
21
|
+
const host = widgets.host();
|
|
22
|
+
const finish = () => done(storedModelCount(deps));
|
|
23
|
+
const showPicker = (): void =>
|
|
24
|
+
host.show(
|
|
25
|
+
widgets.picker(pickerItems(deps), (id) => showModel(id), finish, "Model settings"),
|
|
26
|
+
);
|
|
27
|
+
const showModel = (id: string): void =>
|
|
28
|
+
host.show(widgets.settings(() => modelRows(deps, widgets, id), showPicker, { title: id }));
|
|
29
|
+
showPicker();
|
|
30
|
+
return host;
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function footerStatusesRow(deps: MenuDeps, widgets: Widgets): Row {
|
|
36
|
+
return row({
|
|
37
|
+
id: "footer",
|
|
38
|
+
label: "Footer statuses",
|
|
39
|
+
description: "Status texts the extension puts in pi's footer. All are off by default.",
|
|
40
|
+
currentValue: footerCount(deps),
|
|
41
|
+
submenu: (_current, done) =>
|
|
42
|
+
widgets.settings(() => footerRows(deps), () => done(footerCount(deps)), { title: "Footer statuses" }),
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function planRow(deps: MenuDeps): Row {
|
|
47
|
+
const label = planLabel(deps.plan(), deps.planName());
|
|
48
|
+
return row({
|
|
49
|
+
id: "plan",
|
|
50
|
+
label: "Plan",
|
|
51
|
+
description: "Enter fetches the plan again from /v1/key and rebuilds every row.",
|
|
52
|
+
currentValue: label,
|
|
53
|
+
values: [label],
|
|
54
|
+
write: async () => {
|
|
55
|
+
try {
|
|
56
|
+
await deps.refreshPlan();
|
|
57
|
+
return undefined;
|
|
58
|
+
} catch (error) {
|
|
59
|
+
return { message: redactKeys((error as Error).message), level: "error" };
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function topRows(deps: MenuDeps, widgets: Widgets): Row[] {
|
|
66
|
+
const { default: defaults } = currentConfig(deps);
|
|
67
|
+
return [
|
|
68
|
+
routingRow(deps, "sort", "default", defaults, {}),
|
|
69
|
+
routingRow(deps, "tier", "default", defaults, {}),
|
|
70
|
+
routingRow(deps, "fallback", "default", defaults, {}),
|
|
71
|
+
modelSettingsRow(deps, widgets),
|
|
72
|
+
footerStatusesRow(deps, widgets),
|
|
73
|
+
planRow(deps),
|
|
74
|
+
];
|
|
75
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { PinnableProvider } from "../catalog/model-mapping.ts";
|
|
2
|
+
import type { ConfigStore } from "../routing/config-store.ts";
|
|
3
|
+
import type { Plan } from "../routing/routing-config.ts";
|
|
4
|
+
import { type CompletionItem, complete } from "../routing/routing-command.ts";
|
|
5
|
+
import type { CommandResult } from "../routing/routing-writes.ts";
|
|
6
|
+
import { type PinModel, pinOptions, pinStatus } from "./pin-target.ts";
|
|
7
|
+
import { removePin, setPin } from "./pin-writes.ts";
|
|
8
|
+
|
|
9
|
+
export interface PinCommandDeps {
|
|
10
|
+
store: ConfigStore;
|
|
11
|
+
plan: () => Plan;
|
|
12
|
+
models: () => PinModel[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const USAGE = "Usage: /llmgateway-pin [<model> [<provider[:region]>|off]]";
|
|
16
|
+
|
|
17
|
+
const IGNORED = {
|
|
18
|
+
devpass: " (ignored on DevPass)",
|
|
19
|
+
"plan unknown": " (ignored: plan unknown)",
|
|
20
|
+
"not served": " (ignored: not served)",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function pinCompletions(argumentPrefix: string, models: PinModel[]): CompletionItem[] | null {
|
|
24
|
+
const tokens = argumentPrefix.trimStart().split(/\s+/);
|
|
25
|
+
const [id = "", pin = ""] = tokens;
|
|
26
|
+
let items: CompletionItem[] = [];
|
|
27
|
+
if (tokens.length <= 1)
|
|
28
|
+
items = complete(id, models.map((model) => model.id), (option) => `${option} `);
|
|
29
|
+
else if (tokens.length === 2) {
|
|
30
|
+
const options = [...pinOptions(models.find((model) => model.id === id)?.providers ?? []), "off"];
|
|
31
|
+
items = complete(pin, options, (option) => `${id} ${option}`);
|
|
32
|
+
}
|
|
33
|
+
return items.length > 0 ? items : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function describePin(providers: PinnableProvider[], pin: string, plan: Plan): string {
|
|
37
|
+
const status = pinStatus(providers, pin, plan);
|
|
38
|
+
return status === "sent" ? pin : `${pin}${IGNORED[status]}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function planLabel(plan: Plan): string {
|
|
42
|
+
if (plan === "payg") return "pay-as-you-go";
|
|
43
|
+
return plan === "devpass" ? "DevPass" : "unknown plan";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function showAll(pins: Record<string, string>, deps: PinCommandDeps): CommandResult {
|
|
47
|
+
const plan = deps.plan();
|
|
48
|
+
const models = deps.models();
|
|
49
|
+
const lines = [`LLM Gateway pins (${planLabel(plan)})`];
|
|
50
|
+
for (const [id, pin] of Object.entries(pins)) {
|
|
51
|
+
const providers = models.find((model) => model.id === id)?.providers ?? [];
|
|
52
|
+
lines.push(`${id}: ${describePin(providers, pin, plan)}`);
|
|
53
|
+
}
|
|
54
|
+
if (lines.length === 1) lines.push("no pins");
|
|
55
|
+
return { message: lines.join("\n"), level: "info" };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function showOne(model: PinModel, pin: string | undefined, plan: Plan): CommandResult {
|
|
59
|
+
const options = pinOptions(model.providers);
|
|
60
|
+
const lines = [
|
|
61
|
+
`${model.id}: ${pin === undefined ? "no pin" : describePin(model.providers, pin, plan)}`,
|
|
62
|
+
`pinnable: ${options.length > 0 ? options.join(", ") : "none"}`,
|
|
63
|
+
];
|
|
64
|
+
return { message: lines.join("\n"), level: "info" };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function runPinCommand(argText: string, deps: PinCommandDeps): Promise<CommandResult> {
|
|
68
|
+
const args = argText.trim().split(/\s+/).filter(Boolean);
|
|
69
|
+
const read = deps.store.read();
|
|
70
|
+
if (!read.ok) return { message: read.error, level: "error" };
|
|
71
|
+
if (args.length === 0) return showAll(read.config.pins, deps);
|
|
72
|
+
const [id = "", pin] = args;
|
|
73
|
+
if (args.length > 2) return { message: USAGE, level: "warning" };
|
|
74
|
+
const model = deps.models().find((entry) => entry.id === id);
|
|
75
|
+
const stored = read.config.pins[id];
|
|
76
|
+
if (pin === "off" && stored !== undefined) {
|
|
77
|
+
return (await removePin(deps.store, id)) ?? { message: `${id}: pin removed`, level: "info" };
|
|
78
|
+
}
|
|
79
|
+
if (!model) return { message: `Unknown LLM Gateway model: ${id}`, level: "warning" };
|
|
80
|
+
if (pin === undefined) return showOne(model, stored, deps.plan());
|
|
81
|
+
if (pin === "off") return { message: `${id}: no pin`, level: "info" };
|
|
82
|
+
return (await setPin(deps.store, deps.plan(), model, pin)) ?? { message: `${id}: pinned to ${pin}`, level: "info" };
|
|
83
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { PinnableProvider } from "../catalog/model-mapping.ts";
|
|
2
|
+
import type { Plan } from "../routing/routing-config.ts";
|
|
3
|
+
|
|
4
|
+
export type PinStatus = "sent" | "devpass" | "plan unknown" | "not served";
|
|
5
|
+
|
|
6
|
+
export interface PinModel {
|
|
7
|
+
id: string;
|
|
8
|
+
providers: PinnableProvider[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function pinOptions(providers: PinnableProvider[]): string[] {
|
|
12
|
+
return [
|
|
13
|
+
...providers.map((provider) => provider.id),
|
|
14
|
+
...providers.flatMap((provider) => provider.regions.map((region) => `${provider.id}:${region}`)),
|
|
15
|
+
];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface PinTarget {
|
|
19
|
+
provider: string;
|
|
20
|
+
region: string | undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function parsePin(pin: string): PinTarget {
|
|
24
|
+
const split = pin.indexOf(":");
|
|
25
|
+
if (split < 0) return { provider: pin, region: undefined };
|
|
26
|
+
return { provider: pin.slice(0, split), region: pin.slice(split + 1) };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function providersOf(model: object): PinnableProvider[] {
|
|
30
|
+
const stored = (model as { llmgatewayProviders?: unknown }).llmgatewayProviders;
|
|
31
|
+
return Array.isArray(stored) ? (stored as PinnableProvider[]) : [];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function pinModels(models: readonly object[]): PinModel[] {
|
|
35
|
+
return models.map((model) => ({ id: (model as { id: string }).id, providers: providersOf(model) }));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function isServed(providers: PinnableProvider[], pin: string): boolean {
|
|
39
|
+
const target = parsePin(pin);
|
|
40
|
+
const provider = providers.find((entry) => entry.id === target.provider);
|
|
41
|
+
if (!provider) return false;
|
|
42
|
+
return target.region === undefined || provider.regions.includes(target.region);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function pinStatus(providers: PinnableProvider[], pin: string, plan: Plan): PinStatus {
|
|
46
|
+
if (plan === undefined) return "plan unknown";
|
|
47
|
+
if (plan === "devpass") return "devpass";
|
|
48
|
+
return isServed(providers, pin) ? "sent" : "not served";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function pinnedModelId(
|
|
52
|
+
upstream: string,
|
|
53
|
+
providers: PinnableProvider[],
|
|
54
|
+
pin: string | undefined,
|
|
55
|
+
plan: Plan,
|
|
56
|
+
): string {
|
|
57
|
+
if (pin === undefined || pinStatus(providers, pin, plan) !== "sent") return upstream;
|
|
58
|
+
const target = parsePin(pin);
|
|
59
|
+
const id = `${target.provider}/${upstream}`;
|
|
60
|
+
return target.region === undefined ? id : `${id}:${target.region}`;
|
|
61
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type ConfigStore, type Refusal, writeConfig } from "../routing/config-store.ts";
|
|
2
|
+
import { isObject, type Json, type Plan } from "../routing/routing-config.ts";
|
|
3
|
+
import { isServed, type PinModel, pinOptions } from "./pin-target.ts";
|
|
4
|
+
|
|
5
|
+
export function pinRefusal(model: PinModel, pin: string, plan: Plan): Refusal | undefined {
|
|
6
|
+
if (plan === undefined) return { message: "Cannot set a pin: the plan fetch failed. Try again.", level: "warning" };
|
|
7
|
+
if (plan === "devpass") {
|
|
8
|
+
return {
|
|
9
|
+
message: "Cannot set a pin: provider pins need a pay-as-you-go key, and this key is on DevPass.",
|
|
10
|
+
level: "warning",
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
if (isServed(model.providers, pin)) return undefined;
|
|
14
|
+
const pinnable = pinOptions(model.providers).join(", ") || "none";
|
|
15
|
+
return { message: `${model.id} has no provider or region "${pin}". Pinnable: ${pinnable}`, level: "warning" };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function pinsOf(raw: Json): Json {
|
|
19
|
+
if (!isObject(raw.pins)) raw.pins = {};
|
|
20
|
+
return raw.pins as Json;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function setPin(store: ConfigStore, plan: Plan, model: PinModel, pin: string): Promise<Refusal | undefined> {
|
|
24
|
+
const refused = pinRefusal(model, pin, plan);
|
|
25
|
+
if (refused) return refused;
|
|
26
|
+
return writeConfig(store, (raw) => {
|
|
27
|
+
pinsOf(raw)[model.id] = pin;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function removePin(store: ConfigStore, id: string): Promise<Refusal | undefined> {
|
|
32
|
+
return writeConfig(store, (raw) => {
|
|
33
|
+
delete pinsOf(raw)[id];
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ConfigStore } from "../routing/config-store.ts";
|
|
3
|
+
import { gatewayModels, trackCompletionTargets } from "../routing/completion-targets.ts";
|
|
4
|
+
import type { Plan } from "../routing/routing-config.ts";
|
|
5
|
+
import { pinCompletions, runPinCommand } from "./pin-command.ts";
|
|
6
|
+
import { pinModels } from "./pin-target.ts";
|
|
7
|
+
|
|
8
|
+
export interface RegisterPinDeps {
|
|
9
|
+
store: ConfigStore;
|
|
10
|
+
plan: () => Plan;
|
|
11
|
+
refresh: (ctx: ExtensionContext, signal?: AbortSignal) => Promise<unknown>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function registerPin(pi: ExtensionAPI, deps: RegisterPinDeps): void {
|
|
15
|
+
const completionTargets = trackCompletionTargets(pi);
|
|
16
|
+
pi.registerCommand("llmgateway-pin", {
|
|
17
|
+
description: "Show or set LLM Gateway provider pins: [<model> [<provider[:region]>|off]]",
|
|
18
|
+
getArgumentCompletions: (prefix) => pinCompletions(prefix, pinModels(completionTargets())),
|
|
19
|
+
handler: async (args, ctx) => {
|
|
20
|
+
if (!deps.plan()) await deps.refresh(ctx, ctx.signal).catch(() => undefined);
|
|
21
|
+
const result = await runPinCommand(args, {
|
|
22
|
+
store: deps.store,
|
|
23
|
+
plan: deps.plan,
|
|
24
|
+
models: () => pinModels(gatewayModels(ctx)),
|
|
25
|
+
});
|
|
26
|
+
ctx.ui.notify(result.message, result.level);
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createProvider, envApiKeyAuth, openAICompletionsApi } from "@earendil-works/pi-ai/compat";
|
|
2
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { KeyClient } from "../account/key-info.ts";
|
|
4
|
+
import { API_KEY_ENV, fetchCatalog, withCatalogFreshness } from "../catalog/fetch-catalog.ts";
|
|
5
|
+
import { BASE_URL, PROVIDER_ID } from "../catalog/model-mapping.ts";
|
|
6
|
+
import { type ConfigStore, storedPin, storedRequestShape } from "../routing/config-store.ts";
|
|
7
|
+
import type { ServedResponse } from "./served-response.ts";
|
|
8
|
+
import { gatewayStreams } from "./stream-wrapper.ts";
|
|
9
|
+
|
|
10
|
+
export interface RegisterProviderDeps {
|
|
11
|
+
store: ConfigStore;
|
|
12
|
+
client: KeyClient;
|
|
13
|
+
onServed: (served: ServedResponse) => void;
|
|
14
|
+
fetchImpl: typeof fetch;
|
|
15
|
+
env: (name: string) => string | undefined;
|
|
16
|
+
now: () => number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function registerProvider(pi: ExtensionAPI, deps: RegisterProviderDeps): void {
|
|
20
|
+
const { client } = deps;
|
|
21
|
+
const provider = createProvider({
|
|
22
|
+
id: PROVIDER_ID,
|
|
23
|
+
name: "LLM Gateway",
|
|
24
|
+
baseUrl: BASE_URL,
|
|
25
|
+
headers: { "x-source": "pi" },
|
|
26
|
+
auth: { apiKey: envApiKeyAuth("LLM Gateway API key", [API_KEY_ENV]) },
|
|
27
|
+
models: [],
|
|
28
|
+
fetchModels: (context) => fetchCatalog(context, { fetchImpl: deps.fetchImpl, env: deps.env, now: deps.now }),
|
|
29
|
+
api: gatewayStreams(openAICompletionsApi(), {
|
|
30
|
+
shape: (model, plan) => storedRequestShape(deps.store, model.id, plan ?? client.plan()),
|
|
31
|
+
awaitPlan: async (key) => client.plan() ?? (await client.fetchPlan(key)).plan,
|
|
32
|
+
pin: (model) => storedPin(deps.store, model.id),
|
|
33
|
+
onServed: (_model, served) => deps.onServed(served),
|
|
34
|
+
}),
|
|
35
|
+
});
|
|
36
|
+
pi.registerProvider(withCatalogFreshness(provider, deps.now, deps.env));
|
|
37
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface ServedResponse {
|
|
2
|
+
cost: number | undefined;
|
|
3
|
+
provider: string | undefined;
|
|
4
|
+
region: string | undefined;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
type Json = Record<string, unknown>;
|
|
8
|
+
|
|
9
|
+
function isObject(value: unknown): value is Json {
|
|
10
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function nonEmpty(value: unknown): string | undefined {
|
|
14
|
+
return typeof value === "string" && value !== "" ? value : undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function emptyServedResponse(): ServedResponse {
|
|
18
|
+
return { cost: undefined, provider: undefined, region: undefined };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function recordChunk(served: ServedResponse, chunk: unknown): void {
|
|
22
|
+
if (!isObject(chunk)) return;
|
|
23
|
+
if (isObject(chunk.usage)) {
|
|
24
|
+
const cost = chunk.usage.cost;
|
|
25
|
+
if (typeof cost === "number" && Number.isFinite(cost) && cost >= 0) served.cost = cost;
|
|
26
|
+
}
|
|
27
|
+
if (isObject(chunk.metadata)) {
|
|
28
|
+
served.provider = nonEmpty(chunk.metadata.used_provider) ?? served.provider;
|
|
29
|
+
served.region = nonEmpty(chunk.metadata.used_region) ?? served.region;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Api,
|
|
3
|
+
type AssistantMessage,
|
|
4
|
+
type AssistantMessageEvent,
|
|
5
|
+
type AssistantMessageEventStream,
|
|
6
|
+
createAssistantMessageEventStream,
|
|
7
|
+
type Model,
|
|
8
|
+
type ProviderStreams,
|
|
9
|
+
type StreamOptions,
|
|
10
|
+
} from "@earendil-works/pi-ai";
|
|
11
|
+
import { pinnedModelId, providersOf } from "../pin/pin-target.ts";
|
|
12
|
+
import type { Plan } from "../routing/routing-config.ts";
|
|
13
|
+
import { emptyServedResponse, recordChunk, type ServedResponse } from "./served-response.ts";
|
|
14
|
+
|
|
15
|
+
export interface RequestShape {
|
|
16
|
+
body: Record<string, unknown>;
|
|
17
|
+
headers: Record<string, string>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface WrapperHooks {
|
|
21
|
+
shape: (model: Model<Api>, plan?: Plan) => RequestShape;
|
|
22
|
+
awaitPlan?: (apiKey: string | undefined) => Promise<Plan>;
|
|
23
|
+
pin?: (model: Model<Api>) => string | undefined;
|
|
24
|
+
onServed: (model: Model<Api>, served: ServedResponse) => void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function upstreamId(model: Model<Api>): string {
|
|
28
|
+
const stored = (model as { llmgatewayUpstreamId?: unknown }).llmgatewayUpstreamId;
|
|
29
|
+
if (typeof stored !== "string" || stored === "") throw new Error(`LLM Gateway model ${model.id} has no upstream id`);
|
|
30
|
+
return stored;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function resolvePlan(
|
|
34
|
+
awaitPlan: (apiKey: string | undefined) => Promise<Plan>,
|
|
35
|
+
apiKey: string | undefined,
|
|
36
|
+
signal: AbortSignal | undefined,
|
|
37
|
+
): Promise<Plan> {
|
|
38
|
+
const aborted = new Promise<undefined>((resolve) => signal?.addEventListener("abort", () => resolve(undefined), { once: true }));
|
|
39
|
+
try {
|
|
40
|
+
return await Promise.race([awaitPlan(apiKey), aborted]);
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function shapedOptions<T extends StreamOptions>(
|
|
47
|
+
model: Model<Api>,
|
|
48
|
+
options: T | undefined,
|
|
49
|
+
served: ServedResponse,
|
|
50
|
+
hooks: WrapperHooks,
|
|
51
|
+
): T {
|
|
52
|
+
const shape = hooks.shape(model);
|
|
53
|
+
const upstream = upstreamId(model);
|
|
54
|
+
return {
|
|
55
|
+
...options,
|
|
56
|
+
headers: { ...options?.headers, ...shape.headers },
|
|
57
|
+
onPayload: async (payload: unknown, payloadModel: Model<Api>) => {
|
|
58
|
+
const plan = hooks.awaitPlan ? await resolvePlan(hooks.awaitPlan, options?.apiKey, options?.signal) : undefined;
|
|
59
|
+
const body = hooks.awaitPlan ? hooks.shape(model, plan).body : shape.body;
|
|
60
|
+
const sent = pinnedModelId(upstream, providersOf(model), hooks.pin?.(model), plan);
|
|
61
|
+
const { routing: _routing, ...pinnedBody } = body as Record<string, unknown>;
|
|
62
|
+
const params = { ...(payload as object), ...(sent === upstream ? body : pinnedBody), model: sent };
|
|
63
|
+
return (await options?.onPayload?.(params, payloadModel)) ?? params;
|
|
64
|
+
},
|
|
65
|
+
onProviderStreamEvent: async (data: unknown, eventModel: Model<Api>) => {
|
|
66
|
+
recordChunk(served, data);
|
|
67
|
+
await options?.onProviderStreamEvent?.(data, eventModel);
|
|
68
|
+
},
|
|
69
|
+
} as T;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function applyBilledCost(message: AssistantMessage, served: ServedResponse): void {
|
|
73
|
+
if (served.cost === undefined) return;
|
|
74
|
+
message.usage.cost.total = served.cost;
|
|
75
|
+
message.usage.cost.totalFromProvider = true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function emptyMessage(model: Model<Api>): AssistantMessage {
|
|
79
|
+
return {
|
|
80
|
+
role: "assistant",
|
|
81
|
+
content: [],
|
|
82
|
+
api: model.api,
|
|
83
|
+
provider: model.provider,
|
|
84
|
+
model: model.id,
|
|
85
|
+
usage: {
|
|
86
|
+
input: 0,
|
|
87
|
+
output: 0,
|
|
88
|
+
cacheRead: 0,
|
|
89
|
+
cacheWrite: 0,
|
|
90
|
+
totalTokens: 0,
|
|
91
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
92
|
+
},
|
|
93
|
+
stopReason: "error",
|
|
94
|
+
timestamp: Date.now(),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function failure(model: Model<Api>, partial: AssistantMessage | undefined, reason: string): AssistantMessageEvent {
|
|
99
|
+
const error = { ...(partial ?? emptyMessage(model)), stopReason: "error" as const, errorMessage: reason };
|
|
100
|
+
return { type: "error", reason: "error", error };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function settle(event: AssistantMessageEvent, model: Model<Api>, served: ServedResponse, hooks: WrapperHooks): void {
|
|
104
|
+
if (event.type !== "done" && event.type !== "error") return;
|
|
105
|
+
if (event.type === "done") applyBilledCost(event.message, served);
|
|
106
|
+
try {
|
|
107
|
+
hooks.onServed(model, served);
|
|
108
|
+
} catch {}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function relay(
|
|
112
|
+
start: () => AssistantMessageEventStream,
|
|
113
|
+
model: Model<Api>,
|
|
114
|
+
served: ServedResponse,
|
|
115
|
+
hooks: WrapperHooks,
|
|
116
|
+
): AssistantMessageEventStream {
|
|
117
|
+
const outer = createAssistantMessageEventStream();
|
|
118
|
+
void (async () => {
|
|
119
|
+
let partial: AssistantMessage | undefined;
|
|
120
|
+
try {
|
|
121
|
+
for await (const event of start()) {
|
|
122
|
+
if ("partial" in event) partial = event.partial;
|
|
123
|
+
settle(event, model, served, hooks);
|
|
124
|
+
outer.push(event);
|
|
125
|
+
if (event.type === "done" || event.type === "error") return;
|
|
126
|
+
}
|
|
127
|
+
outer.push(failure(model, partial, "LLM Gateway stream ended without a result"));
|
|
128
|
+
} catch (error) {
|
|
129
|
+
outer.push(failure(model, partial, (error as Error).message));
|
|
130
|
+
}
|
|
131
|
+
})();
|
|
132
|
+
return outer;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function gatewayStreams(inner: ProviderStreams, hooks: WrapperHooks): ProviderStreams {
|
|
136
|
+
const streams: ProviderStreams = {
|
|
137
|
+
stream: (model, context, options) => {
|
|
138
|
+
const served = emptyServedResponse();
|
|
139
|
+
return relay(
|
|
140
|
+
() => inner.stream(model, context, shapedOptions(model, options, served, hooks)),
|
|
141
|
+
model,
|
|
142
|
+
served,
|
|
143
|
+
hooks,
|
|
144
|
+
);
|
|
145
|
+
},
|
|
146
|
+
streamSimple: (model, context, options) => {
|
|
147
|
+
const served = emptyServedResponse();
|
|
148
|
+
return relay(
|
|
149
|
+
() => inner.streamSimple(model, context, shapedOptions(model, options, served, hooks)),
|
|
150
|
+
model,
|
|
151
|
+
served,
|
|
152
|
+
hooks,
|
|
153
|
+
);
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
if (inner.fetchDeferred) streams.fetchDeferred = inner.fetchDeferred.bind(inner);
|
|
157
|
+
if (inner.cancelDeferred) streams.cancelDeferred = inner.cancelDeferred.bind(inner);
|
|
158
|
+
return streams;
|
|
159
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { PROVIDER_ID } from "../catalog/model-mapping.ts";
|
|
4
|
+
|
|
5
|
+
export type TargetModel = Model<Api>;
|
|
6
|
+
|
|
7
|
+
export function gatewayModels(ctx: ExtensionContext): readonly TargetModel[] {
|
|
8
|
+
return ctx.modelRegistry.getModelsOfType("chat", PROVIDER_ID);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function trackCompletionTargets(pi: ExtensionAPI): () => readonly TargetModel[] {
|
|
12
|
+
let targets: readonly TargetModel[] = [];
|
|
13
|
+
const remember = (_event: unknown, ctx: ExtensionContext): void => {
|
|
14
|
+
const scoped = ctx.scopedModels.filter((entry) => entry.model.provider === PROVIDER_ID);
|
|
15
|
+
targets = scoped.length > 0 ? scoped.map((entry) => entry.model) : gatewayModels(ctx);
|
|
16
|
+
};
|
|
17
|
+
pi.on("session_start", remember);
|
|
18
|
+
pi.on("model_select", remember);
|
|
19
|
+
return () => targets;
|
|
20
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { type ConfigRead, type Json, type Plan, parseConfig, requestShape } from "./routing-config.ts";
|
|
6
|
+
|
|
7
|
+
export interface ConfigStore {
|
|
8
|
+
read(): ConfigRead;
|
|
9
|
+
update(mutate: (raw: Json) => void): Promise<string | undefined>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface Refusal {
|
|
13
|
+
message: string;
|
|
14
|
+
level: "warning" | "error";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function writeConfig(store: ConfigStore, mutate: (raw: Json) => void): Promise<Refusal | undefined> {
|
|
18
|
+
const error = await store.update(mutate);
|
|
19
|
+
return error ? { message: error, level: "error" } : undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function isMissing(error: unknown): boolean {
|
|
23
|
+
return (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function readText(path: string): string | undefined {
|
|
27
|
+
try {
|
|
28
|
+
return readFileSync(path, "utf8");
|
|
29
|
+
} catch (error) {
|
|
30
|
+
if (isMissing(error)) return undefined;
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function readTextAsync(path: string): Promise<string | undefined> {
|
|
36
|
+
try {
|
|
37
|
+
return await readFile(path, "utf8");
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (isMissing(error)) return undefined;
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function storedRequestShape(store: ConfigStore, modelId: string, plan: Plan) {
|
|
45
|
+
const read = store.read();
|
|
46
|
+
return read.ok ? requestShape(read.config, modelId, plan) : { body: {}, headers: {} };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function storedPin(store: ConfigStore, modelId: string): string | undefined {
|
|
50
|
+
const read = store.read();
|
|
51
|
+
return read.ok ? read.config.pins[modelId] : undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function storedFooter(store: ConfigStore): string[] {
|
|
55
|
+
const read = store.read();
|
|
56
|
+
return read.ok ? read.config.footer : [];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function fileConfigStore(path: string): ConfigStore {
|
|
60
|
+
return {
|
|
61
|
+
read: () => {
|
|
62
|
+
try {
|
|
63
|
+
return parseConfig(readText(path));
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return { ok: false, error: `Cannot read ${path}: ${(error as Error).message}` };
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
update: (mutate) =>
|
|
69
|
+
withFileMutationQueue(path, async () => {
|
|
70
|
+
try {
|
|
71
|
+
const current = parseConfig(await readTextAsync(path));
|
|
72
|
+
if (!current.ok) return current.error;
|
|
73
|
+
mutate(current.raw);
|
|
74
|
+
await mkdir(dirname(path), { recursive: true });
|
|
75
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
76
|
+
await writeFile(temporary, `${JSON.stringify(current.raw, null, 2)}\n`, "utf8");
|
|
77
|
+
await rename(temporary, path);
|
|
78
|
+
return undefined;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
return `Cannot update ${path}: ${(error as Error).message}`;
|
|
81
|
+
}
|
|
82
|
+
}),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ConfigStore } from "./config-store.ts";
|
|
3
|
+
import { gatewayModels, trackCompletionTargets } from "./completion-targets.ts";
|
|
4
|
+
import { routingCompletions, runRoutingCommand } from "./routing-command.ts";
|
|
5
|
+
import type { Plan } from "./routing-config.ts";
|
|
6
|
+
|
|
7
|
+
export interface RegisterRoutingDeps {
|
|
8
|
+
store: ConfigStore;
|
|
9
|
+
plan: () => Plan;
|
|
10
|
+
refresh: (ctx: ExtensionContext, signal?: AbortSignal) => Promise<unknown>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function registerRouting(pi: ExtensionAPI, deps: RegisterRoutingDeps): void {
|
|
14
|
+
const completionTargets = trackCompletionTargets(pi);
|
|
15
|
+
|
|
16
|
+
pi.registerCommand("llmgateway-routing", {
|
|
17
|
+
description: "Show or set LLM Gateway routing: <default|model> <sort|tier|fallback|reset> [value]",
|
|
18
|
+
getArgumentCompletions: (prefix) => routingCompletions(prefix, completionTargets().map((model) => model.id), deps.plan()),
|
|
19
|
+
handler: async (args, ctx) => {
|
|
20
|
+
if (!deps.plan()) await deps.refresh(ctx, ctx.signal).catch(() => undefined);
|
|
21
|
+
const known = gatewayModels(ctx).map((model) => model.id);
|
|
22
|
+
const result = await runRoutingCommand(args, {
|
|
23
|
+
store: deps.store,
|
|
24
|
+
plan: deps.plan,
|
|
25
|
+
knownModel: (id) => known.includes(id),
|
|
26
|
+
});
|
|
27
|
+
ctx.ui.notify(result.message, result.level);
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
}
|