ceulen 0.1.0 → 0.5.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/CHANGELOG.md +150 -0
- package/README.md +103 -14
- package/extensions/index.ts +113 -0
- package/extensions/lib/env.ts +75 -0
- package/extensions/lib/panel.ts +1720 -0
- package/extensions/lib/registry.ts +182 -0
- package/extensions/modules/composer/index.ts +128 -0
- package/extensions/modules/composer/lib/settings.ts +55 -0
- package/extensions/modules/composer/lib/shapes.ts +436 -0
- package/extensions/modules/composer/test/editor.test.ts +138 -0
- package/extensions/modules/composer/test/module.test.ts +218 -0
- package/extensions/modules/composer/test/screen.test.ts +195 -0
- package/extensions/modules/composer/test/shapes.test.ts +175 -0
- package/extensions/modules/config/index.ts +298 -0
- package/extensions/modules/config/piSettings.ts +467 -0
- package/extensions/modules/config/plugins.ts +290 -0
- package/extensions/modules/config/test/kernel.test.ts +523 -0
- package/extensions/modules/config/test/kernelV4.test.ts +196 -0
- package/extensions/modules/config/test/menu.test.ts +226 -0
- package/extensions/modules/config/test/panel.test.ts +395 -0
- package/extensions/modules/config/test/piSettings.test.ts +185 -0
- package/extensions/modules/config/test/plugins.test.ts +181 -0
- package/extensions/modules/config/test/preview-block.test.ts +88 -0
- package/extensions/modules/ponytail/UPSTREAM +26 -0
- package/extensions/modules/ponytail/index.ts +336 -0
- package/extensions/modules/ponytail/lib/config.ts +149 -0
- package/extensions/modules/ponytail/lib/instructions.ts +98 -0
- package/extensions/modules/ponytail/lib/subagent.ts +31 -0
- package/extensions/modules/ponytail/test/extension.test.ts +422 -0
- package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
- package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
- package/extensions/modules/router/commands/commands.ts +99 -0
- package/extensions/modules/router/configPanel.ts +89 -0
- package/extensions/modules/router/index.ts +75 -0
- package/extensions/modules/router/lib/client.ts +390 -0
- package/extensions/modules/router/lib/config.ts +142 -0
- package/extensions/modules/router/lib/migrate.ts +92 -0
- package/extensions/modules/router/lib/provider.ts +138 -0
- package/extensions/modules/router/lib/refresh.ts +19 -0
- package/extensions/modules/router/test/guard.test.ts +77 -0
- package/extensions/modules/router/test/unit.test.ts +1126 -0
- package/extensions/modules/usage/index.ts +1975 -0
- package/extensions/modules/usage/test/context.test.ts +387 -0
- package/extensions/modules/usage/test/env-gating.test.ts +113 -0
- package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
- package/extensions/modules/usage/test/parsers.test.ts +244 -0
- package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
- package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
- package/package.json +15 -3
- package/skills/ponytail/SKILL.md +124 -0
- package/skills/ponytail-audit/SKILL.md +41 -0
- package/skills/ponytail-debt/SKILL.md +44 -0
- package/skills/ponytail-gain/SKILL.md +51 -0
- package/skills/ponytail-help/SKILL.md +73 -0
- package/skills/ponytail-review/SKILL.md +57 -0
- package/extensions/index.js +0 -42
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { configSummary, getSettings } from "../lib/config.js";
|
|
3
|
+
import { maybeRefreshCatalog, PROVIDER_ID } from "../lib/provider.js";
|
|
4
|
+
|
|
5
|
+
/** Router model ids from the last /router-model invocation — the completion
|
|
6
|
+
* hook has no ctx, so it replays this cache (empty until first use). */
|
|
7
|
+
let lastRouterModelIds: string[] | undefined;
|
|
8
|
+
|
|
9
|
+
export function registerCommands(pi: ExtensionAPI): void {
|
|
10
|
+
pi.registerCommand("router-model", {
|
|
11
|
+
description: "Search and select a router model by name.",
|
|
12
|
+
getArgumentCompletions: (prefix) => {
|
|
13
|
+
// Model list is cached by the last invocation (registry is not reachable
|
|
14
|
+
// synchronously from the completion hook on first use).
|
|
15
|
+
const ids = lastRouterModelIds ?? [];
|
|
16
|
+
const q = (prefix || "").trim().toLowerCase();
|
|
17
|
+
const items = ids
|
|
18
|
+
.filter((id) => id.toLowerCase().includes(q))
|
|
19
|
+
.map((id) => ({ value: id, label: id }));
|
|
20
|
+
return items.length > 0 ? items : null;
|
|
21
|
+
},
|
|
22
|
+
handler: async (args, ctx) => {
|
|
23
|
+
if (ctx.mode !== "tui") {
|
|
24
|
+
ctx.ui.notify("/router-model requires interactive (TUI) mode.", "error");
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
// Pull the live catalog first (TTL-gated, in-flight-guarded) — mirrors
|
|
28
|
+
// Pi's own /model picker, which refreshes every time it opens. Best
|
|
29
|
+
// effort: on failure the cached list still serves.
|
|
30
|
+
try { await maybeRefreshCatalog(ctx); } catch { /* cached list below */ }
|
|
31
|
+
const ids = ctx.modelRegistry
|
|
32
|
+
.getAll()
|
|
33
|
+
.filter((m) => m.provider === PROVIDER_ID)
|
|
34
|
+
.map((m) => m.id);
|
|
35
|
+
lastRouterModelIds = ids;
|
|
36
|
+
if (ids.length === 0) {
|
|
37
|
+
ctx.ui.notify("No router models available yet — open /models or /login router to trigger discovery.", "error");
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const term = (args || "").trim().toLowerCase();
|
|
42
|
+
const matches = term ? ids.filter((id) => id.toLowerCase().includes(term)) : ids;
|
|
43
|
+
|
|
44
|
+
if (matches.length === 0) {
|
|
45
|
+
ctx.ui.notify(`No router models matching "${args}".`, "error");
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function trySelect(id: string): Promise<boolean> {
|
|
50
|
+
const model = ctx.modelRegistry.find(PROVIDER_ID, id);
|
|
51
|
+
if (!model) return false;
|
|
52
|
+
try { await pi.setModel(model); return true; }
|
|
53
|
+
catch { return false; }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if (matches.length === 1) {
|
|
57
|
+
const ok = await trySelect(matches[0]);
|
|
58
|
+
ctx.ui.notify(
|
|
59
|
+
ok ? `Selected ${PROVIDER_ID}/${matches[0]}` : `Failed to select ${PROVIDER_ID}/${matches[0]}`,
|
|
60
|
+
ok ? "info" : "error",
|
|
61
|
+
);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const choice = await ctx.ui.select("Select router model:", matches);
|
|
66
|
+
if (choice) {
|
|
67
|
+
const ok = await trySelect(choice);
|
|
68
|
+
ctx.ui.notify(
|
|
69
|
+
ok ? `Selected ${PROVIDER_ID}/${choice}` : `Failed to select ${PROVIDER_ID}/${choice}`,
|
|
70
|
+
ok ? "info" : "error",
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
pi.registerCommand("router-status", {
|
|
77
|
+
description: "Show router connection status and model info.",
|
|
78
|
+
handler: async (_args, ctx) => {
|
|
79
|
+
const settings = getSettings();
|
|
80
|
+
const count = ctx.modelRegistry
|
|
81
|
+
.getAll()
|
|
82
|
+
.filter((m) => m.provider === PROVIDER_ID).length;
|
|
83
|
+
const lines = [
|
|
84
|
+
"── Router Status ──",
|
|
85
|
+
configSummary(settings),
|
|
86
|
+
`Models in catalog: ${count}`,
|
|
87
|
+
"",
|
|
88
|
+
"Commands:",
|
|
89
|
+
" /login router Store API key (auth.json)",
|
|
90
|
+
" /config Central settings panel (all ceulen modules)",
|
|
91
|
+
" /router-model Search and select a model",
|
|
92
|
+
" /model Pi built-in picker (triggers refresh)",
|
|
93
|
+
"",
|
|
94
|
+
"URL: settings.json `router.baseUrl` or ROUTER_BASE_URL env.",
|
|
95
|
+
];
|
|
96
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Router's contribution to the central /config panel: ONE build + save path
|
|
3
|
+
* (the save must re-register the provider and force a catalog refresh —
|
|
4
|
+
* duplicating it would drift).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import type { ModuleConfig } from "../../lib/registry.js";
|
|
9
|
+
import { row, type PanelGroup } from "../../lib/panel.js";
|
|
10
|
+
import { getSettings, writeRouterSection, type RouterSettings } from "./lib/config.js";
|
|
11
|
+
import { registerProvider, maybeRefreshCatalog } from "./lib/provider.js";
|
|
12
|
+
import { refreshActiveModel } from "./lib/refresh.js";
|
|
13
|
+
|
|
14
|
+
/** Build the router panel groups over a working copy (mutated by row setters).
|
|
15
|
+
* ONE group — the OMP "Providers" tab carries a single "Router" section
|
|
16
|
+
* (its Enable kill-switch row is prepended by the config module). Exported
|
|
17
|
+
* for tests. */
|
|
18
|
+
export function buildRouterGroups(cfg: RouterSettings): PanelGroup[] {
|
|
19
|
+
return [
|
|
20
|
+
{
|
|
21
|
+
key: "router",
|
|
22
|
+
label: "Router",
|
|
23
|
+
tab: "Providers",
|
|
24
|
+
icon: "🌐",
|
|
25
|
+
rows: [
|
|
26
|
+
row("router.baseUrl", "Base URL", "string", cfg.baseUrl, (v) => {
|
|
27
|
+
cfg.baseUrl = String(v ?? "").trim();
|
|
28
|
+
}, {
|
|
29
|
+
description: "Yardmaster/OmniRoute OpenAI-compatible endpoint (e.g. http://host:20128/v1). ROUTER_BASE_URL env (or a trusted repo's .pi/settings.json) overrides the saved value.",
|
|
30
|
+
defaultValue: "",
|
|
31
|
+
}),
|
|
32
|
+
row("router.enableReasoning", "Thinking levels", "toggle", cfg.enableReasoning, (v) => {
|
|
33
|
+
cfg.enableReasoning = Boolean(v);
|
|
34
|
+
}, {
|
|
35
|
+
description: "Expose Pi thinking-level controls on router models. ROUTER_ENABLE_REASONING env overrides the saved value.",
|
|
36
|
+
defaultValue: true,
|
|
37
|
+
}),
|
|
38
|
+
],
|
|
39
|
+
},
|
|
40
|
+
];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Persist the working copy + apply it live: re-register the provider so its
|
|
44
|
+
* closure picks up the new values, force a catalog refresh (new endpoint or
|
|
45
|
+
* reasoning flag must take effect immediately — bypass TTL, supersede any
|
|
46
|
+
* in-flight fetch), then keep the active model valid. Notifies effective vs
|
|
47
|
+
* saved values (env/repo precedence can shadow the persisted ones) — one
|
|
48
|
+
* save path, no drift. */
|
|
49
|
+
export async function saveRouterConfig(pi: ExtensionAPI, before: RouterSettings, working: RouterSettings, ctx: ExtensionContext): Promise<void> {
|
|
50
|
+
if (working.baseUrl === before.baseUrl && working.enableReasoning === before.enableReasoning) {
|
|
51
|
+
ctx.ui.notify("No changes.", "info");
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
writeRouterSection({
|
|
55
|
+
baseUrl: working.baseUrl !== before.baseUrl ? working.baseUrl : undefined,
|
|
56
|
+
enableReasoning: working.enableReasoning !== before.enableReasoning ? working.enableReasoning : undefined,
|
|
57
|
+
});
|
|
58
|
+
registerProvider(pi, working);
|
|
59
|
+
try {
|
|
60
|
+
await maybeRefreshCatalog(ctx, { force: true });
|
|
61
|
+
} catch { /* refresh errors are surfaced by Pi elsewhere */ }
|
|
62
|
+
await refreshActiveModel(pi, ctx);
|
|
63
|
+
const effective = getSettings();
|
|
64
|
+
const overridden =
|
|
65
|
+
(working.baseUrl !== effective.baseUrl && working.baseUrl !== "") ||
|
|
66
|
+
working.enableReasoning !== effective.enableReasoning;
|
|
67
|
+
ctx.ui.notify(
|
|
68
|
+
overridden
|
|
69
|
+
? `Router: saved, but ROUTER_BASE_URL/ROUTER_ENABLE_REASONING env or repo .pi/settings.json overrides it — ` +
|
|
70
|
+
`effective: ${effective.baseUrl || "(none)"}, reasoning ${effective.enableReasoning}.`
|
|
71
|
+
: `Router config saved. Endpoint: ${effective.baseUrl || "(not configured)"} · reasoning ${effective.enableReasoning ? "ON" : "OFF"}`,
|
|
72
|
+
overridden ? "warning" : "info",
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const OWNED_KEYS = ["router.baseUrl", "router.enableReasoning"];
|
|
77
|
+
|
|
78
|
+
/** Router's ModuleConfig for the central /config panel. */
|
|
79
|
+
export function routerConfig(pi: ExtensionAPI): ModuleConfig {
|
|
80
|
+
const before = getSettings();
|
|
81
|
+
const working = structuredClone(before);
|
|
82
|
+
return {
|
|
83
|
+
groups: () => buildRouterGroups(working),
|
|
84
|
+
save: async (edited, ctx) => {
|
|
85
|
+
if (!OWNED_KEYS.some((k) => edited.has(k))) return;
|
|
86
|
+
await saveRouterConfig(pi, before, working, ctx);
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { getSettings } from "./lib/config.js";
|
|
3
|
+
import { migrateLegacyConfig } from "./lib/migrate.js";
|
|
4
|
+
import { registerProvider, maybeRefreshCatalog } from "./lib/provider.js";
|
|
5
|
+
import { refreshActiveModel } from "./lib/refresh.js";
|
|
6
|
+
import { registerCommands } from "./commands/commands.js";
|
|
7
|
+
|
|
8
|
+
export default function (pi: ExtensionAPI) {
|
|
9
|
+
// Base URL the currently-registered provider was built with — session_start
|
|
10
|
+
// compares against it to detect a trust-gated repo override (see below).
|
|
11
|
+
let registeredBaseUrl = "";
|
|
12
|
+
|
|
13
|
+
// One-shot migration from pi-9router's config file → settings.json + auth.json.
|
|
14
|
+
// Guarded: any fs failure (EACCES, lost race) must never kill provider registration.
|
|
15
|
+
try {
|
|
16
|
+
migrateLegacyConfig();
|
|
17
|
+
} catch { /* non-fatal — retried on next load */ }
|
|
18
|
+
|
|
19
|
+
// Load-time settings: env + global ONLY (no repo scope — no ctx/trust yet,
|
|
20
|
+
// and an untrusted checkout must not own the endpoint the auth key goes to).
|
|
21
|
+
const settings = getSettings();
|
|
22
|
+
registeredBaseUrl = settings.baseUrl;
|
|
23
|
+
if (settings.baseUrl) {
|
|
24
|
+
registerProvider(pi, settings);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
registerCommands(pi);
|
|
28
|
+
|
|
29
|
+
// Periodic catalog pull: TTL gate makes this a no-op while the catalog is
|
|
30
|
+
// fresh, a fetch when it ages out. Catches mid-session endpoint additions.
|
|
31
|
+
// Uses the latest session ctx (ExtensionAPI carries no modelRegistry).
|
|
32
|
+
// ponytail: 5-min tick + 15-min TTL constants, no env knob until asked.
|
|
33
|
+
let lastCtx: ExtensionContext | undefined;
|
|
34
|
+
const periodicRefresh = setInterval(() => {
|
|
35
|
+
if (!lastCtx) return;
|
|
36
|
+
void maybeRefreshCatalog(lastCtx).catch(() => { /* transient — next tick retries */ });
|
|
37
|
+
}, 5 * 60_000);
|
|
38
|
+
periodicRefresh.unref?.();
|
|
39
|
+
|
|
40
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
41
|
+
lastCtx = ctx;
|
|
42
|
+
// Now ctx exists: trust-gate the repo scope. A trusted repo may add/override
|
|
43
|
+
// the endpoint; an untrusted one is ignored (attacker-redirect guard).
|
|
44
|
+
const s = getSettings({ trustProject: ctx.isProjectTrusted?.() === true });
|
|
45
|
+
if (!s.baseUrl) {
|
|
46
|
+
ctx.ui.notify(
|
|
47
|
+
"router provider not configured — set `router.baseUrl` in ~/.pi/agent/settings.json (or ROUTER_BASE_URL), then /login router.",
|
|
48
|
+
"warning",
|
|
49
|
+
);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
// Repo scope flipped the endpoint: re-register + refresh exactly like the
|
|
53
|
+
// /config Router-tab save path so discovery/chat hit the new URL.
|
|
54
|
+
if (s.baseUrl !== registeredBaseUrl) {
|
|
55
|
+
registeredBaseUrl = s.baseUrl;
|
|
56
|
+
registerProvider(pi, s);
|
|
57
|
+
// New endpoint — bypass TTL so the first pull is immediate.
|
|
58
|
+
try { await maybeRefreshCatalog(ctx, { force: true }); } catch { /* surfaced by Pi elsewhere */ }
|
|
59
|
+
}
|
|
60
|
+
await refreshActiveModel(pi, ctx);
|
|
61
|
+
// Automatic network pull in EVERY mode — Pi only network-refreshes from
|
|
62
|
+
// the TUI /model picker (agent-session-services.js forces allowNetwork:
|
|
63
|
+
// false), so RPC/print/headless sessions would otherwise keep serving the
|
|
64
|
+
// stale models-store.json for the whole session. Fire-and-forget: never
|
|
65
|
+
// blocks session start; TTL + in-flight guard make repeats cheap.
|
|
66
|
+
void maybeRefreshCatalog(ctx)
|
|
67
|
+
.then(() => refreshActiveModel(pi, ctx))
|
|
68
|
+
.catch(() => { /* transient — timer/session end retries */ });
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// Stop the interval from refreshing with a dead session's registry after
|
|
72
|
+
// quit/reload/session replacement (review finding 4).
|
|
73
|
+
pi.on("session_shutdown", () => { lastCtx = undefined; });
|
|
74
|
+
}
|
|
75
|
+
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import type { RouterSettings } from "./config.js";
|
|
2
|
+
|
|
3
|
+
// ── Types ────────────────────────────────────────────────────────────────────
|
|
4
|
+
|
|
5
|
+
export interface RouterModelRaw {
|
|
6
|
+
id: string;
|
|
7
|
+
object?: string;
|
|
8
|
+
owned_by?: string;
|
|
9
|
+
context_length?: unknown;
|
|
10
|
+
max_output_tokens?: unknown;
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface RouterModelsResponse {
|
|
15
|
+
object: string;
|
|
16
|
+
data: RouterModelRaw[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Pi model shape with optional reasoning-level support. */
|
|
20
|
+
export type PiModel = {
|
|
21
|
+
id: string;
|
|
22
|
+
name: string;
|
|
23
|
+
reasoning: boolean;
|
|
24
|
+
thinkingLevelMap?: Record<string, string | null>;
|
|
25
|
+
input: ("text" | "image")[];
|
|
26
|
+
cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
|
|
27
|
+
contextWindow: number;
|
|
28
|
+
maxTokens: number;
|
|
29
|
+
compat?: {
|
|
30
|
+
supportsStore: boolean;
|
|
31
|
+
supportsDeveloperRole: boolean;
|
|
32
|
+
supportsReasoningEffort: boolean;
|
|
33
|
+
maxTokensField: "max_tokens";
|
|
34
|
+
thinkingFormat: "openai";
|
|
35
|
+
requiresReasoningContentOnAssistantMessages: boolean;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// ── Constants ────────────────────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
42
|
+
const FALLBACK_CONTEXT_WINDOW = 128_000;
|
|
43
|
+
const FALLBACK_MAX_TOKENS = 4_096;
|
|
44
|
+
|
|
45
|
+
// ── Public API ───────────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
export async function fetchModels(
|
|
48
|
+
config: RouterSettings,
|
|
49
|
+
signal?: AbortSignal,
|
|
50
|
+
apiKey?: string,
|
|
51
|
+
): Promise<RouterModelRaw[]> {
|
|
52
|
+
const headers: Record<string, string> = { Accept: "application/json" };
|
|
53
|
+
// RefreshModelsContext.credential (auth.json via /login) wins; env is the fallback.
|
|
54
|
+
const key = apiKey ?? process.env.ROUTER_API_KEY ?? process.env.NINE_ROUTER_API_KEY;
|
|
55
|
+
if (key) headers.Authorization = `Bearer ${key}`;
|
|
56
|
+
|
|
57
|
+
// baseUrl conventionally ends in /v1 (README + provider baseUrl for chat);
|
|
58
|
+
// never double the segment — append only when missing.
|
|
59
|
+
const url = /\/v1\/?$/.test(config.baseUrl)
|
|
60
|
+
? `${config.baseUrl.replace(/\/+$/, "")}/models`
|
|
61
|
+
: `${config.baseUrl}/v1/models`;
|
|
62
|
+
const response = await fetchWithTimeout(url, { headers, signal });
|
|
63
|
+
if (!response.ok) {
|
|
64
|
+
const text = await response.text().catch(() => "");
|
|
65
|
+
throw new Error(`router returned ${response.status}: ${text || response.statusText}`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const payload = (await response.json()) as RouterModelsResponse;
|
|
69
|
+
return payload.data ?? [];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Upstreams that reject assistant turns without reasoning_content while
|
|
73
|
+
* thinking mode is on (400 "The `reasoning_content` in the thinking mode must
|
|
74
|
+
* be passed back to the API"). Verified ONLY for the ocg/ wire — pi's native
|
|
75
|
+
* opencode-go catalog sets compat.requiresReasoningContentOnAssistantMessages
|
|
76
|
+
* on deepseek-v4*, glm-5.1 and kimi-k2.7-code. The same model ids served via
|
|
77
|
+
* zai//cmd//ds/ have no such verified contract, so the flag is scoped to the
|
|
78
|
+
* ocg/ prefix. Unprefixed opencode-go deployments would need a bare-id row. */
|
|
79
|
+
function isOcgReasoningPassback(id: string): boolean {
|
|
80
|
+
return /^ocg\/(deepseek|glm-5\.1|kimi-k2\.7-code)/i.test(id);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Detect 9router thinkingFormat from model ID, matching the same patterns
|
|
84
|
+
* used in 9router's thinkingLevels.js and capabilities.js. Each format
|
|
85
|
+
* defines a distinct set of valid thinking levels. */
|
|
86
|
+
function detectThinkingFormat(modelId: string): string {
|
|
87
|
+
const id = modelId.toLowerCase();
|
|
88
|
+
|
|
89
|
+
// Pattern overrides (first match wins, matching 9router's PATTERN_THINKING)
|
|
90
|
+
if (id.includes("gpt-5.6-sol")) return "openai-max"; // accepts max
|
|
91
|
+
if (id.includes("codex")) return "codex-pattern"; // cannot disable thinking
|
|
92
|
+
|
|
93
|
+
// Model-family detection (matching 9router's FORMAT_LEVELS keys)
|
|
94
|
+
if (id.includes("deepseek")) return "deepseek";
|
|
95
|
+
if (id.includes("claude")) {
|
|
96
|
+
// Claude 4.6+ uses adaptive thinking (none, low, medium, high, max).
|
|
97
|
+
// Parse major[.-]minor so claude-3-5/3-7 aren't misread by the minor digit,
|
|
98
|
+
// and dash forms like claude-4-6 resolve to 4.6.
|
|
99
|
+
const v = id.match(/claude[^\d]*(\d+)(?:[-.](\d+))?/);
|
|
100
|
+
const ver = v ? Number(v[1]) + (v[2] ? Number(v[2]) / 10 : 0) : 0;
|
|
101
|
+
if (ver >= 4.6 || /\b(sonnet|opus)-5\b/.test(id)) {
|
|
102
|
+
return "claude-adaptive";
|
|
103
|
+
}
|
|
104
|
+
return "claude-budget";
|
|
105
|
+
}
|
|
106
|
+
if (id.includes("gemini")) {
|
|
107
|
+
if (/gemini-3/.test(id)) return "gemini-level"; // minimal required, no disable
|
|
108
|
+
return "gemini-budget";
|
|
109
|
+
}
|
|
110
|
+
if (id.includes("kimi")) return "kimi";
|
|
111
|
+
if (id.includes("qwen") || id.includes("qwq")) return "qwen";
|
|
112
|
+
if (id.includes("glm")) return "zai";
|
|
113
|
+
if (id.includes("minimax")) return "minimax";
|
|
114
|
+
if (id.includes("hunyuan")) return "hunyuan";
|
|
115
|
+
// Anchored like the other families — a bare `includes("step")` grabbed any
|
|
116
|
+
// id containing "step" (e.g. "multistep", "stepwise") into the step map.
|
|
117
|
+
if (/step-|stepfun/.test(id)) return "step";
|
|
118
|
+
|
|
119
|
+
// Default: OpenAI format (GPT, o-series, generic models)
|
|
120
|
+
return "openai";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Return the correct thinkingLevelMap for the model's thinking format.
|
|
124
|
+
* Mirroring 9router's FORMAT_LEVELS from thinkingLevels.js:
|
|
125
|
+
* openai: none, minimal, low, medium, high, xhigh (no max)
|
|
126
|
+
* claude-adaptive: none, low, medium, high, max
|
|
127
|
+
* claude-budget: none, low, medium, high, xhigh, max
|
|
128
|
+
* deepseek: none, high, max (hiMax — low/med→high, xhigh→max)
|
|
129
|
+
* gemini-level: minimal, low, medium, high (no disable)
|
|
130
|
+
* gemini-budget: none, low, medium, high
|
|
131
|
+
* kimi: none, low, medium, high, max (levelMax)
|
|
132
|
+
* qwen/hunyuan/step: none, low, medium, high (base)
|
|
133
|
+
* zai: none, high, max (low/med→high; mirrors native zai-coding-cn/glm-5.2)
|
|
134
|
+
* minimax: none, low, medium, high, xhigh, max
|
|
135
|
+
* Levels not in the format's set map to null (disabled in Pi UI).
|
|
136
|
+
* Levels beyond the format's max cap at the highest available value
|
|
137
|
+
* (e.g. xhigh→max for deepseek, max→xhigh for openai). */
|
|
138
|
+
// Verified context windows from models.dev (cited by 9router's capabilities.js
|
|
139
|
+
// as its authoritative source). 9router's capabilities.js applies a 200k
|
|
140
|
+
// DEFAULT_CAPABILITIES floor to models without an explicit pattern match,
|
|
141
|
+
// which under-reports models with larger windows (e.g. GLM-5.2 = 1M).
|
|
142
|
+
// This table corrects known gaps client-side.
|
|
143
|
+
// Source: https://models.dev/api.json
|
|
144
|
+
// Floor constants: 9router/omniroute's DEFAULT_CAPABILITIES pair (context 200000,
|
|
145
|
+
// output 128000) for unprofiled models. Anything ≤ these on a matched-override
|
|
146
|
+
// model is the router's default-floor stamp, not real metadata — `mapModel`
|
|
147
|
+
// uses these to de-poison without inflating truthful reports above the floor.
|
|
148
|
+
// Cited: 9router capabilities.js DEFAULT_CAPABILITIES (OmniRoute is a 9router fork).
|
|
149
|
+
const DEFAULT_CONTEXT_FLOOR = 200_000;
|
|
150
|
+
const DEFAULT_MAX_FLOOR = 128_000;
|
|
151
|
+
const CONTEXT_OVERRIDES: { pattern: RegExp; contextWindow: number; maxTokens?: number }[] = [
|
|
152
|
+
// GLM-5.2/5.3 only: 1M context, 128K output (models.dev: zhipuai/glm-5.2; GLM-5.3[1m]
|
|
153
|
+
// Coding Plan route + launch coverage report the same window). Lookahead keeps
|
|
154
|
+
// future glm-5.4+ (unverified profile) off this override.
|
|
155
|
+
{ pattern: /glm-5\.[23](?!\d)/i, contextWindow: 1_000_000, maxTokens: 131_072 },
|
|
156
|
+
// DeepSeek V4: 1M context (models.dev + 9router codebuddy/nvidia overrides)
|
|
157
|
+
{ pattern: /deepseek-v[34]/i, contextWindow: 1_000_000 },
|
|
158
|
+
// GLM-5.1 / 5 / 5-turbo / 5v-turbo: ~200K context (models.dev zhipuai/zhipuai-coding-plan/opencode-go: 200000–204800),
|
|
159
|
+
// 128K output. Routes on the user's omniroute (glm-cn/glmcn/opencode-go/aug/nvidia) lack
|
|
160
|
+
// top-level metadata and fall to the 128K FALLBACK, which under-reports.
|
|
161
|
+
// Lookahead keeps glm-5.[23] out (covered above) and variant suffixes with their
|
|
162
|
+
// own distinct windows safe (live catalog reports them above the floor).
|
|
163
|
+
{ pattern: /glm-5(?:\.1|-turbo|v-turbo)?(?![0-9.v-])/i, contextWindow: 200_000, maxTokens: 131_072 },
|
|
164
|
+
// GLM-4.6 / 4.7: 200K / 128K (models.dev zhipuai/glm-4.6 = 204800; opencode-go glm-4.x = 200000).
|
|
165
|
+
// Same fallback-under-report pattern.
|
|
166
|
+
{ pattern: /glm-4\.[67](?![0-9.v-])/i, contextWindow: 200_000, maxTokens: 131_072 },
|
|
167
|
+
// Kimi K3: 1M context (models.dev moonshotai/kimi-k3 = 1048576/131072 across opencode-go/
|
|
168
|
+
// openrouter/moonshotai-cn). Specific pattern — `kimi-k2.7-code` real = 262K so a
|
|
169
|
+
// blanket override would inflate it (pi-commandcode 0.1.6 bug class).
|
|
170
|
+
{ pattern: /kimi-k3(?![0-9.v-])/i, contextWindow: 1_048_576, maxTokens: 131_072 },
|
|
171
|
+
];
|
|
172
|
+
|
|
173
|
+
function lookupContextOverride(modelId: string): { contextWindow?: number; maxTokens?: number } {
|
|
174
|
+
for (const entry of CONTEXT_OVERRIDES) {
|
|
175
|
+
if (entry.pattern.test(modelId)) {
|
|
176
|
+
return { contextWindow: entry.contextWindow, ...(entry.maxTokens ? { maxTokens: entry.maxTokens } : {}) };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return {};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Transport-verified vision routes. OmniRoute's /v1/models omits
|
|
183
|
+
// capabilities.vision on most non-openrouter connections, and the flag lies in
|
|
184
|
+
// BOTH directions — some flagged routes strip image parts outbound, some
|
|
185
|
+
// unflagged routes pass them. Entries here are proven end-to-end with
|
|
186
|
+
// extensions/scripts/probe-vision.mjs (PASS = image tokens counted / large
|
|
187
|
+
// prompt-token delta + correct image-only answer); re-probe when the router
|
|
188
|
+
// image updates. 2026-09-06 probe: gemini-3.7-flash prompt 21→1092 (Δ1071);
|
|
189
|
+
// deepseek-v4-flash-vision-exp 104→319 (Δ215). combo/glm-5.3-flash also
|
|
190
|
+
// passed (Δ1060) but is excluded — combo failover can land on a stripping
|
|
191
|
+
// member.
|
|
192
|
+
const VISION_OVERRIDES: RegExp[] = [
|
|
193
|
+
// Anchored + explicit effort-tier suffix group: -low…-max are 9router's
|
|
194
|
+
// thinking-level variants of the probed base (same upstream + executor, so
|
|
195
|
+
// same image transport). Sibling models (-preview, -lite, future versions)
|
|
196
|
+
// stay unverified — mirroring CONTEXT_OVERRIDES lookahead discipline.
|
|
197
|
+
/^(cmd|command-code)\/google\/gemini-3\.7-flash(?:-(?:low|medium|high|xhigh|max))?$/i,
|
|
198
|
+
/^(cmd|command-code)\/deepseek\/deepseek-v4-flash-vision-exp(?:-(?:low|medium|high|xhigh|max))?$/i,
|
|
199
|
+
];
|
|
200
|
+
// Inverse lie, verified 2026-09-06: openrouter entries stamp vision:true but
|
|
201
|
+
// the openrouter upstream strips image parts (glm-5.3-flash probe: Δ16, model
|
|
202
|
+
// replied NOIMAGE). Surgical list — other vision:true rows are untouched.
|
|
203
|
+
const VISION_DOWNGRADES: RegExp[] = [
|
|
204
|
+
/^openrouter\/z-ai\/glm-5\.3-flash/i,
|
|
205
|
+
];
|
|
206
|
+
|
|
207
|
+
/** Net vision for a model id given the router's metadata claim. Also applied
|
|
208
|
+
* to the persisted offline catalog (provider.ts) so stale models-store.json
|
|
209
|
+
* entries self-heal at restore. */
|
|
210
|
+
export function resolveVision(id: string, metadataVision: boolean): boolean {
|
|
211
|
+
if (VISION_DOWNGRADES.some((re) => re.test(id))) return false;
|
|
212
|
+
return metadataVision || VISION_OVERRIDES.some((re) => re.test(id));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Upstream connection slugs (OmniRoute ids are "<connection>/<model>") whose
|
|
216
|
+
// reasoning_effort schema rejects "none" and "minimal". The `cmd` slug is an alias
|
|
217
|
+
// usage-module memory maps to the same upstream.
|
|
218
|
+
const NO_DISABLE_PREFIX = /^(command-?code|cmd)[-/]/i;
|
|
219
|
+
|
|
220
|
+
const FORMAT_TO_LEVEL_MAP: Record<string, Record<string, string | null>> = {
|
|
221
|
+
"openai": { off:"none", minimal:"minimal", low:"low", medium:"medium", high:"high", xhigh:"xhigh", max:"xhigh" },
|
|
222
|
+
"openai-max": { off:"none", minimal:"minimal", low:"low", medium:"medium", high:"high", xhigh:"xhigh", max:"max" },
|
|
223
|
+
"codex-pattern": { off:null, minimal:null, low:"low", medium:"medium", high:"high", xhigh:"xhigh", max:"xhigh" },
|
|
224
|
+
"claude-adaptive": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"max", max:"max" },
|
|
225
|
+
"claude-budget": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"xhigh", max:"max" },
|
|
226
|
+
// hiMax: only none, high, max are valid levels — xhigh is not shown at all
|
|
227
|
+
// (matches opencode-go native behavior where xhigh is absent from the map)
|
|
228
|
+
"deepseek": { off:"none", minimal:null, low:null, medium:null, high:"high", xhigh:null, max:"max" },
|
|
229
|
+
"kimi": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"max", max:"max" },
|
|
230
|
+
"gemini-level": { off:null, minimal:"minimal", low:"low", medium:"medium", high:"high", xhigh:"high", max:"high" },
|
|
231
|
+
"gemini-budget": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"high", max:"high" },
|
|
232
|
+
"qwen": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"high", max:"high" },
|
|
233
|
+
"hunyuan": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"high", max:"high" },
|
|
234
|
+
"step": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"high", max:"high" },
|
|
235
|
+
// zai: mirrors native zai-coding-cn/glm-5.2 — low/medium/high all map to "high"
|
|
236
|
+
// (GLM's single thinking-on tier), max→"max"; xhigh/minimal unsupported (hidden).
|
|
237
|
+
"zai": { off:"none", minimal:null, low:"high", medium:"high", high:"high", xhigh:null, max:"max" },
|
|
238
|
+
"minimax": { off:"none", minimal:null, low:"low", medium:"medium", high:"high", xhigh:"xhigh", max:"xhigh" },
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
function getThinkingLevelMap(modelId: string): Record<string, string | null> {
|
|
242
|
+
const fmt = detectThinkingFormat(modelId);
|
|
243
|
+
const map = FORMAT_TO_LEVEL_MAP[fmt] ?? FORMAT_TO_LEVEL_MAP["openai"];
|
|
244
|
+
// Upstream connections whose reasoning_effort accepts only low|medium|high|xhigh|max
|
|
245
|
+
// (Command Code) — "none"/"minimal" would be forwarded untranslated and rejected
|
|
246
|
+
// with HTTP 400 (same bug class as pi-commandcode 0.1.4). null hides both levels
|
|
247
|
+
// in the Pi UI; the SDK omits reasoning_effort entirely when offValue is not a
|
|
248
|
+
// string (openai-completions buildParams no-level branch), so background calls
|
|
249
|
+
// (/tree branch summary, /handoff, off-level compaction) stop sending an invalid
|
|
250
|
+
// value. Mirrors 9router FORMAT_LEVELS otherwise — only these prefixes are scoped.
|
|
251
|
+
return NO_DISABLE_PREFIX.test(modelId) ? { ...map, off: null, minimal: null } : map;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function mapModel(raw: RouterModelRaw, enableReasoning: boolean): PiModel {
|
|
255
|
+
const isCombo = raw.owned_by === "combo";
|
|
256
|
+
const caps = raw.capabilities as
|
|
257
|
+
| { contextWindow?: unknown; maxOutput?: unknown; vision?: unknown }
|
|
258
|
+
| undefined;
|
|
259
|
+
// Context/max-output resolution, single-tier provenance with floor-aware
|
|
260
|
+
// override: top-level `context_length`/`max_output_tokens` are authoritative
|
|
261
|
+
// for their own field UNLESS the value sits at/below 9router's
|
|
262
|
+
// DEFAULT_CAPABILITIES floor (200000) for a model whose verified window
|
|
263
|
+
// exceeds the floor — that signature is the router's registry default stamp,
|
|
264
|
+
// not real metadata, and the curated override corrects it. Anything above
|
|
265
|
+
// the floor is never overridden (preserves e.g. openrouter/z-ai/glm-5.2:free
|
|
266
|
+
// = 256K from the inflation bug 1.1.1 fixed). See also:
|
|
267
|
+
// pi-commandcode/extensions/lib/client.ts#mapModel (same ordering; no floor
|
|
268
|
+
// rule there — commandcode reports vendor-official context_length).
|
|
269
|
+
const topLevelContext = parsePositiveInt(raw.context_length);
|
|
270
|
+
const topLevelMax = parsePositiveInt(raw.max_output_tokens);
|
|
271
|
+
// Raw presence gate (kept for back-compat with the 1.1.1 test contract): a
|
|
272
|
+
// gateway that emits a present-but-invalid value (0, "unknown") must still
|
|
273
|
+
// suppress CONTEXT_OVERRIDES so the stale override never mixes with router
|
|
274
|
+
// truth; the unparseable value itself falls through to caps/fallback below.
|
|
275
|
+
const override = lookupContextOverride(raw.id);
|
|
276
|
+
const ctxAbsent = raw.context_length === undefined || raw.context_length === null;
|
|
277
|
+
const maxAbsent = raw.max_output_tokens === undefined || raw.max_output_tokens === null;
|
|
278
|
+
const ctxUsable = !ctxAbsent && topLevelContext !== undefined;
|
|
279
|
+
const maxUsable = !maxAbsent && topLevelMax !== undefined;
|
|
280
|
+
// All-or-nothing pair-floor-poison gate. The curated override applies to the
|
|
281
|
+
// model when (a) no top-level fields are present at all (the router signals
|
|
282
|
+
// nothing — override fills both), OR (b) the top-level pair exactly matches the omniroute /
|
|
283
|
+
// 9router DEFAULT_CAPABILITIES signature (context ≤ DEFAULT_CONTEXT_FLOOR
|
|
284
|
+
// AND max ≤ DEFAULT_MAX_FLOOR, with a verified override at the floor or
|
|
285
|
+
// above for each). `>=` (not strict `>`) so models whose verified window
|
|
286
|
+
// equals the floor (e.g. glm-5.1 / glm-4.6 at 200000) still get the max
|
|
287
|
+
// correction when the router stamps the floor pair — the override is the
|
|
288
|
+
// verified truth (models.dev) and is never stale below the floor. In all
|
|
289
|
+
// other cases (any present field carries a truthful router value, or the
|
|
290
|
+
// pair is only partially the floor stamp), the override is fully bypassed
|
|
291
|
+
// (1.1.1 single-tier back-compat: presence = "router is signaling, don't
|
|
292
|
+
// override; fall through to caps"). Per-field rules would break Direction
|
|
293
|
+
// A/B; the all-or-nothing pair rule preserves the 1.1.1 invariant while
|
|
294
|
+
// correcting the user's exact case (glm-cn/glm-5.3 stamped with the
|
|
295
|
+
// 200000/128000 default-floor pair).
|
|
296
|
+
const ctxFloorPoisoned =
|
|
297
|
+
ctxUsable &&
|
|
298
|
+
(topLevelContext as number) <= DEFAULT_CONTEXT_FLOOR &&
|
|
299
|
+
override.contextWindow !== undefined &&
|
|
300
|
+
override.contextWindow >= DEFAULT_CONTEXT_FLOOR;
|
|
301
|
+
const maxFloorPoisoned =
|
|
302
|
+
maxUsable &&
|
|
303
|
+
(topLevelMax as number) <= DEFAULT_MAX_FLOOR &&
|
|
304
|
+
override.maxTokens !== undefined &&
|
|
305
|
+
override.maxTokens >= DEFAULT_MAX_FLOOR;
|
|
306
|
+
const pairFloorPoisoned = ctxFloorPoisoned && maxFloorPoisoned;
|
|
307
|
+
const useOverride = (ctxAbsent && maxAbsent) || pairFloorPoisoned;
|
|
308
|
+
const ctxFromRouter = !pairFloorPoisoned && ctxUsable ? topLevelContext : undefined;
|
|
309
|
+
const maxFromRouter = !pairFloorPoisoned && maxUsable ? topLevelMax : undefined;
|
|
310
|
+
const contextWindow =
|
|
311
|
+
ctxFromRouter ??
|
|
312
|
+
(useOverride ? override.contextWindow : undefined) ??
|
|
313
|
+
parsePositiveInt(caps?.contextWindow) ??
|
|
314
|
+
FALLBACK_CONTEXT_WINDOW;
|
|
315
|
+
const maxTokens =
|
|
316
|
+
maxFromRouter ??
|
|
317
|
+
(useOverride ? override.maxTokens : undefined) ??
|
|
318
|
+
parsePositiveInt(caps?.maxOutput) ??
|
|
319
|
+
FALLBACK_MAX_TOKENS;
|
|
320
|
+
const inputTypes: ("text" | "image")[] = resolveVision(raw.id, caps?.vision === true)
|
|
321
|
+
? ["text", "image"]
|
|
322
|
+
: ["text"];
|
|
323
|
+
|
|
324
|
+
const compat = {
|
|
325
|
+
supportsStore: false,
|
|
326
|
+
supportsDeveloperRole: false,
|
|
327
|
+
supportsReasoningEffort: enableReasoning,
|
|
328
|
+
maxTokensField: "max_tokens" as const,
|
|
329
|
+
thinkingFormat: "openai" as const,
|
|
330
|
+
requiresReasoningContentOnAssistantMessages: isOcgReasoningPassback(raw.id),
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
return {
|
|
334
|
+
id: raw.id,
|
|
335
|
+
name: isCombo ? `🔀 ${raw.id}` : raw.id,
|
|
336
|
+
reasoning: enableReasoning,
|
|
337
|
+
...(enableReasoning ? { thinkingLevelMap: getThinkingLevelMap(raw.id) } : {}),
|
|
338
|
+
input: inputTypes,
|
|
339
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
340
|
+
contextWindow,
|
|
341
|
+
maxTokens,
|
|
342
|
+
compat,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function parsePositiveInt(value: unknown): number | undefined {
|
|
347
|
+
// Accept numeric strings ("1048576") — heterogeneous OpenAI-compat gateways
|
|
348
|
+
// may serialize context_length/max_output_tokens as strings. Invalid values
|
|
349
|
+
// (NaN, <=0, non-numeric text, null) fall through to the next tier.
|
|
350
|
+
const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
|
|
351
|
+
if (typeof n === "number" && Number.isFinite(n) && n > 0) return Math.floor(n);
|
|
352
|
+
return undefined;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Re-map an already-mapped model with a new enableReasoning flag — toggling
|
|
356
|
+
* thinking levels without re-fetching. */
|
|
357
|
+
export function applyReasoning(model: PiModel, enableReasoning: boolean): PiModel {
|
|
358
|
+
return {
|
|
359
|
+
...model,
|
|
360
|
+
reasoning: enableReasoning,
|
|
361
|
+
...(enableReasoning
|
|
362
|
+
? { thinkingLevelMap: getThinkingLevelMap(model.id) }
|
|
363
|
+
: { thinkingLevelMap: undefined }),
|
|
364
|
+
compat: { ...model.compat!, supportsReasoningEffort: enableReasoning },
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// ── Internal helpers ─────────────────────────────────────────────────────────
|
|
369
|
+
|
|
370
|
+
async function fetchWithTimeout(
|
|
371
|
+
url: string,
|
|
372
|
+
init: RequestInit & { signal?: AbortSignal } = {},
|
|
373
|
+
): Promise<Response> {
|
|
374
|
+
const controller = new AbortController();
|
|
375
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
376
|
+
timer.unref?.();
|
|
377
|
+
|
|
378
|
+
// Combine caller signal with timeout signal
|
|
379
|
+
const signal = init.signal;
|
|
380
|
+
const abort = () => controller.abort();
|
|
381
|
+
if (signal?.aborted) controller.abort();
|
|
382
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
383
|
+
|
|
384
|
+
try {
|
|
385
|
+
return await fetch(url, { ...init, signal: controller.signal });
|
|
386
|
+
} finally {
|
|
387
|
+
clearTimeout(timer);
|
|
388
|
+
signal?.removeEventListener("abort", abort);
|
|
389
|
+
}
|
|
390
|
+
}
|