@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.
@@ -0,0 +1,133 @@
1
+ import type {
2
+ Model,
3
+ ModelCost,
4
+ ModelCostTier,
5
+ ModelThinkingLevel,
6
+ OpenAICompletionsCompat,
7
+ ThinkingLevelMap,
8
+ } from "@earendil-works/pi-ai";
9
+ import type { GatewayModel, GatewayPricing, GatewayProvider, GatewayRates } from "./gateway-models.ts";
10
+
11
+ export const PROVIDER_ID = "llmgateway";
12
+ export const BASE_URL = "https://api.llmgateway.io/v1";
13
+
14
+ export interface PinnableProvider {
15
+ id: string;
16
+ regions: string[];
17
+ }
18
+
19
+ export type GatewayChatModel = Model<"openai-completions"> & {
20
+ llmgatewayUpstreamId: string;
21
+ llmgatewayProviders: PinnableProvider[];
22
+ };
23
+
24
+ const authorLabels: Record<string, string> = {
25
+ alibaba: "Alibaba",
26
+ anthropic: "Anthropic",
27
+ baai: "BAAI",
28
+ bytedance: "ByteDance",
29
+ deepseek: "DeepSeek",
30
+ google: "Google",
31
+ ibm: "IBM",
32
+ inclusionai: "inclusionAI",
33
+ meta: "Meta",
34
+ microsoft: "Microsoft",
35
+ minimax: "MiniMax",
36
+ mistral: "Mistral",
37
+ moonshot: "Moonshot",
38
+ nvidia: "NVIDIA",
39
+ openai: "OpenAI",
40
+ perplexity: "Perplexity",
41
+ stepfun: "StepFun",
42
+ tencent: "Tencent",
43
+ xai: "xAI",
44
+ xiaomi: "Xiaomi",
45
+ zai: "Z.ai",
46
+ };
47
+
48
+ const baseThinkingLevels: readonly ModelThinkingLevel[] = ["minimal", "low", "medium", "high"];
49
+ const extendedThinkingLevels: readonly ModelThinkingLevel[] = ["xhigh", "max"];
50
+
51
+ function usableProviders(model: GatewayModel, now: number): GatewayProvider[] {
52
+ return model.providers.filter(
53
+ (provider) => provider.streaming && provider.tools && (provider.deactivatedAt === undefined || provider.deactivatedAt > now),
54
+ );
55
+ }
56
+
57
+ export function isAgentModel(model: GatewayModel, now: number): boolean {
58
+ return (
59
+ model.family !== PROVIDER_ID &&
60
+ model.contextLength > 0 &&
61
+ model.outputModalities.includes("text") &&
62
+ (model.deactivatedAt === undefined || model.deactivatedAt > now) &&
63
+ usableProviders(model, now).length > 0
64
+ );
65
+ }
66
+
67
+ function thinkingLevelMap(providers: GatewayProvider[]): ThinkingLevelMap | undefined {
68
+ const efforts = new Set(providers.flatMap((provider) => provider.reasoningEfforts));
69
+ if (efforts.size === 0) return undefined;
70
+ const map: ThinkingLevelMap = {};
71
+ for (const level of baseThinkingLevels) map[level] = efforts.has(level) ? level : null;
72
+ for (const level of extendedThinkingLevels) if (efforts.has(level)) map[level] = level;
73
+ return map;
74
+ }
75
+
76
+ function perMillion(perToken: number): number {
77
+ return Math.round(perToken * 1e12) / 1e6;
78
+ }
79
+
80
+ function rates(source: Partial<GatewayRates>, base: GatewayRates) {
81
+ return {
82
+ input: perMillion(source.prompt ?? base.prompt),
83
+ output: perMillion(source.completion ?? base.completion),
84
+ cacheRead: perMillion(source.cacheRead ?? base.cacheRead),
85
+ cacheWrite: perMillion(source.cacheWrite ?? base.cacheWrite),
86
+ };
87
+ }
88
+
89
+ function cost(pricing: GatewayPricing): ModelCost {
90
+ const tiers: ModelCostTier[] = [];
91
+ for (const [index, tier] of pricing.tiers.entries()) {
92
+ const above = pricing.tiers[index - 1]?.upToTokens;
93
+ if (index > 0 && above !== undefined) tiers.push({ inputTokensAbove: above, ...rates(tier, pricing) });
94
+ }
95
+ return { ...rates({}, pricing), ...(tiers.length > 0 ? { tiers } : {}) };
96
+ }
97
+
98
+ function compat(family: string): OpenAICompletionsCompat {
99
+ return {
100
+ maxTokensField: "max_tokens",
101
+ supportsUsageInStreaming: true,
102
+ thinkingFormat: "openai",
103
+ sendSessionAffinityHeaders: true,
104
+ sessionAffinityFormat: "openrouter",
105
+ supportsDeveloperRole: family === "openai",
106
+ supportsStore: false,
107
+ };
108
+ }
109
+
110
+ export function toPiModel(model: GatewayModel, now: number): GatewayChatModel {
111
+ const usable = usableProviders(model, now);
112
+ const thinking = thinkingLevelMap(usable);
113
+ return {
114
+ id: `${model.family}/${model.id}`,
115
+ name: `${authorLabels[model.family] ?? model.family}: ${model.name}`,
116
+ api: "openai-completions",
117
+ provider: PROVIDER_ID,
118
+ baseUrl: BASE_URL,
119
+ reasoning: model.supportedParameters.includes("reasoning"),
120
+ ...(thinking ? { thinkingLevelMap: thinking } : {}),
121
+ input: model.inputModalities.includes("image") ? ["text", "image"] : ["text"],
122
+ cost: cost(model.pricing),
123
+ contextWindow: model.contextLength,
124
+ maxTokens: model.maxOutput ?? model.contextLength,
125
+ compat: compat(model.family),
126
+ llmgatewayUpstreamId: model.id,
127
+ llmgatewayProviders: usable.map((provider) => ({ id: provider.id, regions: provider.regions })),
128
+ };
129
+ }
130
+
131
+ export function toPiModels(models: GatewayModel[], now: number): GatewayChatModel[] {
132
+ return models.filter((model) => isAgentModel(model, now)).map((model) => toPiModel(model, now));
133
+ }
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { join } from "node:path";
2
+ import { type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { accountStatus } from "./account/account-status.ts";
4
+ import { keyClient } from "./account/key-info.ts";
5
+ import { registerAccount } from "./account/register-account.ts";
6
+ import { BASE_URL, PROVIDER_ID } from "./catalog/model-mapping.ts";
7
+ import { registerMenu } from "./menu/register-menu.ts";
8
+ import { registerPin } from "./pin/register-pin.ts";
9
+ import { registerProvider } from "./request/register-provider.ts";
10
+ import { fileConfigStore, storedFooter } from "./routing/config-store.ts";
11
+ import { registerRouting } from "./routing/register-routing.ts";
12
+
13
+ export default function llmgateway(pi: ExtensionAPI): void {
14
+ const store = fileConfigStore(join(getAgentDir(), "llmgateway.json"));
15
+ const fetchImpl: typeof fetch = (input, init) => fetch(input, init);
16
+ const client = keyClient({ fetchImpl, baseUrl: BASE_URL });
17
+ const status = accountStatus({ providerId: PROVIDER_ID, client, footer: () => storedFooter(store), now: Date.now });
18
+ registerProvider(pi, {
19
+ store,
20
+ client,
21
+ onServed: (served) => status.served(served),
22
+ fetchImpl,
23
+ env: (name) => process.env[name],
24
+ now: Date.now,
25
+ });
26
+ registerRouting(pi, { store, plan: () => client.plan(), refresh: status.refresh });
27
+ registerPin(pi, { store, plan: () => client.plan(), refresh: status.refresh });
28
+ registerMenu(pi, { store, plan: () => client.plan(), planName: () => client.last()?.planName, refresh: status.refresh });
29
+ registerAccount(pi, { status, now: Date.now });
30
+ }
@@ -0,0 +1,45 @@
1
+ import { STATUS_KEYS, type StatusKey } from "../account/footer-status.ts";
2
+ import { toggleFooterKey } from "../account/footer-writes.ts";
3
+ import type { Plan } from "../routing/routing-config.ts";
4
+ import { currentConfig, type MenuDeps, type Row, row } from "./menu-types.ts";
5
+
6
+ interface StatusInfo {
7
+ sample: string;
8
+ source: string;
9
+ plan: Exclude<Plan, undefined> | undefined;
10
+ }
11
+
12
+ const STATUS_INFO: Record<StatusKey, StatusInfo> = {
13
+ "llmgateway-provider": { sample: "aws-bedrock:eu", source: "the serving provider of the last response", plan: undefined },
14
+ "llmgateway-day": { sample: "day 3.10/14.22", source: "the DevPass daily meter", plan: "devpass" },
15
+ "llmgateway-premium": { sample: "prem 5.00/18.96", source: "the DevPass weekly premium meter", plan: "devpass" },
16
+ "llmgateway-month": { sample: "mo 25.00/158.00", source: "the DevPass monthly meter", plan: "devpass" },
17
+ "llmgateway-spend": { sample: "$31.42/$50.00", source: "pay-as-you-go spend and key limit", plan: "payg" },
18
+ "llmgateway-premium-model": { sample: "★", source: "the selected model meeting the premium price rule", plan: undefined },
19
+ };
20
+
21
+ const PLAN_NAMES = { devpass: "DevPass", payg: "pay-as-you-go" };
22
+
23
+ function describeStatus(info: StatusInfo, plan: Plan): string {
24
+ const base = `Shows ${info.sample} from ${info.source}.`;
25
+ if (info.plan === undefined || plan === undefined || plan === info.plan) return base;
26
+ return `${base} Never shows on your plan: it needs ${PLAN_NAMES[info.plan]}.`;
27
+ }
28
+
29
+ export function footerCount(deps: MenuDeps): string {
30
+ return String(currentConfig(deps).footer.length);
31
+ }
32
+
33
+ export function footerRows(deps: MenuDeps): Row[] {
34
+ const listed = currentConfig(deps).footer;
35
+ return STATUS_KEYS.map((key) =>
36
+ row({
37
+ id: key,
38
+ label: key,
39
+ description: describeStatus(STATUS_INFO[key], deps.plan()),
40
+ currentValue: listed.includes(key) ? "on" : "off",
41
+ values: ["on", "off"],
42
+ write: (value) => toggleFooterKey(deps.store, key, value === "on"),
43
+ }),
44
+ );
45
+ }
@@ -0,0 +1,18 @@
1
+ import { runPinCommand } from "../pin/pin-command.ts";
2
+ import { runRoutingCommand } from "../routing/routing-command.ts";
3
+ import { currentConfig, type MenuDeps } from "./menu-types.ts";
4
+ import { planLabel } from "./top-rows.ts";
5
+
6
+ export async function menuSummary(deps: MenuDeps): Promise<string> {
7
+ const known = deps.catalog().map((model) => model.id);
8
+ const routing = await runRoutingCommand("", { store: deps.store, plan: deps.plan, knownModel: (id) => known.includes(id) });
9
+ const pins = await runPinCommand("", { store: deps.store, plan: deps.plan, models: deps.catalog });
10
+ const footer = currentConfig(deps).footer;
11
+ return [
12
+ `LLM Gateway plan: ${planLabel(deps.plan(), deps.planName())}`,
13
+ routing.message,
14
+ pins.message,
15
+ `footer statuses: ${footer.length > 0 ? footer.join(", ") : "none"}`,
16
+ "The settings menu needs the interactive terminal. Change routing with /llmgateway-routing and pins with /llmgateway-pin. /llmgateway-usage shows plan usage. Footer statuses change in the menu or in llmgateway.json.",
17
+ ].join("\n\n");
18
+ }
@@ -0,0 +1,44 @@
1
+ import type { Component, SelectItem, SettingItem } from "@earendil-works/pi-tui";
2
+ import type { PinModel } from "../pin/pin-target.ts";
3
+ import type { ConfigStore, Refusal } from "../routing/config-store.ts";
4
+ import { emptyConfig, type GatewayConfig, type Plan } from "../routing/routing-config.ts";
5
+
6
+ export type Row = SettingItem & { write: ((value: string) => Promise<Refusal | undefined>) | undefined };
7
+
8
+ export interface Host extends Component {
9
+ show(page: Component): void;
10
+ }
11
+
12
+ export interface Widgets {
13
+ host(): Host;
14
+ settings(build: () => Row[], close: () => void, options: { title?: string; search?: boolean }): Component;
15
+ picker(items: SelectItem[], pick: (value: string) => void, close: () => void, title?: string): Component;
16
+ }
17
+
18
+ export interface MenuDeps {
19
+ store: ConfigStore;
20
+ plan: () => Plan;
21
+ planName: () => string | undefined;
22
+ refreshPlan: () => Promise<void>;
23
+ catalog: () => PinModel[];
24
+ targets: () => PinModel[];
25
+ notify: (message: string, level: "info" | "warning" | "error") => void;
26
+ }
27
+
28
+ const lastGood = new WeakMap<ConfigStore, GatewayConfig>();
29
+
30
+ export function currentConfig(deps: MenuDeps): GatewayConfig {
31
+ const read = deps.store.read();
32
+ if (read.ok) lastGood.set(deps.store, read.config);
33
+ return read.ok ? read.config : (lastGood.get(deps.store) ?? emptyConfig());
34
+ }
35
+
36
+ export function row(fields: Partial<Row> & Pick<Row, "id" | "label" | "currentValue">): Row {
37
+ return {
38
+ description: undefined,
39
+ values: undefined,
40
+ submenu: undefined,
41
+ write: undefined,
42
+ ...fields,
43
+ };
44
+ }
@@ -0,0 +1,143 @@
1
+ import { getSelectListTheme, getSettingsListTheme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type Component,
4
+ fuzzyFilter,
5
+ getKeybindings,
6
+ Input,
7
+ type SelectItem,
8
+ SelectList,
9
+ SettingsList,
10
+ } from "@earendil-works/pi-tui";
11
+ import type { Host, Row, Widgets } from "./menu-types.ts";
12
+
13
+ const VISIBLE_ROWS = 12;
14
+ const LIST_KEYS = [
15
+ "tui.select.up",
16
+ "tui.select.down",
17
+ "tui.select.pageUp",
18
+ "tui.select.pageDown",
19
+ "tui.select.confirm",
20
+ "tui.select.cancel",
21
+ ] as const;
22
+
23
+ export interface WidgetEnv {
24
+ requestRender: () => void;
25
+ notify: (message: string, level: "info" | "warning" | "error") => void;
26
+ }
27
+
28
+ class PageHost implements Host {
29
+ private page: Component | undefined;
30
+
31
+ show(page: Component): void {
32
+ this.page = page;
33
+ }
34
+
35
+ render(width: number): string[] {
36
+ return this.page?.render(width) ?? [];
37
+ }
38
+
39
+ handleInput(data: string): void {
40
+ this.page?.handleInput?.(data);
41
+ }
42
+
43
+ invalidate(): void {
44
+ this.page?.invalidate();
45
+ }
46
+ }
47
+
48
+ class Titled implements Component {
49
+ constructor(
50
+ private readonly title: string | undefined,
51
+ private readonly inner: Component,
52
+ ) {}
53
+
54
+ render(width: number): string[] {
55
+ if (this.title === undefined) return this.inner.render(width);
56
+ return [getSettingsListTheme().label(this.title, true), "", ...this.inner.render(width)];
57
+ }
58
+
59
+ handleInput(data: string): void {
60
+ this.inner.handleInput?.(data);
61
+ }
62
+
63
+ invalidate(): void {
64
+ this.inner.invalidate();
65
+ }
66
+ }
67
+
68
+ class SearchSelect implements Component {
69
+ private readonly input = new Input();
70
+ private query = "";
71
+ private list: SelectList;
72
+
73
+ constructor(
74
+ private readonly items: SelectItem[],
75
+ private readonly pick: (value: string) => void,
76
+ private readonly close: () => void,
77
+ ) {
78
+ this.input.focused = true;
79
+ this.list = this.build();
80
+ }
81
+
82
+ private build(): SelectList {
83
+ const shown = fuzzyFilter(this.items, this.query, (item) => `${item.label} ${item.description ?? ""}`);
84
+ const list = new SelectList(shown, VISIBLE_ROWS, getSelectListTheme());
85
+ list.onSelect = (item) => this.pick(item.value);
86
+ list.onCancel = this.close;
87
+ return list;
88
+ }
89
+
90
+ render(width: number): string[] {
91
+ const hint = getSettingsListTheme().hint(" Type to search · Enter to select · Esc to go back");
92
+ return [...this.input.render(width), "", ...this.list.render(width), "", hint];
93
+ }
94
+
95
+ handleInput(data: string): void {
96
+ const keys = getKeybindings();
97
+ if (LIST_KEYS.some((key) => keys.matches(data, key))) {
98
+ this.list.handleInput(data);
99
+ return;
100
+ }
101
+ this.input.handleInput(data);
102
+ const query = this.input.getValue();
103
+ if (query === this.query) return;
104
+ this.query = query;
105
+ this.list = this.build();
106
+ }
107
+
108
+ invalidate(): void {
109
+ this.input.invalidate();
110
+ this.list.invalidate();
111
+ }
112
+ }
113
+
114
+ export function createWidgets(env: WidgetEnv): Widgets {
115
+ return {
116
+ host: () => new PageHost(),
117
+ picker: (items, pick, close, title) => new Titled(title, new SearchSelect(items, pick, close)),
118
+ settings: (build, close, options) => {
119
+ const rows = build();
120
+ const sync = (): void => {
121
+ for (const fresh of build()) {
122
+ const target = rows.find((candidate) => candidate.id === fresh.id);
123
+ if (target) Object.assign(target, fresh);
124
+ }
125
+ };
126
+ const change = async (id: string, value: string): Promise<void> => {
127
+ const refusal = await rows.find((candidate: Row) => candidate.id === id)?.write?.(value);
128
+ if (refusal) env.notify(refusal.message, refusal.level);
129
+ sync();
130
+ env.requestRender();
131
+ };
132
+ const list = new SettingsList(
133
+ rows,
134
+ VISIBLE_ROWS,
135
+ getSettingsListTheme(),
136
+ (id, value) => void change(id, value),
137
+ close,
138
+ { enableSearch: options.search ?? false },
139
+ );
140
+ return new Titled(options.title, list);
141
+ },
142
+ };
143
+ }
@@ -0,0 +1,113 @@
1
+ import type { SelectItem } from "@earendil-works/pi-tui";
2
+ import { describePin } from "../pin/pin-command.ts";
3
+ import { type PinModel, pinOptions } from "../pin/pin-target.ts";
4
+ import { removePin, setPin } from "../pin/pin-writes.ts";
5
+ import { describePrefs } from "../routing/routing-command.ts";
6
+ import { effectivePrefs, type Plan } from "../routing/routing-config.ts";
7
+ import { resetTarget } from "../routing/routing-writes.ts";
8
+ import { currentConfig, type MenuDeps, type Row, row, type Widgets } from "./menu-types.ts";
9
+ import { routingRow } from "./routing-rows.ts";
10
+
11
+ const STORED_MARKER = " ●";
12
+
13
+ export function pickerItems(deps: MenuDeps): SelectItem[] {
14
+ const config = currentConfig(deps);
15
+ const plan = deps.plan();
16
+ const catalog = deps.catalog();
17
+ const listed = deps.targets().map((model) => model.id);
18
+ const stored = [...new Set([...Object.keys(config.models), ...Object.keys(config.pins)])];
19
+ return [...listed, ...stored.filter((id) => !listed.includes(id))].map((id) => {
20
+ const entry = id in config.models;
21
+ const pin = config.pins[id];
22
+ const model = catalog.find((candidate) => candidate.id === id);
23
+ const parts: string[] = [];
24
+ if (!model) parts.push("not in the catalog");
25
+ if (entry) parts.push(describePrefs(effectivePrefs(config, id), plan));
26
+ if (pin !== undefined) parts.push(`pin ${describePin(model?.providers ?? [], pin, plan)}`);
27
+ const marked = entry || pin !== undefined;
28
+ return {
29
+ value: id,
30
+ label: marked ? `${id}${STORED_MARKER}` : id,
31
+ description: parts.length > 0 ? parts.join("; ") : "no stored settings",
32
+ };
33
+ });
34
+ }
35
+
36
+ export function storedModelCount(deps: MenuDeps): string {
37
+ const config = currentConfig(deps);
38
+ return String(new Set([...Object.keys(config.models), ...Object.keys(config.pins)]).size);
39
+ }
40
+
41
+ function pinChoices(options: string[], stored: string | undefined): SelectItem[] {
42
+ const choices: SelectItem[] = [{ value: "off", label: "off", description: stored === undefined ? "No pin" : `Remove the pin ${stored}` }];
43
+ for (const option of options) {
44
+ const region = option.includes(":");
45
+ choices.push({ value: option, label: option, description: region ? "Pin to this provider region" : "Pin to this provider" });
46
+ }
47
+ return choices;
48
+ }
49
+
50
+ function pinReason(model: PinModel | undefined, plan: Plan, offered: boolean, options: string[]): string {
51
+ if (!model) return "This model is not in the catalog. Only removing a stored pin is possible.";
52
+ if (plan === "devpass") return `Provider pins need a pay-as-you-go key, and this key is on DevPass.${offered ? " Only off is available." : ""}`;
53
+ if (plan === undefined) return `The plan is unknown, so pins are unavailable.${offered ? " Only off is available." : ""} Select Plan in the top menu.`;
54
+ if (options.length === 0) return "The catalog lists no providers for this model.";
55
+ return "Send this model to one provider or region. Choose off to remove the pin.";
56
+ }
57
+
58
+ function pinRow(deps: MenuDeps, widgets: Widgets, id: string, model: PinModel | undefined): Row {
59
+ const plan = deps.plan();
60
+ const stored = currentConfig(deps).pins[id];
61
+ const options = model && plan === "payg" ? pinOptions(model.providers) : [];
62
+ const offered = options.length > 0 || stored !== undefined;
63
+ const shown = stored === undefined ? "off" : describePin(model?.providers ?? [], stored, plan);
64
+ const apply = (value: string) =>
65
+ value === "off"
66
+ ? stored === undefined
67
+ ? Promise.resolve(undefined)
68
+ : removePin(deps.store, id)
69
+ : setPin(deps.store, plan, model ?? { id, providers: [] }, value);
70
+ return row({
71
+ id: "pin",
72
+ label: "Pin",
73
+ description: pinReason(model, plan, offered, options),
74
+ currentValue: shown,
75
+ submenu: offered
76
+ ? (_current, done) =>
77
+ widgets.picker(
78
+ pinChoices(options, stored),
79
+ (value) => {
80
+ void apply(value).then((refusal) => {
81
+ if (refusal) deps.notify(refusal.message, refusal.level);
82
+ done(refusal ? shown : value);
83
+ });
84
+ },
85
+ () => done(),
86
+ `Pin: ${id}`,
87
+ )
88
+ : undefined,
89
+ });
90
+ }
91
+
92
+ function resetRow(deps: MenuDeps, id: string): Row {
93
+ const stored = id in currentConfig(deps).models;
94
+ const label = stored ? "reset" : "nothing stored";
95
+ return row({
96
+ id: "reset",
97
+ label: "Reset routing",
98
+ description: "Remove the routing settings of this model. The pin stays.",
99
+ currentValue: label,
100
+ values: [label],
101
+ write: () => (stored ? resetTarget(deps.store, id) : Promise.resolve(undefined)),
102
+ });
103
+ }
104
+
105
+ export function modelRows(deps: MenuDeps, widgets: Widgets, id: string): Row[] {
106
+ const config = currentConfig(deps);
107
+ const model = deps.catalog().find((candidate) => candidate.id === id);
108
+ const own = config.models[id] ?? {};
109
+ const routing = model
110
+ ? (["sort", "tier", "fallback"] as const).map((setting) => routingRow(deps, setting, id, config.default, own))
111
+ : [];
112
+ return [...routing, pinRow(deps, widgets, id, model), resetRow(deps, id)];
113
+ }
@@ -0,0 +1,53 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { pinModels } from "../pin/pin-target.ts";
3
+ import { gatewayModels, trackCompletionTargets } from "../routing/completion-targets.ts";
4
+ import type { ConfigStore } from "../routing/config-store.ts";
5
+ import type { Plan } from "../routing/routing-config.ts";
6
+ import { createWidgets } from "./menu-widgets.ts";
7
+ import { menuSummary } from "./menu-summary.ts";
8
+ import type { MenuDeps } from "./menu-types.ts";
9
+ import { topRows } from "./top-rows.ts";
10
+
11
+ export interface RegisterMenuDeps {
12
+ store: ConfigStore;
13
+ plan: () => Plan;
14
+ planName: () => string | undefined;
15
+ refresh: (ctx: ExtensionContext, signal?: AbortSignal) => Promise<unknown>;
16
+ }
17
+
18
+ export function registerMenu(pi: ExtensionAPI, deps: RegisterMenuDeps): void {
19
+ const completionTargets = trackCompletionTargets(pi);
20
+ pi.registerCommand("llmgateway", {
21
+ description: "Open the LLM Gateway settings menu",
22
+ handler: async (_args, ctx) => {
23
+ const read = deps.store.read();
24
+ if (!read.ok) {
25
+ ctx.ui.notify(read.error, "error");
26
+ return;
27
+ }
28
+ if (!deps.plan()) await deps.refresh(ctx, ctx.signal).catch(() => undefined);
29
+ const menu: MenuDeps = {
30
+ store: deps.store,
31
+ plan: deps.plan,
32
+ planName: deps.planName,
33
+ refreshPlan: async () => {
34
+ await deps.refresh(ctx, ctx.signal);
35
+ },
36
+ catalog: () => pinModels(gatewayModels(ctx)),
37
+ targets: () => {
38
+ const scoped = completionTargets();
39
+ return pinModels(scoped.length > 0 ? scoped : gatewayModels(ctx));
40
+ },
41
+ notify: (message, level) => ctx.ui.notify(message, level),
42
+ };
43
+ if (ctx.mode !== "tui") {
44
+ ctx.ui.notify(await menuSummary(menu), "info");
45
+ return;
46
+ }
47
+ await ctx.ui.custom<void>((tui, _theme, _keys, done) => {
48
+ const widgets = createWidgets({ requestRender: () => tui.requestRender(), notify: menu.notify });
49
+ return widgets.settings(() => topRows(menu, widgets), () => done(), { search: true });
50
+ });
51
+ },
52
+ });
53
+ }
@@ -0,0 +1,57 @@
1
+ import { ignoredMark } from "../routing/routing-command.ts";
2
+ import type { Plan, RoutingPrefs } from "../routing/routing-config.ts";
3
+ import { deleteRoutingField, setRoutingField, settingValues } from "../routing/routing-writes.ts";
4
+ import { type MenuDeps, type Row, row } from "./menu-types.ts";
5
+
6
+ export type RoutingSetting = "sort" | "tier" | "fallback";
7
+
8
+ const LABELS: Record<RoutingSetting, string> = { sort: "Strategy", tier: "Service tier", fallback: "Fallback" };
9
+ const FALLBACK_DEFAULTS: Record<RoutingSetting, string> = { sort: "auto", tier: "auto", fallback: "on" };
10
+
11
+ function storedValue(prefs: RoutingPrefs, setting: RoutingSetting): string | undefined {
12
+ if (setting === "sort") return prefs.routing;
13
+ if (setting === "tier") return prefs.tier;
14
+ if (prefs.fallback === undefined) return undefined;
15
+ return prefs.fallback ? "on" : "off";
16
+ }
17
+
18
+ function marked(value: string, setting: RoutingSetting, plan: Plan): string {
19
+ return settingValues(setting, plan).includes(value) ? value : `${value}${ignoredMark(plan)}`;
20
+ }
21
+
22
+ function effective(defaults: RoutingPrefs, setting: RoutingSetting, plan: Plan): string {
23
+ const value = storedValue(defaults, setting);
24
+ return value === undefined ? FALLBACK_DEFAULTS[setting] : marked(value, setting, plan);
25
+ }
26
+
27
+ function describe(setting: RoutingSetting, target: string, plan: Plan): string {
28
+ const accepted = `Accepted on your plan: ${settingValues(setting, plan).join(", ")}.`;
29
+ const unset = target === "default" ? "unset leaves the choice to the gateway." : "inherit uses the default.";
30
+ const scope = target === "default" ? "every model" : "this model";
31
+ const noun = { sort: "Routing strategy", tier: "Service tier", fallback: "Cross-provider fallback" }[setting];
32
+ return setting === "fallback" && target === "default"
33
+ ? `${noun} for ${scope}. ${accepted}`
34
+ : `${noun} for ${scope}. ${unset} ${accepted}`;
35
+ }
36
+
37
+ export function routingRow(deps: MenuDeps, setting: RoutingSetting, target: string, defaults: RoutingPrefs, own: RoutingPrefs): Row {
38
+ const plan = deps.plan();
39
+ const isDefault = target === "default";
40
+ const keepsDefault = isDefault && setting === "fallback";
41
+ const stored = storedValue(isDefault ? defaults : own, setting);
42
+ const unsetLabel = isDefault ? "unset" : `inherit (${effective(defaults, setting, plan)})`;
43
+ let shown = stored === undefined ? unsetLabel : marked(stored, setting, plan);
44
+ if (keepsDefault) shown = stored === undefined ? "on" : marked(stored, setting, plan);
45
+ const values = keepsDefault ? [...settingValues(setting, plan)] : [unsetLabel, ...settingValues(setting, plan)];
46
+ return row({
47
+ id: setting,
48
+ label: LABELS[setting],
49
+ description: describe(setting, target, plan),
50
+ currentValue: shown,
51
+ values,
52
+ write: (value) =>
53
+ value === unsetLabel
54
+ ? deleteRoutingField(deps.store, target, setting)
55
+ : setRoutingField(deps.store, plan, target, setting, value),
56
+ });
57
+ }