@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,88 @@
1
+ import type { ConfigStore } from "./config-store.ts";
2
+ import { allowedStrategies, allowedTiers, type GatewayConfig, type Plan, type RoutingPrefs } from "./routing-config.ts";
3
+ import { resetTarget, SETTINGS, setRoutingField, settingValues, type CommandResult } from "./routing-writes.ts";
4
+
5
+ export interface CompletionItem {
6
+ value: string;
7
+ label: string;
8
+ description?: string;
9
+ }
10
+
11
+ export interface RoutingCommandDeps {
12
+ store: ConfigStore;
13
+ plan: () => Plan;
14
+ knownModel: (id: string) => boolean;
15
+ }
16
+
17
+ export function complete(prefix: string, options: readonly string[], toValue: (option: string) => string): CompletionItem[] {
18
+ return options
19
+ .filter((option) => option.startsWith(prefix))
20
+ .map((option) => ({ value: toValue(option), label: option }));
21
+ }
22
+
23
+ export function routingCompletions(argumentPrefix: string, targets: string[], plan: Plan): CompletionItem[] | null {
24
+ const tokens = argumentPrefix.trimStart().split(/\s+/);
25
+ const [target = "", setting = "", value = ""] = tokens;
26
+ let items: CompletionItem[] = [];
27
+ if (tokens.length <= 1) items = complete(target, ["default", ...targets], (option) => `${option} `);
28
+ else if (tokens.length === 2) {
29
+ items = complete(setting, Object.keys(SETTINGS), (option) => `${target} ${option}${option === "reset" ? "" : " "}`);
30
+ for (const item of items) item.description = SETTINGS[item.label];
31
+ } else if (tokens.length === 3) {
32
+ items = complete(value, settingValues(setting, plan), (option) => `${target} ${setting} ${option}`);
33
+ }
34
+ return items.length > 0 ? items : null;
35
+ }
36
+
37
+ export function ignoredMark(plan: Plan): string {
38
+ return plan === undefined ? " (ignored: plan unknown)" : " (ignored on DevPass)";
39
+ }
40
+
41
+ export function describePrefs(prefs: RoutingPrefs, plan: Plan): string {
42
+ const sortMark = prefs.routing && !allowedStrategies(plan).includes(prefs.routing) ? ignoredMark(plan) : "";
43
+ const tierMark = prefs.tier && !allowedTiers(plan).includes(prefs.tier) ? ignoredMark(plan) : "";
44
+ const parts = [
45
+ `sort ${prefs.routing ?? "auto"}${sortMark}`,
46
+ `tier ${prefs.tier ?? "auto"}${tierMark}`,
47
+ `fallback ${prefs.fallback === false ? "off" : "on"}`,
48
+ ];
49
+ return parts.join(", ");
50
+ }
51
+
52
+ export function describeConfig(config: GatewayConfig, plan: Plan): string {
53
+ const planLabel = plan === "payg" ? "pay-as-you-go" : plan === "devpass" ? "DevPass" : "unknown plan, DevPass limits";
54
+ const lines = [`LLM Gateway routing (${planLabel})`, `default: ${describePrefs(config.default, plan)}`];
55
+ for (const [id, prefs] of Object.entries(config.models)) {
56
+ lines.push(`${id}: ${describePrefs({ ...config.default, ...prefs }, plan)}`);
57
+ }
58
+ return lines.join("\n");
59
+ }
60
+
61
+ function validate(args: string[], deps: RoutingCommandDeps): string | undefined {
62
+ const [target, setting, value] = args;
63
+ if (!target || !setting) return "Usage: /llmgateway-routing [<default|model> <sort|tier|fallback|reset> [value]]";
64
+ if (target !== "default" && !deps.knownModel(target)) return `Unknown LLM Gateway model: ${target}`;
65
+ if (!(setting in SETTINGS)) return `Unknown setting: ${setting}. Use sort, tier, fallback or reset.`;
66
+ if (setting === "reset") return args.length === 2 ? undefined : "reset takes no value";
67
+ const allowed = settingValues(setting, deps.plan());
68
+ if (!value || !allowed.includes(value) || args.length > 3) return `${setting} accepts: ${allowed.join(", ")}`;
69
+ return undefined;
70
+ }
71
+
72
+ export async function runRoutingCommand(argText: string, deps: RoutingCommandDeps): Promise<CommandResult> {
73
+ const args = argText.trim().split(/\s+/).filter(Boolean);
74
+ if (args.length === 0) {
75
+ const read = deps.store.read();
76
+ if (!read.ok) return { message: read.error, level: "error" };
77
+ return { message: describeConfig(read.config, deps.plan()), level: "info" };
78
+ }
79
+ const invalid = validate(args, deps);
80
+ if (invalid) return { message: invalid, level: "warning" };
81
+ const [target = "", setting = "", value = ""] = args;
82
+ const reset = setting === "reset";
83
+ const refusal = reset
84
+ ? await resetTarget(deps.store, target)
85
+ : await setRoutingField(deps.store, deps.plan(), target, setting, value);
86
+ if (refusal) return refusal;
87
+ return { message: reset ? `${target}: settings removed` : `${target}: ${setting} ${value}`, level: "info" };
88
+ }
@@ -0,0 +1,96 @@
1
+ export const STRATEGIES = ["auto", "price", "throughput", "latency"] as const;
2
+ export const TIERS = ["auto", "default", "flex", "priority"] as const;
3
+ const DEVPASS_STRATEGIES: readonly string[] = ["auto", "price"];
4
+ const DEVPASS_TIERS: readonly string[] = ["auto", "default", "flex"];
5
+
6
+ export type Strategy = (typeof STRATEGIES)[number];
7
+ export type Tier = (typeof TIERS)[number];
8
+ export type Plan = "devpass" | "payg" | undefined;
9
+
10
+ export interface RoutingPrefs {
11
+ routing?: Strategy;
12
+ tier?: Tier;
13
+ fallback?: boolean;
14
+ }
15
+
16
+ export interface GatewayConfig {
17
+ default: RoutingPrefs;
18
+ models: Record<string, RoutingPrefs>;
19
+ pins: Record<string, string>;
20
+ footer: string[];
21
+ }
22
+
23
+ export type Json = Record<string, unknown>;
24
+
25
+ export type ConfigRead = { ok: true; raw: Json; config: GatewayConfig } | { ok: false; error: string };
26
+
27
+ export function isObject(value: unknown): value is Json {
28
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29
+ }
30
+
31
+ function oneOf<T extends string>(values: readonly T[], value: unknown): T | undefined {
32
+ return values.find((item) => item === value);
33
+ }
34
+
35
+ function parsePrefs(value: unknown): RoutingPrefs {
36
+ if (!isObject(value)) return {};
37
+ const prefs: RoutingPrefs = {};
38
+ const routing = oneOf(STRATEGIES, value.routing);
39
+ const tier = oneOf(TIERS, value.tier);
40
+ if (routing) prefs.routing = routing;
41
+ if (tier) prefs.tier = tier;
42
+ if (typeof value.fallback === "boolean") prefs.fallback = value.fallback;
43
+ return prefs;
44
+ }
45
+
46
+ export function emptyConfig(): GatewayConfig {
47
+ return { default: {}, models: {}, pins: {}, footer: [] };
48
+ }
49
+
50
+ export function parseConfig(text: string | undefined): ConfigRead {
51
+ if (text === undefined) return { ok: true, raw: { version: 1 }, config: emptyConfig() };
52
+ let raw: unknown;
53
+ try {
54
+ raw = JSON.parse(text);
55
+ } catch (error) {
56
+ return { ok: false, error: `llmgateway.json is not valid JSON: ${(error as Error).message}` };
57
+ }
58
+ if (!isObject(raw)) return { ok: false, error: "llmgateway.json must hold a JSON object" };
59
+ if (raw.version !== 1) return { ok: false, error: `llmgateway.json has unknown version ${JSON.stringify(raw.version)}` };
60
+ const models = isObject(raw.models) ? raw.models : {};
61
+ const pins = isObject(raw.pins) ? raw.pins : {};
62
+ return {
63
+ ok: true,
64
+ raw,
65
+ config: {
66
+ default: parsePrefs(raw.default),
67
+ models: Object.fromEntries(Object.entries(models).map(([id, prefs]) => [id, parsePrefs(prefs)])),
68
+ pins: Object.fromEntries(
69
+ Object.entries(pins).filter((entry): entry is [string, string] => typeof entry[1] === "string" && entry[1] !== ""),
70
+ ),
71
+ footer: Array.isArray(raw.footer) ? raw.footer.filter((key): key is string => typeof key === "string") : [],
72
+ },
73
+ };
74
+ }
75
+
76
+ export function allowedStrategies(plan: Plan): readonly string[] {
77
+ return plan === "payg" ? STRATEGIES : DEVPASS_STRATEGIES;
78
+ }
79
+
80
+ export function allowedTiers(plan: Plan): readonly string[] {
81
+ return plan === "payg" ? TIERS : DEVPASS_TIERS;
82
+ }
83
+
84
+ export function effectivePrefs(config: GatewayConfig, modelId: string): RoutingPrefs {
85
+ return { ...config.default, ...config.models[modelId] };
86
+ }
87
+
88
+ export function requestShape(config: GatewayConfig, modelId: string, plan: Plan) {
89
+ const prefs = effectivePrefs(config, modelId);
90
+ const body: Record<string, unknown> = {};
91
+ const headers: Record<string, string> = {};
92
+ if (prefs.routing && allowedStrategies(plan).includes(prefs.routing)) body.routing = prefs.routing;
93
+ if (prefs.tier && allowedTiers(plan).includes(prefs.tier)) body.service_tier = prefs.tier;
94
+ if (prefs.fallback === false) headers["X-No-Fallback"] = "true";
95
+ return { body, headers };
96
+ }
@@ -0,0 +1,80 @@
1
+ import { type ConfigStore, type Refusal, writeConfig } from "./config-store.ts";
2
+ import { allowedStrategies, allowedTiers, isObject, type Json, type Plan } from "./routing-config.ts";
3
+
4
+ export interface CommandResult {
5
+ message: string;
6
+ level: "info" | "warning" | "error";
7
+ }
8
+
9
+ export const SETTINGS: Record<string, string> = {
10
+ sort: "routing strategy",
11
+ tier: "service tier",
12
+ fallback: "cross-provider fallback",
13
+ reset: "remove all settings for the target",
14
+ };
15
+
16
+ const FIELDS: Record<string, string> = { sort: "routing", tier: "tier", fallback: "fallback" };
17
+
18
+ export function settingValues(setting: string, plan: Plan): readonly string[] {
19
+ if (setting === "sort") return allowedStrategies(plan);
20
+ if (setting === "tier") return allowedTiers(plan);
21
+ if (setting === "fallback") return ["on", "off"];
22
+ return [];
23
+ }
24
+
25
+ function section(raw: Json, target: string): Json {
26
+ if (target === "default") {
27
+ if (!isObject(raw.default)) raw.default = {};
28
+ return raw.default as Json;
29
+ }
30
+ if (!isObject(raw.models)) raw.models = {};
31
+ const models = raw.models as Json;
32
+ if (!isObject(models[target])) models[target] = {};
33
+ return models[target] as Json;
34
+ }
35
+
36
+ function existingSection(raw: Json, target: string): Json | undefined {
37
+ const found = target === "default" ? raw.default : isObject(raw.models) ? raw.models[target] : undefined;
38
+ return isObject(found) ? found : undefined;
39
+ }
40
+
41
+ function dropEmpty(raw: Json, target: string): void {
42
+ const found = existingSection(raw, target);
43
+ if (!found || Object.keys(found).length > 0) return;
44
+ if (target === "default") delete raw.default;
45
+ else delete (raw.models as Json)[target];
46
+ }
47
+
48
+ export function setRoutingField(
49
+ store: ConfigStore,
50
+ plan: Plan,
51
+ target: string,
52
+ setting: string,
53
+ value: string,
54
+ ): Promise<Refusal | undefined> {
55
+ const field = FIELDS[setting];
56
+ const allowed = settingValues(setting, plan);
57
+ if (!field || !allowed.includes(value)) {
58
+ return Promise.resolve({ message: `${setting} accepts: ${allowed.join(", ")}`, level: "warning" });
59
+ }
60
+ return writeConfig(store, (raw) => {
61
+ section(raw, target)[field] = setting === "fallback" ? value === "on" : value;
62
+ });
63
+ }
64
+
65
+ export function deleteRoutingField(store: ConfigStore, target: string, setting: string): Promise<Refusal | undefined> {
66
+ const field = FIELDS[setting] ?? setting;
67
+ return writeConfig(store, (raw) => {
68
+ const found = existingSection(raw, target);
69
+ if (!found) return;
70
+ delete found[field];
71
+ dropEmpty(raw, target);
72
+ });
73
+ }
74
+
75
+ export function resetTarget(store: ConfigStore, target: string): Promise<Refusal | undefined> {
76
+ return writeConfig(store, (raw) => {
77
+ if (target === "default") delete raw.default;
78
+ else if (isObject(raw.models)) delete raw.models[target];
79
+ });
80
+ }