dsh-model-think-level 1.1.8 → 2.0.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/lib/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/constants.ts", "../src/key-refs.ts", "../src/key-index.ts", "../src/knowledge.ts", "../src/guard.ts", "../src/shared.ts", "../src/headers-core.ts", "../src/headers-fetch.ts", "../src/headers-pi-ai.ts", "../src/headers-conflict.ts", "../src/autofill.ts"],
4
- "sourcesContent": ["/**\n * Host half of dsh-model-think-level.\n *\n * One job: settings auto-adaptation. Whenever the `llm-pi-ai` section gains a\n * hand-declared model that carries no `reasoningEfforts`, fill one in from the\n * knowledge base + protocol inference (see {@link suggestEfforts}). The fill\n * is a *suggestion* written to the user layer \u2014 the user can still edit it on\n * the Models page \u2014 and a model that already declares efforts, or an explicit\n * `false`, is never touched. All interactive editing (per-model editors and\n * per-model auto-adapt) lives in the browser half, which reuses the same\n * knowledge base as a pure module.\n *\n * @module dsh-model-think-level\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\n// Type-only: pulls the webServer service merge into this program's Context.\nimport type {} from '@deepseek-ai/dsh-host-webserver'\n// Type-only: the `declare module '@deepseek-ai/cordis'` merge that types\n// `ctx.settings` as the profile-form service. `describe()` returns one\n// descriptor per active entry: an ARRAY, not the wire `{namespaces}` envelope.\n// The kernel ships no `settingsNamespace` value export (it is a private parse\n// + a compile-time SettingsNamespaceInput); the brand is a compile-time\n// concept, so a typed constant is enough.\nimport type { SettingsNamespace } from '@deepseek-ai/dsh-settings'\nimport Schema from '@deepseek-ai/schemastery'\nimport {\n AUTOFILL_CONFIG_PATH,\n DIAG_PATH,\n HEADERS_CONFIG_PATH,\n KEY_INDEX_PATH,\n PI_AI_NS,\n PLUGIN_ID,\n PROBE_PATH,\n PROVIDER_KEY_PATH,\n} from './constants.js'\nimport { isLegalKeyValue, maskKeyValue, nextKeyRef, normalizeKeyAlias } from './key-refs.js'\nimport {\n hasKeyEntry,\n keyEntriesOf,\n keyIndexFilePath,\n readKeyIndex,\n updateKeyIndex,\n withKeyAlias,\n withKeyEntry,\n withoutKeyEntry,\n} from './key-index.js'\nimport { suggestEfforts } from './knowledge.js'\nimport type { ReasoningEfforts } from './knowledge.js'\nimport { resolveGuardEffort } from './guard.js'\nimport { isRecord, looksLikeCompatRefusal, routeFactsOf } from './shared.js'\nimport { buildHeaderIndex, emptyIndex, type UserAgentIndex } from './headers-core.js'\nimport { headerOverlayInstalled, installHeaderOverlay, type OverlaySource } from './headers-fetch.js'\nimport { describePiAiHeaderState, installPiAiHeaderTransforms } from './headers-pi-ai.js'\nimport { detectHeaderConflicts, type HeaderConflictReport } from './headers-conflict.js'\n// The knowledge-base patch builder lives in its own module: the browser half\n// builds the SAME patch from its own idle-time read, so one suggestion can\n// never produce two different documents.\nimport { buildAutofillPatch, stripNewCompatKeysDeep } from './autofill.js'\n\n/** Re-exported so the package entry keeps naming the patch builder. */\nexport { buildAutofillPatch }\n\n/** Stable plugin id, matching the cordis.patch.yml row and the bundle id. */\nexport const name = PLUGIN_ID\n\n/** Hard dependencies: the loader waits for these before calling apply. */\nexport const inject = ['settings', 'llm']\n\n/** The branded settings namespace this plugin reads and fills. */\nconst PI_NS = PI_AI_NS as SettingsNamespace\n\n/**\n * Exponential backoff for the boot fill: llm-pi-ai may register its namespace\n * well after this plugin on a slow start, and registration emits no event of\n * its own \u2014 the schedule must outlast a realistically slow profile instead of\n * giving up after a few flat seconds.\n */\nconst BOOT_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000] as const\n\n/** Probe fetch budget: a gateway that cannot answer /models in 15s will not answer the composer either. */\nconst PROBE_TIMEOUT_MS = 15_000\n\n/**\n * Plugin configuration, supplied through the profile's cordis layer\n * (the row's `config:` block). Every tunable two deployments may want\n * to set differently lives here rather than as a code constant.\n */\nexport interface Config {\n /** Auto-fill undeclared pi-ai models on boot and after settings updates (default true). */\n autofill?: boolean\n /**\n * Whether the auto-fill above also fills the input-modality declaration\n * (default true). Effort auto-fill is governed by {@link autofill} alone.\n */\n modalityAutofill?: boolean\n /** Upstream fetch timeout for the raw /models probe route, in milliseconds (default 15000). */\n probeTimeoutMs?: number\n /**\n * Boot-fill retry backoff schedule in milliseconds; an empty list means\n * \"try exactly once\" (default [1000, 2000, 4000, 8000, 16000, 30000]).\n */\n bootRetryDelaysMs?: number[]\n /**\n * Rewrite effort-less calls to forced-thinking ladders into the ladder's\n * vendor default (default true). Only the request class that today becomes\n * `thinking: {type: disabled}` on a ladder that cannot switch thinking off\n * is rewritten (issue #2); everything else passes through byte-identical.\n */\n defaultGuard?: boolean\n /**\n * Take over the configured request headers at the fetch layer for every route\n * whose `headers` declare one (default true). The official adapter may merge\n * attribution headers over profile values, so the overlay reapplies the\n * profile dictionary before the request reaches the wire. The historical\n * `uaOverride` name is retained for configuration compatibility.\n */\n uaOverride?: boolean\n}\n\n/** Schemastery schema: Cordis validates the row config and fills defaults before apply(). */\nexport const Config: Schema<Config> = Schema.object({\n autofill: Schema.boolean().default(true),\n modalityAutofill: Schema.boolean().default(true),\n probeTimeoutMs: Schema.natural().min(1).default(PROBE_TIMEOUT_MS),\n bootRetryDelaysMs: Schema.array(Schema.natural().min(1)).default([...BOOT_RETRY_DELAYS_MS]),\n defaultGuard: Schema.boolean().default(true),\n uaOverride: Schema.boolean().default(true),\n})\n\ninterface CredentialsService {\n resolve(ref: string): Promise<{ value?: string } | undefined>\n /** Per-reference configuration facts \u2014 never the values themselves. */\n describe?(refs: string[]): Promise<unknown>\n /** Store one value under one reference. */\n set?(ref: string, value: string): Promise<unknown>\n /** Forget one reference's value. */\n unset?(ref: string): Promise<unknown>\n}\n\n/** One row of the key manager's list, as the browser half reads it. */\ninterface KeyEntryView {\n /** Credential reference holding the value. */\n ref: string\n /** Stored label, when the user gave one. */\n alias?: string\n /** Whether this is the reference the adapter resolves. */\n enabled: boolean\n /** Whether the store holds a value; null when the store cannot say. */\n configured: boolean | null\n /** The value in its display form, when the store let it be read. */\n masked?: string\n}\n\n/** One route's profile inside a pi-ai section value, or undefined. */\nfunction providerProfileOf(section: unknown, route: string): Record<string, unknown> | undefined {\n if (!isRecord(section)) return undefined\n const providers = section['providers']\n if (!isRecord(providers)) return undefined\n const profile = providers[route]\n return isRecord(profile) ? profile : undefined\n}\n\n/** The reference one profile names as the key in use, when it names one. */\nfunction enabledRefOf(profile: Record<string, unknown> | undefined): string | undefined {\n const ref = profile?.['apiKeyEnv']\n return typeof ref === 'string' && ref.length > 0 ? ref : undefined\n}\n\n/** Whether a host-service answer is the refusal envelope (`{ok: false}`). */\nfunction isRefusal(answer: unknown): boolean {\n return isRecord(answer) && answer['ok'] === false\n}\n\n/** The message a host-service answer carries when it refuses. */\nfunction refusalMessage(answer: unknown): string | undefined {\n if (!isRecord(answer)) return undefined\n const error = answer['error']\n if (typeof error === 'string') return error\n if (isRecord(error) && typeof error['message'] === 'string') return error['message']\n return typeof answer['message'] === 'string' ? answer['message'] : undefined\n}\n\n/**\n * The per-reference info map a `credentials.describe()` answer carries. The\n * host service is documented to answer the map itself while the Remote face\n * wraps it in the `{ok, value}` envelope; both are read here.\n */\nfunction describeRecords(answer: unknown): Record<string, unknown> | undefined {\n const candidate = isRecord(answer) && answer['value'] !== undefined ? answer['value'] : answer\n return isRecord(candidate) ? candidate : undefined\n}\n\n/** Store one value under one reference; the refusal text, or undefined. */\nasync function storeCredential(\n credentials: CredentialsService | undefined,\n ref: string,\n value: string,\n): Promise<string | undefined> {\n const set = credentials?.set\n if (credentials === undefined || typeof set !== 'function') {\n return 'this deployment cannot write the credential store'\n }\n try {\n const answer = await set.call(credentials, ref, value)\n if (!isRefusal(answer)) return undefined\n return refusalMessage(answer) ?? `the credential store refused ${ref}`\n } catch (error) {\n return error instanceof Error ? error.message : String(error)\n }\n}\n\n/** Forget one reference's value; the refusal text, or undefined. */\nasync function forgetCredential(credentials: CredentialsService | undefined, ref: string): Promise<string | undefined> {\n const unset = credentials?.unset\n if (credentials === undefined || typeof unset !== 'function') {\n return 'this deployment cannot write the credential store'\n }\n try {\n const answer = await unset.call(credentials, ref)\n if (!isRefusal(answer)) return undefined\n return refusalMessage(answer) ?? `the credential store refused to forget ${ref}`\n } catch (error) {\n return error instanceof Error ? error.message : String(error)\n }\n}\n\n/** A host dependency failed to answer a read; never report this as absence. */\nclass HostReadError extends Error {}\n\nasync function resolveCredential(credentials: CredentialsService | undefined, ref: string): Promise<string | undefined> {\n if (credentials === undefined || typeof credentials.resolve !== 'function') {\n throw new HostReadError('the credential store is unavailable')\n }\n let hit: unknown\n try {\n hit = await credentials.resolve(ref)\n } catch {\n throw new HostReadError('the credential store could not read the reference')\n }\n if (isRefusal(hit) || (hit !== undefined && !isRecord(hit))) {\n throw new HostReadError('the credential store could not read the reference')\n }\n if (hit === undefined) return undefined\n const value = (hit as Record<string, unknown>)['value']\n if (value !== undefined && typeof value !== 'string') {\n throw new HostReadError('the credential store returned an invalid value')\n }\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/** What the store will say about one reference: configured, and its masked value. */\ninterface CredentialFacts {\n configured: boolean\n masked?: string\n}\n\n/**\n * What the store will say about each reference: whether it holds a value, and \u2014\n * when the value can be read \u2014 the display form the list shows beside it.\n *\n * `describe` answers `configured` without handing the secret over, which is all\n * a badge needs; the masked preview needs the value itself, so it comes from\n * `resolve`, the same call the eye already makes. `describe` stays authoritative\n * about `configured` when both answer. A reference neither can speak about is\n * simply absent from the map.\n */\nasync function credentialFacts(\n credentials: CredentialsService | undefined,\n refs: readonly string[],\n): Promise<Record<string, CredentialFacts>> {\n const out: Record<string, CredentialFacts> = {}\n if (credentials === undefined || refs.length === 0) return out\n const describe = credentials.describe\n if (typeof describe === 'function') {\n try {\n const answer = await describe.call(credentials, [...refs])\n const records = isRefusal(answer) ? undefined : describeRecords(answer)\n for (const ref of refs) {\n const info = records?.[ref]\n if (isRecord(info) && typeof info['configured'] === 'boolean') {\n out[ref] = { configured: info['configured'] }\n }\n }\n } catch {\n // Unanswered references fall through to resolve() below.\n }\n }\n for (const ref of refs) {\n try {\n const value = await resolveCredential(credentials, ref)\n const configured = out[ref]?.configured ?? (value !== undefined && value.length > 0)\n const masked = value === undefined ? undefined : maskKeyValue(value)\n out[ref] = masked === undefined || masked.length === 0 ? { configured } : { configured, masked }\n } catch {\n // Leave it unknown: a badge is not worth failing the list over.\n }\n }\n return out\n}\n\n/**\n * Which references hold a value, as far as the store will say.\n *\n * Kept as the narrow question for callers that only badge the list; the list\n * itself asks `credentialFacts` so one read answers both.\n */\nasync function credentialConfigured(\n credentials: CredentialsService | undefined,\n refs: readonly string[],\n): Promise<Record<string, boolean>> {\n const facts = await credentialFacts(credentials, refs)\n const out: Record<string, boolean> = {}\n for (const ref of refs) {\n const configured = facts[ref]?.configured\n if (configured !== undefined) out[ref] = configured\n }\n return out\n}\n\n/** Whether a settings write was refused because the document moved under it. */\nfunction isConflictError(error: unknown): boolean {\n return isRecord(error) && error['code'] === 'SETTINGS_CONFLICT'\n}\n\n/** Read a small JSON request body; undefined when there is nothing to read. */\nasync function readJsonBody(req: IncomingMessage, limit = 8192): Promise<unknown> {\n const decoder = new TextDecoder()\n let text = ''\n try {\n for await (const chunk of req as AsyncIterable<Uint8Array | string>) {\n text += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true })\n // A provider key is short; anything larger is not a body this route serves.\n if (text.length > limit) return undefined\n }\n } catch {\n return undefined\n }\n if (text.length === 0) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n\nfunction isLoopbackHostname(hostname: string): boolean {\n return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1'\n}\n\n/** WHATWG-parse a Host/Origin authority (`host` or `host:port`). */\nfunction parseAuthority(authority: string): URL | undefined {\n try {\n // http: is a WHATWG special scheme: parsing yields a hostname or throws,\n // and normalizes casing the raw header keeps. Note the hostname of an\n // IPv6 authority KEEPS its brackets (`[::1]`) \u2014 the literal check below\n // deliberately matches on the colon.\n return new URL(`http://${authority}`)\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether a parsed hostname is an IP literal (IPv4 dotted quad, or IPv6 whose\n * brackets URL parsing already stripped). A browser fills Host from the URL it\n * believes it is talking to, so a DNS-rebound page ALWAYS carries the\n * attacker's domain here \u2014 it can never produce an IP-literal Host short of\n * the user genuinely navigating to that IP.\n */\nfunction isIpLiteralHostname(hostname: string): boolean {\n return /^\\d{1,3}(\\.\\d{1,3}){3}$/.test(hostname) || hostname.includes(':')\n}\n\n/**\n * Browser trust fence for the probe route. It mirrors the core /api fence's\n * DEFENSE (packages/client/connection/src/api-request-trust.ts) minus one\n * feature: there is no `trustedHosts` escape hatch yet.\n *\n * - Cross-site requests are refused outright; a same-origin/same-site\n * marker never ADMITS anything by itself.\n * - An attached Origin must name exactly this authority; the literal\n * `null` (sandboxed iframe, file: page) is refused.\n * - The Host fence binds every request and is the rebinding defense:\n * only loopback names and IP literals are answered. A rebound page\n * names the attacker's DOMAIN in Host even though the socket lands on\n * this server, so named hosts are always 403.\n *\n * The route proxies only endpoints the user's own settings already name, but\n * it does so with the stored credential attached \u2014 so it must not be callable\n * from elsewhere. LAN deployments serving the GUI under a DOMAIN name get 403\n * here by design (IP-literal LAN hosts keep working); see README known\n * limitations until a trustedHosts seam exists.\n */\nfunction isTrustedRequest(req: IncomingMessage): boolean {\n const host = req.headers.host\n if (typeof host !== 'string' || host.length === 0) return false\n const hostUrl = parseAuthority(host)\n if (hostUrl === undefined) return false\n const secFetchSite = req.headers['sec-fetch-site']\n if (secFetchSite === 'cross-site') return false\n const origin = req.headers.origin\n if (typeof origin === 'string') {\n if (origin === 'null') return false\n try {\n if (new URL(origin).host !== hostUrl.host) return false\n } catch {\n return false\n }\n }\n const hostname = hostUrl.hostname.toLowerCase()\n return isLoopbackHostname(hostname) || isIpLiteralHostname(hostname)\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json; charset=utf-8')\n res.end(JSON.stringify(body))\n}\n\n/**\n * A URL safe to echo in responses: a baseURL may carry userinfo\n * (https://user:pass@host), and failure messages must never repeat it.\n */\nfunction displayUrl(raw: string): string {\n try {\n const url = new URL(raw)\n url.username = ''\n url.password = ''\n return url.toString()\n } catch {\n return raw\n }\n}\n\n/**\n * Probe-listing URL, mirroring the harness's own model discovery:\n * OpenAI-compatible protocols list at\n * `{baseURL}/models`; Anthropic Messages uses its native route at\n * `{root}/v1/models?limit=1000`, where the root is the base without trailing\n * slashes and without one trailing `/v1` segment (gateway documentation\n * publishes both spellings of the same root). Only this listing URL\n * normalizes that segment.\n */\nfunction probeListingUrl(baseURL: string, api: string): string {\n const base = baseURL.replace(/\\/+$/, '')\n if (api !== 'anthropic-messages') return `${base}/models`\n const root = base.endsWith('/v1') ? base.slice(0, -3) : base\n return `${root}/v1/models?limit=${String(ANTHROPIC_MODEL_LIMIT)}`\n}\n\n/** Protocols whose model listing this module can read (the harness discovery set). */\nconst LISTABLE_PROTOCOLS: ReadonlySet<string> = new Set([\n 'anthropic-messages',\n 'openai-completions',\n 'openai-responses',\n])\n\n/** Stable API version required by Anthropic's model-listing endpoint. */\nconst ANTHROPIC_VERSION = '2023-06-01'\n\n/** Largest model-list page accepted by Anthropic's public endpoint. */\nconst ANTHROPIC_MODEL_LIMIT = 1000\n\n/**\n * Compose the raw-models probe request's headers, mirroring the discipline of\n * the harness's own model discovery: the provider\n * profile's configured request headers form the base (deployment-owned\n * credentials like `x-api-key` ride along), `accept` is always JSON, and a\n * resolved credential's Bearer overwrites a profile `authorization` \u2014 which\n * survives only when no credential resolves (a route may authenticate through\n * its configured headers alone). Anthropic Messages answers through\n * `x-api-key` plus a fixed `anthropic-version`, and its Bearer arm is never\n * used (a profile `authorization` survives untouched there, exactly as the\n * official discovery leaves it). Entries Fetch would refuse are dropped\n * rather than failing the probe. Harness attribution headers are deliberately\n * not sent \u2014 this is a same-origin diagnostic, not a harness request.\n * @param profileHeaders - the profile's raw `headers` dict (simply absent\n * on older documents).\n * @param apiKey - the resolved credential, when one resolved.\n * @param api - the profile's wire protocol.\n */\nexport function composeProbeHeaders(\n profileHeaders: unknown,\n apiKey: string | undefined,\n api: string,\n): Record<string, string> {\n const headers = new Headers()\n if (isRecord(profileHeaders)) {\n for (const [name, value] of Object.entries(profileHeaders)) {\n if (typeof value !== 'string') continue\n try {\n headers.set(name, value)\n } catch {\n // Unrepresentable as a Fetch header: skip the entry, keep probing.\n }\n }\n }\n headers.set('accept', 'application/json')\n if (api === 'anthropic-messages') {\n headers.set('anthropic-version', ANTHROPIC_VERSION)\n if (apiKey !== undefined) headers.set('x-api-key', apiKey)\n } else if (apiKey !== undefined) {\n headers.set('authorization', `Bearer ${apiKey}`)\n }\n return Object.fromEntries(headers.entries())\n}\n\n/**\n * Read a listing reply body, refusing one that outgrows the ceiling (the same\n * bound the official discovery applies). A declared length is checked first\n * so an honest server is turned away without transferring anything; the\n * accumulated total is what actually enforces the bound.\n */\nasync function readBounded(response: Response, url: string): Promise<string> {\n const declared = Number(response.headers.get('content-length') ?? Number.NaN)\n if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {\n await response.body?.cancel()\n throw new Error(`${displayUrl(url)} overshoots the ${MAX_RESPONSE_BYTES}-byte listing ceiling`)\n }\n if (response.body === null) return ''\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n total += value.byteLength\n if (total > MAX_RESPONSE_BYTES) throw new Error(`${displayUrl(url)} overshoots the ${MAX_RESPONSE_BYTES}-byte listing ceiling`)\n chunks.push(value)\n }\n } finally {\n await reader.cancel().catch(() => {\n // Cancel after a drained read, or after this function walked away from\n // an oversized one, is cleanup; the reply is already decided either way.\n })\n }\n const body = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return new TextDecoder().decode(body)\n}\n\n/** Largest listing reply the probe accepts (same bound as official discovery). */\nconst MAX_RESPONSE_BYTES = 4 * 1024 * 1024\n\n/**\n * Normalize a supported listing reply into one entry array, mirroring the\n * official parser: the standard `data` array takes precedence; the\n * enriched `models` map uses each property key as the endpoint-facing id\n * (the nested `id` only falls back for an empty key \u2014 gateways may put a\n * canonical identity there instead of the alias they accept on requests);\n * only object-valued map entries are models, and entries without a usable id\n * are dropped. Returns undefined when the listing names neither shape.\n */\nfunction listingEntries(body: unknown): Record<string, unknown>[] | undefined {\n const listing = isRecord(body) ? body : {}\n const data = listing['data']\n if (Array.isArray(data)) return data.filter(isRecord)\n const models = listing['models']\n if (isRecord(models)) {\n return Object.entries(models)\n .filter(([, raw]) => isRecord(raw))\n .map(([key, raw]) => {\n // The map key is the endpoint-facing id, but an EMPTY key falls back\n // to the entry's own id exactly as the official parser's\n // label(key, entry.id) does \u2014 gateways may put the canonical identity\n // there instead of the alias they accept on requests.\n const entry = raw as Record<string, unknown>\n const ownId = typeof entry['id'] === 'string' && entry['id'].length > 0 ? entry['id'] : ''\n return { ...entry, id: key.length > 0 ? key : ownId }\n })\n .filter(entry => typeof entry['id'] === 'string' && entry['id'].length > 0)\n }\n return undefined\n}\n\n/**\n * The llm-service surface the default-guard wraps: only the two dispatch\n * entries, typed structurally so no new dependency is needed.\n */\ninterface LlmDispatchLike {\n prepareCall(config: Record<string, unknown>, signal?: unknown): Promise<Record<string, unknown>>\n stream(options: Record<string, unknown>): AsyncIterable<unknown>\n}\n\n/**\n * Fill one call config with the vendor default when it names no effort and\n * its declared ladder cannot switch thinking off (issue #2).\n *\n * Reads the resolved pi-ai section (never the user layer -- this only reads).\n * Fails open: any unreadable shape returns the config untouched, reproducing\n * today's behavior exactly.\n */\nfunction guardCallConfig(cfg: Record<string, unknown>, section: unknown): Record<string, unknown> {\n try {\n if (typeof cfg['reasoningEffort'] !== 'undefined') return cfg\n const provider = cfg['provider']\n const modelId = cfg['model']\n if (typeof provider !== 'string' || typeof modelId !== 'string') return cfg\n if (!isRecord(section)) return cfg\n const providers = section['providers']\n if (!isRecord(providers)) return cfg\n const profile = providers[provider]\n if (!isRecord(profile)) return cfg\n const rawModels = profile['models']\n if (!Array.isArray(rawModels)) return cfg\n const row = rawModels.find((candidate): candidate is Record<string, unknown> =>\n isRecord(candidate) && candidate['id'] === modelId)\n if (row === undefined || !isRecord(row['reasoningEfforts'])) return cfg\n const profileDefault = typeof profile['reasoning'] === 'string' ? profile['reasoning'] : undefined\n const facts = routeFactsOf({ providers: { [provider]: profile } }, provider)\n const suggestion = suggestEfforts(modelId, facts)\n const level = resolveGuardEffort({\n declared: row['reasoningEfforts'] as ReasoningEfforts,\n vendorDefault: suggestion.defaultEffort,\n profileDefault,\n requested: undefined,\n })\n return level === undefined ? cfg : { ...cfg, reasoningEffort: level }\n } catch {\n return cfg\n }\n}\n\n/**\n * Apply the plugin: autofill undeclared models on boot and after every commit\n * that touches the pi-ai namespace.\n * @param ctx - host context.\n */\nexport function apply(ctx: Context, config: Config = {}): void {\n // Cordis fills schema defaults; direct calls (tests) may omit fields.\n const resolved = {\n autofill: config.autofill !== false,\n modalityAutofill: config.modalityAutofill !== false,\n probeTimeoutMs: config.probeTimeoutMs ?? PROBE_TIMEOUT_MS,\n bootRetryDelaysMs: config.bootRetryDelaysMs ?? [...BOOT_RETRY_DELAYS_MS],\n defaultGuard: config.defaultGuard !== false,\n uaOverride: config.uaOverride !== false,\n }\n\n // Module-level `inject` already guarantees the settings service; using it\n // directly (instead of a redundant inner ctx.inject) keeps one dependency\n // declaration as the single source of truth.\n const settings = ctx.settings\n\n // The guard and probe route read the pi-ai section through this cached\n // closure slot. Describing every active form on every model call is both\n // needless work and, on 0.1.7+, can publish revision invalidation; retain the\n // last resolved section until the settings document reports that it moved.\n let piSectionCache: unknown\n let piSectionCached = false\n const piSection = (required = false): unknown => {\n if (piSectionCached) return piSectionCache\n let value: unknown\n try {\n value = settings.describe().find(entry => entry.ns === PI_NS)?.value\n } catch {\n if (required) throw new HostReadError('the llm-pi-ai settings could not be read')\n // Dispatch guards remain advisory while interactive routes report errors.\n return undefined\n }\n // A missing namespace is expected during boot and must be retried.\n if (value === undefined) {\n if (required) throw new HostReadError('the llm-pi-ai settings entry is unavailable')\n return undefined\n }\n piSectionCache = value\n piSectionCached = true\n return value\n }\n ctx.on('settings/document-updated', (ns) => {\n if (ns === PI_NS) piSectionCached = false\n })\n\n if (resolved.autofill) {\n /** One autofill pass; resolves false while the pi-ai namespace is unregistered. */\n const autofillOnce = async (): Promise<boolean> => {\n const descriptor = settings.describe().find(entry => entry.ns === PI_NS)\n if (!isRecord(descriptor?.value)) return false\n // Build the patch from the RAW USER layer, never the resolved value:\n // the fill merges into the user document, and building from the\n // resolved view would materialize schema defaults / composition-base\n // models into it wholesale the moment pi-ai grows such layers for its\n // profile. A namespace whose user section holds no providers has\n // nothing this plugin may fill.\n const user = descriptor?.user\n const userProviders = isRecord(user) && isRecord(user['providers']) ? user['providers'] : undefined\n if (userProviders === undefined) return true\n const fullPatch = buildAutofillPatch(userProviders, () => true, { modalities: resolved.modalityAutofill }, descriptor?.revision ?? 0)\n if (fullPatch === undefined) return true\n // Optimistic lock: only write while the namespace has not moved past\n // this read. The fill is a background suggestion -- losing the race to a\n // user edit is fine; a later boot, or the browser half's idle pass,\n // simply fills whatever is still undeclared. Without the lock every fill\n // would bump the revision and invalidate the one the settings page read,\n // surfacing as SettingsConflictError on the next user save.\n try {\n await settings.update(PI_NS, fullPatch, descriptor?.revision)\n } catch (error) {\n const msg = String(error instanceof Error ? error.message : error)\n if (!looksLikeCompatRefusal(msg)) throw error\n const stripped = stripNewCompatKeysDeep(fullPatch)\n if (stripped === undefined) throw error\n await settings.update(PI_NS, stripped, settings.describe().find(entry => entry.ns === PI_NS)?.revision)\n }\n return true\n }\n\n /** Auto-fill must never break the settings pipeline; log and move on. */\n const logFailure = (error: unknown): void => {\n console.error(`[dsh-model-think-level] autofill failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n\n // Pending boot-retry timers, cleared with the fiber (a disposed plugin\n // must not fire into a torn-down service graph).\n const timers = new Set<ReturnType<typeof setTimeout>>()\n ctx.effect(() => () => {\n for (const timer of timers) clearTimeout(timer)\n timers.clear()\n }, 'dsh-model-think-level: boot-fill retries')\n\n // Fill once at boot for models declared before this plugin was installed,\n // backing off exponentially while llm-pi-ai has not registered yet.\n const bootFill = (attempt: number): void => {\n void autofillOnce().then((ready) => {\n if (ready || attempt >= resolved.bootRetryDelaysMs.length) return\n const timer = setTimeout(() => {\n timers.delete(timer)\n bootFill(attempt + 1)\n }, resolved.bootRetryDelaysMs[attempt])\n timers.add(timer)\n }, logFailure)\n }\n bootFill(0)\n\n // Deliberately NOT re-run on `settings/document-updated`. The boot pass is safe\n // (no settings surface is open yet); a fill the moment a commit lands is\n // not: the official Models card freezes its own revision baseline while it\n // is open, so a background write there makes the user's very next save in\n // that card fail with `settings/conflict` and their edit reads as lost\n // (issue #7). The browser half carries the running complement instead: it\n // builds this SAME patch and writes it on its idle pass, once no card is\n // open. A headless composition has no editing surface to break and no\n // browser half either -- boot covers it.\n }\n\n // Default-guard (issue #2): wrap the llm dispatch entries so effort-less\n // calls to forced-thinking ladders ride the ladder's vendor default instead\n // of the wire's off-equivalent. Deferred inject: the wrap lands whenever\n // the llm service registers, and ctx.effect restores the originals on\n // dispose (disable/HMR leaves no trace).\n if (resolved.defaultGuard) {\n ctx.inject(['llm'], (llmCtx) => {\n const llm = (llmCtx as unknown as { llm?: unknown }).llm as LlmDispatchLike | undefined\n if (llm === undefined || typeof llm.prepareCall !== 'function' || typeof llm.stream !== 'function') return\n // Unbound originals: restore assigns back the exact references, and\n // dispatch keeps the service as receiver through .call.\n const origPrepare = llm.prepareCall\n const origStream = llm.stream\n let disposed = false\n const prepare: LlmDispatchLike['prepareCall'] = (callConfig, signal) =>\n origPrepare.call(llm, disposed ? callConfig : guardCallConfig(callConfig, piSection()), signal)\n const stream: LlmDispatchLike['stream'] = (options) =>\n origStream.call(llm, disposed ? options : guardCallConfig(options, piSection()))\n llm.prepareCall = prepare\n llm.stream = stream\n ctx.effect(() => () => {\n disposed = true\n if (llm.prepareCall === prepare) llm.prepareCall = origPrepare\n if (llm.stream === stream) llm.stream = origStream\n }, 'dsh-model-think-level: default-guard')\n })\n }\n\n // Request-header takeover (issue #12): the official adapter can merge\n // attribution headers over the profile's own dictionary, so configured\n // values may be lost before the request reaches the wire. The plugin keeps\n // the fetch overlay as a compatibility fallback and also uses pi-ai's\n // request-level transform, which runs after auth/default headers are merged.\n // This mirrors the request-scoped header handling used by PI-Desktop and\n // covers SDK transports that do not call the current global fetch function.\n //\n // The index is keyed by the endpoint's ORIGIN and rebuilt from the live\n // settings section, so a route added, edited, or removed on the Models page\n // reaches the next request with no reload. `uaOverride: false` empties the\n // index instead of skipping the install: both seams stay installed and\n // simply stop matching anything.\n /** Live index the overlay reads; never undefined once apply has run. */\n const overlaySource: OverlaySource = { current: emptyIndex() }\n const headerRetryTimers = new Set<ReturnType<typeof setTimeout>>()\n let headerRetryAttempt = 0\n const stopHeaderRetries = (): void => {\n for (const timer of headerRetryTimers) clearTimeout(timer)\n headerRetryTimers.clear()\n headerRetryAttempt = 0\n }\n const scheduleHeaderRefresh = (refresh: () => void): void => {\n // A settings event may arrive while a retry is already pending. Keep one\n // timer per activation so repeated document notifications cannot accelerate\n // or multiply the boot retry sequence.\n if (headerRetryTimers.size > 0 || headerRetryAttempt >= resolved.bootRetryDelaysMs.length) return\n const delay = resolved.bootRetryDelaysMs[headerRetryAttempt]\n headerRetryAttempt += 1\n const timer = setTimeout(() => {\n headerRetryTimers.delete(timer)\n refresh()\n }, delay)\n headerRetryTimers.add(timer)\n }\n const refreshHeaders = (): void => {\n if (!resolved.uaOverride) {\n overlaySource.current = emptyIndex()\n stopHeaderRetries()\n return\n }\n const section = piSection()\n if (section === undefined) {\n // llm-pi-ai can register its settings namespace after this plugin. The\n // model probe has an independent direct-header path, but chat needs this\n // index ready before the adapter's first stream reaches fetch().\n overlaySource.current = emptyIndex()\n scheduleHeaderRefresh(refreshHeaders)\n return\n }\n stopHeaderRetries()\n const providers = isRecord(section) && isRecord(section['providers'])\n ? (section['providers'] as Record<string, Record<string, unknown>>)\n : {}\n overlaySource.current = buildHeaderIndex(providers)\n }\n refreshHeaders()\n ctx.effect(() => () => stopHeaderRetries(), 'dsh-model-think-level: header retries')\n ctx.on('settings/document-updated', (ns) => {\n if (ns === PI_NS) refreshHeaders()\n })\n const overlay = installHeaderOverlay(overlaySource)\n ctx.effect(() => () => { overlay.dispose() }, 'dsh-model-think-level: fetch header overlay')\n\n // `?diag=1` on the probe route reports this without touching the wire, so\n // the request-header takeover is observable from the running host.\n let headerBridgeState: () => unknown = () => ({ stage: 'not-installed' })\n const installPiAiBridge = (llm: unknown): void => {\n const transforms = installPiAiHeaderTransforms(llm, overlaySource)\n transforms.refresh()\n headerBridgeState = () => describePiAiHeaderState(llm, overlaySource)\n ctx.on('llm/adapters-updated', () => transforms.refresh())\n ctx.effect(() => () => transforms.dispose(), 'dsh-model-think-level: pi-ai request headers')\n }\n const availableLlm = (ctx as unknown as { llm?: unknown }).llm\n if (availableLlm === undefined) {\n // Direct callers and older hosts may omit llm from the module-level inject;\n // keep the deferred path as a compatibility fallback for those contexts.\n ctx.inject(['llm'], (llmCtx) => {\n const llm = (llmCtx as unknown as { llm?: unknown }).llm\n if (llm !== undefined) installPiAiBridge(llm)\n })\n } else {\n installPiAiBridge(availableLlm)\n }\n\n // Read once: what sits on disk changes only when the user installs or patches\n // something, and a restart is the honest moment to re-read it.\n const environmentConflicts: HeaderConflictReport = detectHeaderConflicts()\n\n // Same-origin probe route: the browser half's Auto-adapt asks the endpoint's\n // RAW /models listing through here, because the sanctioned llm wire call\n // strips reasoning signals host-side. The credential resolves server-side\n // and never echoes back; only routes the user's own settings name are\n // reachable, and the trust fence rejects cross-site callers.\n ctx.inject(['webServer'], (webServerCtx) => {\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: PROBE_PATH,\n handler: async (req, res) => {\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const url = new URL(req.url ?? '/', 'http://x')\n // Read-only diagnostics: makes the request-header takeover\n // observable in the running host (which adapter is patched).\n if (url.searchParams.get('diag') === '1') {\n sendJson(res, 200, {\n ok: true,\n bridge: headerBridgeState(),\n overlay: {\n routes: overlaySource.current.routes.length,\n overrides: overlaySource.current.overrides.length,\n },\n })\n return\n }\n const route = url.searchParams.get('route') ?? ''\n let section: unknown\n try {\n section = piSection(true)\n } catch {\n sendJson(res, 502, { ok: false, error: 'the llm-pi-ai settings could not be read' })\n return\n }\n const profile = isRecord(section) && isRecord(section['providers'])\n ? section['providers'][route]\n : undefined\n if (!isRecord(profile)) {\n sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route \"${route}\"` })\n return\n }\n const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'] : ''\n if (baseURL.length === 0) {\n sendJson(res, 400, { ok: false, error: `provider route \"${route}\" has no baseURL` })\n return\n }\n // The profile's wire protocol selects the listing route and the\n // credential arm, exactly as the official discovery decides them:\n // only the protocols whose listing this mirror can read are\n // interrogated; everything else reports that it cannot.\n const api = typeof profile['api'] === 'string' ? profile['api'] : ''\n if (api.length === 0) {\n sendJson(res, 400, {\n ok: false,\n error: `provider route \"${route}\" names no API protocol to interrogate`,\n })\n return\n }\n if (!LISTABLE_PROTOCOLS.has(api)) {\n sendJson(res, 400, {\n ok: false,\n error: `protocol \"${api}\" cannot be interrogated; enter this provider's models by hand`,\n })\n return\n }\n const apiKeyEnv = typeof profile['apiKeyEnv'] === 'string' ? profile['apiKeyEnv'] : undefined\n const listingURL = probeListingUrl(baseURL, api)\n let apiKey: string | undefined\n if (apiKeyEnv !== undefined) {\n try {\n apiKey = await resolveCredential(ctx.get('credentials') as CredentialsService | undefined, apiKeyEnv)\n } catch {\n sendJson(res, 502, { ok: false, error: 'the credential store could not read the reference' })\n return\n }\n }\n try {\n const upstream = await fetch(listingURL, {\n method: 'GET',\n // Header composition mirrors the harness's own model discovery:\n // the profile's configured request headers ride\n // along, so a deployment that authenticates through a custom\n // header probes here exactly as it lists officially \u2014 and an\n // Anthropic endpoint answers through x-api-key + a fixed\n // anthropic-version instead of a Bearer.\n headers: composeProbeHeaders(profile['headers'], apiKey, api),\n // A probe carries the user's stored credential, so it must\n // reach exactly the authority the profile names: Fetch's\n // default would FOLLOW a cross-origin redirect, and the\n // headers composed here (`x-api-key`, a profile's own auth\n // header) are not stripped on that hop the way `authorization`\n // is. Official discovery keeps the default; this route is\n // stricter on purpose, and the cost is bounded \u2014 a gateway\n // that lists only behind a redirect yields no endpoint\n // evidence, so Auto-adapt falls back to the knowledge base /\n // protocol inference, the path every unanswerable endpoint\n // takes.\n redirect: 'error',\n signal: AbortSignal.timeout(resolved.probeTimeoutMs),\n })\n if (!upstream.ok) {\n const hint = upstream.status === 401 || upstream.status === 403 ? '; check the API key' : ''\n sendJson(res, 502, { ok: false, error: `${displayUrl(listingURL)} answered ${upstream.status}${hint}` })\n return\n }\n const text = await readBounded(upstream, listingURL)\n let body: unknown\n try {\n body = JSON.parse(text) as unknown\n } catch {\n sendJson(res, 502, { ok: false, error: `${displayUrl(listingURL)} answered with a malformed JSON body` })\n return\n }\n // The official parser accepts the standard `data` array and the\n // enriched `models` map; entries are passed through verbatim so\n // the browser half sees the raw capability signals the sanctioned\n // wire call strips.\n const entries = listingEntries(body)\n if (entries === undefined) {\n sendJson(res, 502, {\n ok: false,\n error: `${displayUrl(listingURL)} model listing has neither a \"data\" array nor a \"models\" object`,\n })\n return\n }\n sendJson(res, 200, { ok: true, url: displayUrl(listingURL), data: entries })\n } catch (error) {\n sendJson(res, 502, {\n ok: false,\n error: `could not reach ${displayUrl(listingURL)}: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n },\n }),\n 'dsh-model-think-level: raw-models probe route',\n )\n\n // Read-only diagnostics for the request-header takeover. A path of its own\n // (rather than a flag on the probe route) so a reloaded plugin can answer\n // even while an older instance still owns the probe path.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: DIAG_PATH,\n handler: (req, res) => {\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n sendJson(res, 200, {\n ok: true,\n uaOverride: resolved.uaOverride,\n bridge: headerBridgeState(),\n overlay: {\n routes: overlaySource.current.routes.length,\n overrides: overlaySource.current.overrides.length,\n },\n })\n },\n }),\n 'dsh-model-think-level: header diagnostics route',\n )\n\n // Stored-credential route: the API-key field's eye calls it when the user\n // asks to see a key that is already saved. Every other route here keeps the\n // value host-side; this one hands it to the page on purpose, because the\n // official field is write-only by design \u2014 the settings document carries\n // only the profile's `apiKeyEnv` reference \u2014 so the affordance would\n // otherwise be a mask toggle with nothing behind it. The same trust fence\n // as the probe gates it, the value is never logged, and every answer is\n // `no-store` so neither the key nor the refusals (which name the route's\n // reference) can sit in a cache. The browser half asks only on a click, and\n // only for a card that names a route.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: PROVIDER_KEY_PATH,\n handler: async (req, res) => {\n // Nothing this route answers may sit in a cache: not the key, and\n // not the refusals that name the route's credential reference.\n res.setHeader('cache-control', 'no-store')\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const url = new URL(req.url ?? '/', 'http://x')\n const route = url.searchParams.get('route') ?? ''\n let section: unknown\n try {\n section = piSection(true)\n } catch {\n sendJson(res, 502, { ok: false, error: 'the llm-pi-ai settings could not be read' })\n return\n }\n const profile = isRecord(section) && isRecord(section['providers'])\n ? section['providers'][route]\n : undefined\n if (!isRecord(profile)) {\n sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route \"${route}\"` })\n return\n }\n const apiKeyEnv = typeof profile['apiKeyEnv'] === 'string' ? profile['apiKeyEnv'] : undefined\n // A key-manager row names its own reference; the field's own eye\n // names none and means \"the key this provider is using\". A named\n // one is served only when the route's index lists it, so this route\n // can never become a resolver for arbitrary reference names.\n const named = url.searchParams.get('ref') ?? ''\n let ref: string | undefined\n try {\n ref = named.length > 0\n ? (named === apiKeyEnv || hasKeyEntry(readKeyIndex(keyIndexFilePath()), route, named) ? named : undefined)\n : apiKeyEnv\n } catch {\n sendJson(res, 500, { ok: false, error: 'the key index could not be read' })\n return\n }\n if (ref === undefined) {\n sendJson(res, 404, {\n ok: false,\n error: named.length > 0\n ? `provider route \"${route}\" lists no key \"${named}\"`\n : `provider route \"${route}\" stores no credential reference`,\n })\n return\n }\n let value: string | undefined\n try {\n value = await resolveCredential(ctx.get('credentials') as CredentialsService | undefined, ref)\n } catch {\n sendJson(res, 502, { ok: false, error: 'the credential store could not read the reference' })\n return\n }\n if (value === undefined) {\n sendJson(res, 404, { ok: false, error: `no credential is configured for ${ref}` })\n return\n }\n sendJson(res, 200, { ok: true, key: value })\n },\n }),\n 'dsh-model-think-level: provider-key route',\n )\n\n // The API-key manager: one provider's list of keys, and which one is in use.\n //\n // Both halves of that list are host-side already \u2014 the values belong to the\n // harness credential store, and the reference the adapter actually resolves\n // is a field of the pi-ai profile \u2014 so this route owns the reads AND the\n // writes and the browser half only ever handles references, labels and\n // booleans. That is the same surface the official page works with, and it\n // needs no new Remote face to get it.\n let keyMutationTail = Promise.resolve()\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: KEY_INDEX_PATH,\n handler: async (req, res) => {\n res.setHeader('cache-control', 'no-store')\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET' && req.method !== 'POST') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const url = new URL(req.url ?? '/', 'http://x')\n const route = url.searchParams.get('route') ?? ''\n let releaseMutation: (() => void) | undefined\n try {\n if (req.method === 'POST') {\n // Routes can share credential refs, including normalized names.\n // Keep each write/rollback sequence together; reads never queue.\n const previous = keyMutationTail\n keyMutationTail = new Promise<void>(resolve => { releaseMutation = resolve })\n await previous\n }\n // Read the entry fresh rather than through the cached section: this\n // route writes to it, and an answer built from a pre-write snapshot\n // would show the user the state they just changed away from.\n const entryOf = (): { value: unknown; revision: number } | undefined => {\n try {\n const found = settings.describe().find(candidate => candidate.ns === PI_NS)\n if (found === undefined) throw new HostReadError('the llm-pi-ai settings entry is unavailable')\n return { value: found.value, revision: found.revision }\n } catch {\n throw new HostReadError('the llm-pi-ai settings could not be read')\n }\n }\n if (route.length === 0 || providerProfileOf(entryOf()?.value, route) === undefined) {\n sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route \"${route}\"` })\n return\n }\n const credentials = ctx.get('credentials') as CredentialsService | undefined\n const indexFile = keyIndexFilePath()\n\n /** The reference the profile names right now, read fresh. */\n const enabledNow = (): string | undefined => enabledRefOf(providerProfileOf(entryOf()?.value, route))\n\n /**\n * Hand the \"in use\" seat to one reference; undefined clears it. The\n * seat IS the profile's `apiKeyEnv`, so nothing else has to know\n * which key is active \u2014 every consumer of the profile, in the GUI or\n * not, resolves exactly the key the user enabled.\n * @param ref - reference to enable, or undefined to name none.\n * @returns The refusal text, or undefined when the write landed.\n */\n const setEnabledKey = async (ref: string | undefined): Promise<string | undefined> => {\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const entry = entryOf()\n if (entry === undefined) return 'the llm-pi-ai settings entry is unavailable'\n try {\n await settings.mutate(\n PI_NS,\n ref === undefined\n ? [{ op: 'unset', path: ['providers', route, 'apiKeyEnv'] }]\n : [{ op: 'set', path: ['providers', route, 'apiKeyEnv'], value: ref }],\n entry.revision,\n )\n return undefined\n } catch (error) {\n // Another writer (the official card's Save, another tab, the\n // autofill pass) moved the document between this read and\n // this write: re-read once and fence on the new revision.\n if (attempt === 0 && isConflictError(error)) continue\n return error instanceof Error ? error.message : String(error)\n }\n }\n return 'the settings document kept changing; try again'\n }\n\n /** The whole list, as the browser half renders it. */\n const payload = async (): Promise<unknown> => {\n const enabledRef = enabledNow()\n const listed = keyEntriesOf(readKeyIndex(indexFile), route)\n const refs = listed.map(entry => entry.ref)\n // The key in use is always on the list, even when it was written\n // by the official page or by hand and this plugin has never seen\n // it: the panel must be able to show and act on what is active.\n if (enabledRef !== undefined && !refs.includes(enabledRef)) refs.push(enabledRef)\n const facts = await credentialFacts(credentials, refs)\n const entries: KeyEntryView[] = refs.map(ref => {\n const fact = facts[ref]\n const view: KeyEntryView = {\n ref,\n enabled: ref === enabledRef,\n configured: fact?.configured ?? null,\n }\n if (fact?.masked !== undefined) view.masked = fact.masked\n const stored = listed.find(candidate => candidate.ref === ref)\n if (stored?.alias !== undefined) view.alias = stored.alias\n return view\n })\n return { ok: true, route, enabledRef: enabledRef ?? null, entries }\n }\n\n if (req.method === 'GET') {\n sendJson(res, 200, await payload())\n return\n }\n\n const body = await readJsonBody(req)\n const op = isRecord(body) && typeof body['op'] === 'string' ? body['op'] : ''\n const ref = isRecord(body) && typeof body['ref'] === 'string' ? body['ref'] : undefined\n const alias = isRecord(body) ? normalizeKeyAlias(body['alias']) : undefined\n const value = isRecord(body) && typeof body['value'] === 'string' ? body['value'] : undefined\n // Validate each operation before its first write and compensate\n // later failures across the independent settings and key stores.\n const refuse = (error: string): void => sendJson(res, 400, { ok: false, error })\n\n if (op === 'add') {\n if (!isLegalKeyValue(value)) {\n refuse('a key must be printable ASCII without spaces')\n return\n }\n const taken = keyEntriesOf(readKeyIndex(indexFile), route).map(candidate => candidate.ref)\n // The reference in use need not be listed \u2014 the official card\n // and a hand-edited profile both write one this plugin has never\n // seen \u2014 and minting it again would overwrite the very key the\n // provider is running on.\n const active = enabledNow()\n if (active !== undefined && !taken.includes(active)) taken.push(active)\n let created = nextKeyRef(route, taken)\n // Metadata cannot enumerate the credential store. Check each\n // candidate against both read faces before writing a new value.\n for (;;) {\n const facts = await credentialFacts(credentials, [created])\n const configured = facts[created]?.configured\n if (configured === undefined) throw new HostReadError('the credential store could not confirm a free reference')\n if (!configured && await resolveCredential(credentials, created) === undefined) break\n taken.push(created)\n created = nextKeyRef(route, taken)\n }\n // The value goes into the store first: a reference the index\n // lists but the store cannot hold would render as a key the\n // user can never reveal, enable or remove.\n const refused = await storeCredential(credentials, created, value)\n if (refused !== undefined) {\n refuse(refused)\n return\n }\n let indexed = false\n try {\n updateKeyIndex(document => withKeyEntry(document, route, created, alias), indexFile)\n indexed = true\n // Adding the first key also configures the route.\n if (enabledNow() === undefined) {\n const failed = await setEnabledKey(created)\n if (failed !== undefined) throw new Error(failed)\n }\n } catch (error) {\n const rollback = await forgetCredential(credentials, created)\n // Keep metadata if cleanup failed, so the retained secret can\n // still be found and removed by a later manager request.\n if (rollback === undefined && indexed) {\n updateKeyIndex(document => withoutKeyEntry(document, route, created), indexFile)\n }\n if (rollback !== undefined) {\n throw new Error(`${error instanceof Error ? error.message : String(error)}; credential rollback failed for ${created}: ${rollback}`)\n }\n throw error\n }\n } else if (op === 'enable') {\n const listed = readKeyIndex(indexFile)\n if (ref === undefined || !hasKeyEntry(listed, route, ref)) {\n refuse('that key is not listed for this provider')\n return\n }\n // Moving the seat must not take the key it leaves off the list:\n // that key was a row a moment ago, and unlisted it would fall out\n // of reach \u2014 and let a later add mint its name again, over the\n // value still sitting in the store.\n const previous = enabledNow()\n if (previous !== undefined && previous !== ref && !hasKeyEntry(listed, route, previous)) {\n const leaving: string = previous\n updateKeyIndex(\n document =>\n hasKeyEntry(document, route, leaving)\n ? document\n : withKeyEntry(document, route, leaving, undefined),\n indexFile,\n )\n }\n const failed = await setEnabledKey(ref)\n if (failed !== undefined) {\n refuse(failed)\n return\n }\n } else if (op === 'rename') {\n // The key the provider is RUNNING on takes a label too: that\n // reference is usually the one the official card wrote, which\n // this plugin has never listed. Writing it here is what puts it\n // on the list, so every later write matches an entry.\n const known =\n ref !== undefined &&\n (hasKeyEntry(readKeyIndex(indexFile), route, ref) || ref === enabledNow())\n if (ref === undefined || !known) {\n refuse('that key is not listed for this provider')\n return\n }\n const target = ref\n updateKeyIndex(\n document =>\n hasKeyEntry(document, route, target)\n ? withKeyAlias(document, route, target, alias)\n : withKeyEntry(document, route, target, alias),\n indexFile,\n )\n } else if (op === 'value') {\n const known =\n ref !== undefined &&\n (hasKeyEntry(readKeyIndex(indexFile), route, ref) || ref === enabledNow())\n if (ref === undefined || !known) {\n refuse('that key is not listed for this provider')\n return\n }\n if (!isLegalKeyValue(value)) {\n refuse('a key must be printable ASCII without spaces')\n return\n }\n // Only the secret moves: the reference keeps its name, its alias\n // and its seat. Removing and re-adding would mint a new ref, so\n // the profile would name a key the store no longer holds and the\n // row would lose everything but its value.\n const refused = await storeCredential(credentials, ref, value)\n if (refused !== undefined) {\n refuse(refused)\n return\n }\n } else if (op === 'remove') {\n const document = readKeyIndex(indexFile)\n if (ref === undefined || (!hasKeyEntry(document, route, ref) && ref !== enabledNow())) {\n refuse('that key is not listed for this provider')\n return\n }\n const configured = (await credentialConfigured(credentials, [ref]))[ref]\n if (configured === undefined) throw new HostReadError('the credential store could not read the reference')\n const wasEnabled = ref === enabledNow()\n const remaining = keyEntriesOf(document, route)\n .map(candidate => candidate.ref)\n .filter(candidate => candidate !== ref)\n const replacement = remaining[0]\n if (wasEnabled) {\n // Move the profile before forgetting its credential.\n const failed = await setEnabledKey(replacement)\n if (failed !== undefined) {\n refuse(failed)\n return\n }\n }\n try {\n // Commit metadata before deleting the secret: a disk failure\n // must leave the original credential available for rollback.\n updateKeyIndex(document2 => withoutKeyEntry(document2, route, ref), indexFile)\n if (configured) {\n const refused = await forgetCredential(credentials, ref)\n if (refused !== undefined) throw new Error(refused)\n }\n } catch (error) {\n const failures: string[] = []\n try {\n updateKeyIndex(current => {\n const providers = { ...current.providers }\n const original = document.providers[route]\n if (original === undefined) delete providers[route]\n else providers[route] = original\n return { version: 1, providers }\n }, indexFile)\n } catch {\n failures.push('key index rollback failed')\n }\n // Do not undo a later profile change by another writer.\n if (wasEnabled && enabledNow() === replacement) {\n const failed = await setEnabledKey(ref)\n if (failed !== undefined) failures.push(`profile rollback failed: ${failed}`)\n }\n throw new Error([error instanceof Error ? error.message : String(error), ...failures].join('; '))\n }\n } else {\n refuse(`unknown key operation \"${op}\"`)\n return\n }\n sendJson(res, 200, await payload())\n } catch (error) {\n sendJson(res, error instanceof HostReadError ? 502 : 500, {\n ok: false, error: error instanceof Error ? error.message : String(error),\n })\n } finally {\n releaseMutation?.()\n }\n },\n }),\n 'dsh-model-think-level: key index route',\n )\n\n // The autofill switches, for the browser half that runs the running\n // complement. Read-only and same-origin only, like the probe above: a\n // `dsh.client` declaration carries no plugin config, so without this route\n // a deployment configured `autofill: false` would still be written to from\n // the settings page.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: AUTOFILL_CONFIG_PATH,\n handler: async (req, res) => {\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n sendJson(res, 200, {\n ok: true,\n data: { autofill: resolved.autofill, modalityAutofill: resolved.modalityAutofill },\n })\n },\n }),\n 'dsh-model-think-level: autofill config route',\n )\n\n // The request-header overlay's status, for the browser half. Same-origin\n // and read-only, like the other two routes: the takeover lives host-side, so\n // the page needs this to say which routes it is changing and to warn about\n // another plugin rewriting the same surface.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: HEADERS_CONFIG_PATH,\n handler: async (req, res) => {\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const index = overlaySource.current\n sendJson(res, 200, {\n ok: true,\n data: {\n /** Whether the fetch-layer takeover is enabled in this deployment. */\n enabled: resolved.uaOverride,\n /** Whether this plugin's wrapper currently owns the global fetch. */\n installed: headerOverlayInstalled(),\n /** Routes whose configured request headers are sent, by origin. */\n overrides: index.overrides.map(entry => ({\n origin: entry.origin,\n route: entry.route,\n headers: entry.headers,\n ...(entry.userAgent === undefined ? {} : { userAgent: entry.userAgent }),\n })),\n /** Same-origin routes with different User-Agent values. */\n conflicts: index.conflicts,\n /** Same-origin differences for any configured request header. */\n headerConflicts: index.headerConflicts,\n /** What was found of the plugins that rewrite the same surface. */\n environment: environmentConflicts,\n },\n })\n },\n }),\n 'dsh-model-think-level: headers config route',\n )\n })\n}\n", "/**\n * Plugin-wide constants shared by the host and browser halves.\n *\n * @module dsh-model-think-level/constants\n */\n\n/** Stable plugin id, matching the cordis.patch.yml row and the bundle id. */\nexport const PLUGIN_ID = 'dsh-model-think-level'\n\n/** Same-origin host route that proxies a provider's RAW /models listing. */\nexport const PROBE_PATH = '/dsh-model-think-level/raw-models'\n/** Read-only diagnostics for the request-header takeover. */\nexport const DIAG_PATH = '/dsh-model-think-level/header-bridge'\n\n/**\n * Same-origin host route that resolves one provider profile's stored\n * credential, so the API-key field's eye can show a SAVED key.\n *\n * The harness keeps provider keys write-only on purpose: the settings document\n * carries only the profile's `apiKeyEnv` reference, and the credential service\n * reports `{ configured, source, writable }` through `describe()` \u2014 never the\n * value. Only the host can read it (`credentials.resolve()`), and it does so\n * for the request adapters; the browser normally never sees a stored key at\n * all. This route is the plugin's deliberate exception: an explicit,\n * user-initiated, same-fence read that answers with the value and is never\n * cached, so the eye can put it back into the official field.\n */\nexport const PROVIDER_KEY_PATH = '/dsh-model-think-level/provider-key'\n\n/**\n * Same-origin host route that owns a provider's list of API keys: their\n * references, their labels, and which one is in use.\n *\n * The harness has no notion of \"several keys for one provider\": a profile names\n * exactly one reference (`apiKeyEnv`) and a credential store holds exactly one\n * value per reference, with no enumeration and no label. Both facts are\n * deliberate \u2014 a configuration surface learns which references exist from its\n * settings schema \u2014 so a list of keys can only be plugin-owned state. It lives\n * in the harness home (`<DSH_HOME>/dsh-model-think-level/key-index.json`) rather\n * than in the pi-ai profile, so the official add-provider card, which writes the\n * WHOLE profile at `providers.<route>`, cannot drop it.\n *\n * The route both reads and writes: the values themselves still go to the\n * credential store through the host's own `credentials` service, so the browser\n * never needs a new Remote face.\n */\nexport const KEY_INDEX_PATH = '/dsh-model-think-level/key-index'\n\n/**\n * Same-origin host route that reports this plugin's autofill switches. The\n * browser half runs the running auto-fill complement, and a `dsh.client`\n * declaration carries no plugin config, so the two switches have to be read\n * from the host that owns the cordis row; without it a deployment that turned\n * `autofill: false` would still be written to from the page.\n */\nexport const AUTOFILL_CONFIG_PATH = '/dsh-model-think-level/autofill-config'\n\n/**\n * Same-origin host route reporting the request-header overlay (issue #12): the\n * routes whose `user-agent` the plugin is overriding, and what it found of the\n * plugins that rewrite the same surface. The browser half renders the\n * coexistence warning from here \u2014 the takeover lives host-side, so the page\n * cannot observe it on its own.\n */\nexport const HEADERS_CONFIG_PATH = '/dsh-model-think-level/headers-config'\n\n/** The settings namespace this plugin edits: pi-ai custom provider routes. */\nexport const PI_AI_NS = 'llm-pi-ai'\n\n/**\n * Model-level marker written when the user deliberately unsets the\n * declaration (\"back to inheritance\"). Schemastery passes unknown model keys\n * through, so the marker survives official-page saves and restarts \u2014 which is\n * the point: auto-fill must respect the absence as a decision, not as a gap\n * to fill.\n */\nexport const UNSET_MARKER = 'reasoningEffortsUnset'\n\n/**\n * Model-level marker for a deliberately unset input-modality declaration,\n * mirroring {@link UNSET_MARKER}: auto-fill must respect the absence of\n * `input` as a decision (the route default applies), not as a gap to fill.\n */\nexport const INPUT_UNSET_MARKER = 'inputUnset'\n\n/**\n * Model-level provenance marker written beside every ladder the HOST autofill\n * fills from the knowledge base, carrying the settings revision the fill read.\n *\n * It exists because the plugin's auto-fill and the user's staged declaration\n * race on the SAME row: whichever half runs the fill writes the knowledge base\n * suggestion, while the staged-declaration flush compares the document against\n * its own suggestion. By the time the flush looks, the suggestion may already\n * be stored -- and byte equality alone cannot tell \"the plugin wrote this\" from\n * \"the user declared this\", so a staged ladder differing from the knowledge\n * base in even one spelling (the editor's `off: null` against the knowledge\n * base's `off: 'none'`) was dropped as a document takeover: the reported\n * \"configured it on the add-provider card, saved, and it is gone\".\n *\n * With the marker the flush knows the stored ladder is a suggestion, so a\n * staged user intent overrides it. Either way the user's bytes win; the marker\n * only decides whether the flush is allowed to write at all. Schemastery passes\n * unknown model keys through, so the marker survives official-page saves and\n * restarts like the other two markers. Any ladder written through the plugin\n * clears it, which is what makes a later hand edit outrank a fresh staging.\n */\nexport const AUTOFILL_MARKER = 'reasoningEffortsAutofilled'\n\n/**\n * Model-level default-effort pick (issue #4): the level a brand-new session\n * starts this model at, outranking the remembered levels. The value is one of\n * the model's own declared ladder keys, or the field is absent when the user\n * has not picked one (memory chain applies). Deliberately NOT a harness\n * concept: pi-ai's runtime never sees it (unknown model keys ride the settings\n * document the way the other markers do), and the browser half is its only\n * consumer. The name matches the catalog's `reasoning.defaultEffort` spelling\n * so a future first-class field can adopt the stored values as-is.\n */\nexport const DEFAULT_EFFORT_FIELD = 'defaultEffort'\n\n/** Locale dictionary namespace for the browser half's copy (not a settings namespace). */\nexport const STORE_NS = PLUGIN_ID\n", "/**\n * The credential-reference vocabulary the API-key manager shares between both\n * halves.\n *\n * A provider's key list is a list of NAMES: every value lives in the harness\n * credential store under its own reference, and the profile records exactly one\n * of those names (`providers.<route>.apiKeyEnv`) as the reference the adapter\n * resolves when it calls the provider. This module owns the naming rules the\n * two halves must agree on \u2014 the browser half picks the next free name for a\n * new key, the host half re-validates whatever arrives \u2014 so one name can never\n * mean two different things on the two sides of the wire.\n *\n * Deliberately free of `node:` imports: the client bundle imports this module\n * too (the same way `constants.ts` is shared), and a single `node:` import\n * would drag the host into the browser build.\n *\n * @module dsh-model-think-level/key-refs\n */\n\n/** One key the manager lists for a provider route. */\nexport interface KeyEntry {\n /** Credential reference holding the value. */\n readonly ref: string\n /** User-facing label; absent means \"show the reference itself\". */\n readonly alias?: string\n}\n\n/** Longest reference the manager will mint or accept. */\nexport const KEY_REF_MAX_LENGTH = 80\n\n/** Longest alias the manager stores. A label, never a secret. */\nexport const KEY_ALIAS_MAX_LENGTH = 40\n\n/**\n * The shape of a reference the manager accepts. Looser than the credential\n * store's own POSIX-ish rule on purpose: a route may legitimately start with a\n * digit (`9router` \u2192 `9ROUTER_API_KEY`), and the store stays the authority on\n * what it will hold. This is the plugin's sanity bound, not the validation.\n */\nexport const KEY_REF_PATTERN = /^[A-Za-z0-9_]{1,80}$/\n\n/**\n * The reference the official Models page derives for a provider route: the\n * route upper-cased with every non-alphanumeric run folded to `_`, plus\n * `_API_KEY`. Mirrors the official page exactly so the first key the manager\n * adds for a provider is the very reference that page would have written.\n * @param route - the provider route key (`ofox`, `aliyun-cn`).\n * @returns the derived reference name.\n */\nexport function deriveKeyRef(route: string): string {\n return `${route.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`\n}\n\n/** Whether a value is a reference name this manager will pass to the store. */\nexport function isKeyRefName(value: unknown): value is string {\n return typeof value === 'string' && KEY_REF_PATTERN.test(value)\n}\n\n/**\n * The first free name in the sequence `<DERIVED>`, `<DERIVED>_2`, `<DERIVED>_3`\u2026\n * @param route - the provider route key.\n * @param taken - every reference already listed for that route.\n * @returns a reference not in `taken`.\n */\nexport function nextKeyRef(route: string, taken: readonly string[]): string {\n const used = new Set(taken)\n const base = deriveKeyRef(route)\n if (!used.has(base)) return base\n for (let suffix = 2; suffix <= 999; suffix += 1) {\n const candidate = `${base}_${suffix}`\n if (!used.has(candidate)) return candidate\n }\n // A thousand keys on one route is not a real deployment; stay unique anyway.\n return `${base}_${Date.now()}`\n}\n\n/**\n * A stored alias, or undefined when the label carries nothing.\n *\n * Control characters are dropped rather than escaped: an alias is rendered as\n * text on the official page, and a stray newline there is a rendering bug, not\n * data worth keeping.\n * @param value - whatever arrived (user input, or a hand-edited index file).\n * @returns the trimmed label, capped at {@link KEY_ALIAS_MAX_LENGTH}.\n */\nexport function normalizeKeyAlias(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n let cleaned = ''\n for (const char of value) {\n const code = char.codePointAt(0) ?? 0\n if (code < 32 || code === 127) continue\n cleaned += char\n }\n cleaned = cleaned.trim()\n if (cleaned.length === 0) return undefined\n return cleaned.slice(0, KEY_ALIAS_MAX_LENGTH)\n}\n\n/**\n * Whether a value is a key the official page would itself accept: printable\n * ASCII with no spaces (its own `LEGAL_API_KEY`). The manager applies the same\n * rule so a key it stores can never be one the official card would refuse.\n */\nexport function isLegalKeyValue(value: unknown): value is string {\n return typeof value === 'string' && /^[\\x21-\\x7E]+$/.test(value)\n}\n\n/** Shortest value that still gets a head and a tail; below it, a flat mask. */\nconst KEY_MASK_MIN_LENGTH = 12\n\n/**\n * A stored key's display form: a head, an ellipsis and a tail \u2014 enough to tell\n * two look-alike keys apart, never the whole secret.\n *\n * The manager shows every row this way, so a list can say which key a row holds\n * without putting anything usable on the page; the eye beside the field stays\n * the one gesture that reveals a value. A value too short to survive trimming\n * gets a fixed-width mask instead: at that length a head and a tail would be\n * most of the key.\n */\nexport function maskKeyValue(value: string): string {\n if (value.length === 0) return ''\n if (value.length < KEY_MASK_MIN_LENGTH) return '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022'\n return `${value.slice(0, 4)}...${value.slice(-4)}`\n}\n", "/**\n * The provider key index: plugin-owned metadata about the keys configured for\n * one provider route.\n *\n * The harness stores VALUES only: `<DSH_HOME>/.credentials.yaml` holds one value\n * per reference, the service reports `{configured, source, writable}` and never\n * the value, and there is no enumeration API at all. A list of \"the keys this\n * provider has\", each with a human label, therefore cannot live in the harness\n * \u2014 it is plugin state. It is kept here, beside the harness home rather than\n * inside the pi-ai profile, because the official add-provider card writes the\n * WHOLE profile at `providers.<route>` and an unknown sibling key there would\n * be at the mercy of schema validation.\n *\n * The file holds no secrets: references and labels only, which is what makes it\n * safe to keep in plain text and easy for a user to inspect or repair by hand.\n * Existing unreadable or malformed files fail closed, so a mutation cannot\n * replace lost metadata with a fresh index. Every write is atomic (`write` to a\n * sibling temp file, then `rename`), so a\n * crash mid-write cannot leave a half-parsed index behind.\n *\n * All of it is synchronous on purpose: the host is single-threaded, so a\n * read-modify-write inside one request handler cannot interleave with another\n * request's, which is the whole concurrency story this file needs.\n *\n * @module dsh-model-think-level/key-index\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { normalizeKeyAlias, type KeyEntry } from './key-refs.js'\n\n/** One route's entry, re-exported so the host half has a single import site. */\nexport type KeyIndexEntry = KeyEntry\n\n/** The whole index document, exactly as it sits on disk. */\nexport interface KeyIndexDocument {\n /** Schema version; a future shape can migrate by reading this. */\n readonly version: 1\n /** Route \u2192 keys, in the order the manager lists them. */\n readonly providers: Record<string, readonly KeyIndexEntry[]>\n}\n\n/** A fresh, empty index. */\nexport function emptyKeyIndex(): KeyIndexDocument {\n return { version: 1, providers: {} }\n}\n\n/**\n * The harness home: `$DSH_HOME` when the host exports it, else the `~/.dsh`\n * the harness would have defaulted to. Never throws.\n */\nexport function harnessHome(): string {\n const configured = process.env['DSH_HOME']\n if (typeof configured === 'string' && configured.length > 0) return configured\n try {\n return join(homedir(), '.dsh')\n } catch {\n return '.dsh'\n }\n}\n\n/** Absolute path of the plugin's key index. */\nexport function keyIndexFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', 'key-index.json')\n}\n\n/**\n * Parse an already-decoded index document. Never throws and never trusts the\n * input: anything unrecognisable is dropped entry by entry, so a hand-edited or\n * truncated file costs at most the lines it got wrong.\n * @param raw - the decoded JSON value (or anything else).\n * @returns a well-formed document.\n */\nexport function parseKeyIndex(raw: unknown): KeyIndexDocument {\n if (typeof raw !== 'object' || raw === null) return emptyKeyIndex()\n const providers = (raw as Record<string, unknown>)['providers']\n if (typeof providers !== 'object' || providers === null) return emptyKeyIndex()\n const out: Record<string, KeyIndexEntry[]> = {}\n for (const [route, entries] of Object.entries(providers as Record<string, unknown>)) {\n if (route.length === 0 || !Array.isArray(entries)) continue\n const list: KeyIndexEntry[] = []\n for (const entry of entries) {\n if (typeof entry !== 'object' || entry === null) continue\n const record = entry as Record<string, unknown>\n const ref = record['ref']\n if (typeof ref !== 'string' || ref.length === 0) continue\n if (list.some(existing => existing.ref === ref)) continue\n const alias = normalizeKeyAlias(record['alias'])\n list.push(alias === undefined ? { ref } : { ref, alias })\n }\n if (list.length > 0) out[route] = list\n }\n return { version: 1, providers: out }\n}\n\n/** Read the index; only an absent file means a fresh, empty document. */\nexport function readKeyIndex(file: string = keyIndexFilePath()): KeyIndexDocument {\n let text: string\n try {\n text = readFileSync(file, 'utf8')\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return emptyKeyIndex()\n }\n throw error\n }\n const raw: unknown = JSON.parse(text)\n const record = typeof raw === 'object' && raw !== null && !Array.isArray(raw)\n ? raw as Record<string, unknown> : undefined\n const providers = record?.['providers']\n if (record === undefined || (record['version'] !== undefined && record['version'] !== 1) ||\n typeof providers !== 'object' || providers === null || Array.isArray(providers)) {\n throw new Error('the key index is malformed; repair it before changing keys')\n }\n for (const [route, entries] of Object.entries(providers)) {\n if (route.length === 0 || !Array.isArray(entries) || entries.some((entry: unknown) => {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return true\n const ref = (entry as Record<string, unknown>)['ref']\n return typeof ref !== 'string' || ref.length === 0\n })) {\n throw new Error('the key index is malformed; repair it before changing keys')\n }\n }\n // Keep the existing normalization, including unversioned documents, aliases\n // and duplicate references, for valid indexes written by older versions.\n return parseKeyIndex(raw)\n}\n\n/** Write the index at one path, atomically. */\nexport function writeKeyIndex(document: KeyIndexDocument, file: string = keyIndexFilePath()): void {\n mkdirSync(dirname(file), { recursive: true })\n const temporary = `${file}.${process.pid}.tmp`\n writeFileSync(temporary, `${JSON.stringify(document, null, 2)}\\n`, 'utf8')\n try {\n renameSync(temporary, file)\n } catch (error) {\n try {\n unlinkSync(temporary)\n } catch {\n // The temp file is best-effort cleanup; the rename failure is the news.\n }\n throw error\n }\n}\n\n/**\n * One synchronous read-modify-write. The returned document is what was stored.\n * @param mutate - pure document transform.\n * @param file - index path (tests pass a temp file).\n */\nexport function updateKeyIndex(\n mutate: (document: KeyIndexDocument) => KeyIndexDocument,\n file: string = keyIndexFilePath(),\n): KeyIndexDocument {\n const next = mutate(readKeyIndex(file))\n writeKeyIndex(next, file)\n return next\n}\n\n/** One route's keys, or an empty list. */\nexport function keyEntriesOf(document: KeyIndexDocument, route: string): readonly KeyIndexEntry[] {\n const entries = document.providers[route]\n return Array.isArray(entries) ? entries : []\n}\n\n/** Whether one route's list names this reference. */\nexport function hasKeyEntry(document: KeyIndexDocument, route: string, ref: string): boolean {\n return keyEntriesOf(document, route).some(entry => entry.ref === ref)\n}\n\n/**\n * Add a key, or relabel the one already there. Order is preserved: the list is\n * what the panel renders, and a key that moves on every rename is a worse list.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param alias - a label, or undefined to keep whatever is stored.\n */\nexport function withKeyEntry(\n document: KeyIndexDocument,\n route: string,\n ref: string,\n alias?: string | undefined,\n): KeyIndexDocument {\n const list = [...keyEntriesOf(document, route)]\n const index = list.findIndex(entry => entry.ref === ref)\n const label = normalizeKeyAlias(alias)\n const next: KeyIndexEntry = label === undefined ? { ref } : { ref, alias: label }\n if (index === -1) list.push(next)\n else list[index] = label === undefined && list[index]?.alias !== undefined ? { ref, alias: list[index]?.alias } : next\n return { version: 1, providers: { ...document.providers, [route]: list } }\n}\n\n/**\n * Set (or clear) one key's label.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference; a no-op when it is not listed.\n * @param alias - the new label, or undefined to fall back to the reference.\n */\nexport function withKeyAlias(\n document: KeyIndexDocument,\n route: string,\n ref: string,\n alias: string | undefined,\n): KeyIndexDocument {\n const list = [...keyEntriesOf(document, route)]\n const index = list.findIndex(entry => entry.ref === ref)\n if (index === -1) return document\n const label = normalizeKeyAlias(alias)\n list[index] = label === undefined ? { ref } : { ref, alias: label }\n return { version: 1, providers: { ...document.providers, [route]: list } }\n}\n\n/**\n * Drop one key. The route key itself is removed once its list empties, so a\n * provider the user cleaned up leaves no residue in the file.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference to forget.\n */\nexport function withoutKeyEntry(document: KeyIndexDocument, route: string, ref: string): KeyIndexDocument {\n const list = keyEntriesOf(document, route).filter(entry => entry.ref !== ref)\n const providers: Record<string, readonly KeyIndexEntry[]> = { ...document.providers }\n if (list.length === 0) delete providers[route]\n else providers[route] = list\n return { version: 1, providers }\n}\n", "/**\n * The reasoning-effort + input-modality knowledge base + wire-protocol\n * inference engine.\n *\n * Every model a third-party provider route serves must declare its\n * 'reasoningEfforts' (which DSH thinking levels it accepts, and the exact\n * string to send on the wire for each) before the composer's model picker\n * offers any reasoning control for it. This module answers \"what should this\n * model's declaration be?\" from three sources, in order:\n *\n * 1. An endpoint listing signal (when the route was probed): an explicit\n * \"does not reason\", a modality disclosure, or a context length.\n * 2. A curated knowledge base keyed by model id/name patterns, carrying the\n * exact level set, wire spellings, request modalities, and reference\n * capacities known to work against that family of endpoints.\n * 3. Wire-protocol inference from the route's 'api' / 'baseURL', plus a\n * conservative name heuristic for modalities, for families nothing else\n * names.\n *\n * All outputs stay on the adapter's own vocabulary (THINKING_LEVELS,\n * INPUT_MODALITIES, the reasoningEfforts/input dict shapes) so a suggested\n * declaration can be written to llm-pi-ai settings with no translation step.\n * A suggestion is a *preset*: the user can accept it, tune it, or ignore it.\n * The plugin never silently overwrites a declaration the user already made.\n *\n * @module dsh-model-think-level/knowledge\n */\n\n/** The canonical pi-ai escalation order accepted by llm-pi-ai. */\nexport const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const\n\nexport type ThinkingLevel = (typeof THINKING_LEVELS)[number]\n\n/**\n * The request-modality vocabulary llm-pi-ai accepts on a model entry -- a\n * local mirror of pi-ai's MODALITY_GATE (text/image today). The core schema\n * refuses anything else at write time, and its drift gate forces the\n * vocabulary to grow exactly when pi-ai's Model['input'] does; the vocabulary\n * spec pins this mirror against upstream so the UI follows.\n */\nexport const INPUT_MODALITIES = ['text', 'image'] as const\n\nexport type InputModality = (typeof INPUT_MODALITIES)[number]\n\n/** One level's wire spelling; null means \"send nothing for this level\". */\nexport type WireSpelling = string | null\n\n/** A full reasoning-effort declaration value: level -> wire spelling. */\nexport type ReasoningEfforts = Partial<Record<ThinkingLevel, WireSpelling>>\n\n/** A full input-modality declaration value: the modalities a model accepts. */\nexport type InputModalities = readonly InputModality[]\n\n/** Reasoning-budget request-field spellings pi-ai accepts (older kernels reject them). */\nexport const THINKING_TOKEN_BUDGET_FIELDS = ['thinking_token_budget', 'thinking_budget', 'thinking_budget_tokens'] as const\nexport type ThinkingTokenBudgetField = (typeof THINKING_TOKEN_BUDGET_FIELDS)[number]\n\n/** The compat fields this plugin may suggest (a subset of the profile schema). */\nexport interface CompatSuggestion {\n /** Wire format the endpoint speaks; omitted when unknown. */\n thinkingFormat?: string\n /** Whether the endpoint accepts a reasoning-effort-style parameter. */\n supportsReasoningEffort?: boolean\n /**\n * Whether pi-ai may rewrite the system prompt to the developer role for\n * reasoning models. Self-hosted relays get an explicit false (their\n * upstreams reject role:developer); official endpoints keep pi-ai's own\n * detection default by omitting the field.\n */\n supportsDeveloperRole?: boolean\n /**\n * Anthropic-messages protocol only: force adaptive thinking so the\n * declared efforts dispatch as `output_config.effort` instead of falling\n * into the older budget-based thinking path. pi-ai offers this field on\n * exactly the anthropic-messages compat gate, and the oracle models that\n * take an effort ladder all have adaptive thinking.\n */\n forceAdaptiveThinking?: boolean\n thinkingTokenBudgetField?: ThinkingTokenBudgetField\n supportsThinkingTokenBudget?: boolean\n vllmPriority?: number\n}\n\n/**\n * Compat keys a kernel older than their introduction does not know, so an\n * autofill patch carrying one is stripped before the downgrade retry.\n *\n * `supportsMaxOutputTokens` is RETIRED -- the row editor no longer offers the\n * control -- but a profile written by an earlier version still carries the key,\n * and that stored value rides an autofill patch, so it stays on this list.\n */\nexport const NEW_COMPAT_KEYS = ['thinkingTokenBudgetField', 'vllmPriority', 'supportsMaxOutputTokens'] as const\n\n/** One knowledge-base entry: which model families it matches and what to declare. */\nexport interface KnowledgeEntry {\n /** Stable id (also used to de-duplicate user overrides). */\n id: string\n /** Model id/name patterns (lowercase substring match). */\n patterns: readonly string[]\n /**\n * Level set + wire spellings to declare. `false` marks a family the\n * official catalog serves WITHOUT any reasoning control (GPT-4o / GPT-4\n * generations): suggesting a ladder there would have the composer send\n * reasoning_effort and get a 400 from the real endpoint.\n */\n efforts: ReasoningEfforts | false\n /** Optional compat block to declare alongside the efforts. */\n compat?: CompatSuggestion\n /**\n * The model family takes an effort ladder on the anthropic-messages\n * protocol too: pi-ai only routes declared efforts to `output_config.effort`\n * when `forceAdaptiveThinking` is set, so this pin adds that compat block\n * on anthropic-messages routes (and nothing on any other protocol).\n */\n anthropicAdaptive?: boolean\n /**\n * Request modalities to declare, in core vocabulary. Absent = no modality\n * suggestion for this family. Wider support a gateway may serve (pdf,\n * audio, video) is recorded in 'note' until the core vocabulary grows.\n */\n input?: InputModalities\n /**\n * Reference context window in tokens (display-only advice; the official\n * capacity inputs are never auto-filled).\n */\n contextWindow?: number\n /** Reference max output tokens in tokens (display-only advice). */\n maxTokens?: number\n /**\n * The vendor's own default level for the family, when its docs name one\n * (the same research pass that recorded the ladders). Consumed by the\n * client's effort memory as the model-switch fallback: a switch to a model\n * with no remembered level re-applies the vendor default instead of leaving\n * the session on the host's \"Default\" (no-effort) state. Never guessed --\n * entries whose docs publish no default simply carry none.\n */\n defaultEffort?: ThinkingLevel\n /** Human note shown next to the suggestion (localized by the caller). */\n note?: string\n}\n\n/** What a provider route names about itself that inference can use. */\nexport interface RouteFacts {\n /** Wire protocol as configured ('api'), if any. */\n api?: string\n /** Endpoint URL, if any. */\n baseURL?: string\n /** Display name, if any. */\n displayName?: string\n}\n\n/** The endpoint facts a suggestion fuses, as the probe route reports them. */\nexport interface EndpointFacts {\n /** Tri-state reasoning signal: true / false / 'unknown' (listing silent). */\n reasoning: boolean | 'unknown'\n /** The listing field that produced the reasoning signal, null when none did. */\n source: string | null\n /**\n * The listing's input-modality disclosure, normalized to lowercase strings,\n * when the listing named such a field at all. Present-but-empty means the\n * field existed with no usable members; absent means the listing never\n * spoke about modalities (or the probe never ran) -- the tri-state\n * discipline: silence is not refusal.\n */\n input?: readonly string[]\n /** Context length the listing disclosed, when it carries one. */\n contextLength?: number\n}\n\n/** How a suggestion's input-modality part was derived. */\nexport type InputSource = 'knowledge' | 'endpoint' | 'heuristic'\n\n/** A resolved suggestion for one model on one route. */\nexport interface EffortSuggestion {\n /**\n * The reasoning-effort declaration to write, if one is derivable. False\n * arrives when the endpoint explicitly reports the model does not reason.\n */\n efforts?: ReasoningEfforts | false\n /**\n * The vendor's own default level for the model, when the knowledge base\n * names one and the suggested ladder carries it. The effort memory uses it\n * as the model-switch fallback (see {@link KnowledgeEntry.defaultEffort}).\n */\n defaultEffort?: ThinkingLevel\n /** The compat block to write alongside, if any. */\n compat?: CompatSuggestion\n /** Request modalities to declare, when derivable. */\n input?: InputModalities\n /** Where the modality part came from -- its confidence rides this. */\n inputSource?: InputSource\n /** Reference context window (display-only; never auto-filled anywhere). */\n contextWindow?: number\n /** Reference max output tokens (display-only). */\n maxTokens?: number\n /** Whether a knowledge-base entry matched (vs protocol inference). */\n matched: boolean\n /** The knowledge entry id when one matched. */\n entryId?: string\n /** Human-readable source of the suggestion. */\n source: string\n /**\n * Overall confidence for the UI: high = knowledge base (wire values) and/or\n * an explicit endpoint signal; medium = endpoint confirmed reasoning but the\n * level ladder is inferred; low = protocol inference alone.\n */\n confidence: 'high' | 'medium' | 'low'\n /** The endpoint signal behind this suggestion, when one was supplied. */\n endpoint?: { reasoning: boolean | 'unknown'; source: string | null }\n}\n\n/**\n * The curated knowledge base. Patterns are lowercase substring matches against\n * the model id (and display name). First match wins, longest pattern wins.\n *\n * Sources of truth (per family; DeepSeek / OpenAI / Anthropic re-checked\n * 2026-09 against their current official docs, the rest 2026-08): official API docs --\n * api-docs.deepseek.com (news/pricing/thinking/vision/API reference),\n * developers.openai.com model pages + guides (platform.openai.com blocked;\n * Azure learn mirror cross-checked), platform.claude.com (effort page,\n * models overview, OpenAI-SDK compatibility page), ai.google.dev (thinking +\n * OpenAI-compat pages), docs.x.ai (model pages + reasoning capability),\n * docs.bigmodel.cn (thinking + model pages), platform.kimi.com (models /\n * use-thinking-models / use-reasoning-effort), platform.stepfun.com (model\n * pages + reasoning), docs.byteplus.com / volcengine ModelArk (deep\n * reasoning), cloud.baidu.com (Qianfan pricing/thinking model list),\n * plus first-party GitHub cards (openai/gpt-oss, mistralai/mistral-common,\n * Tencent-Hunyuan/Hy3, MiniMax-AI/MiniMax-M3) -- cross-checked against the\n * public OpenRouter catalog (input_modalities, supported_parameters) where\n * noted. 2026-10 \u5168\u9762\u6821\u51C6 pass: the whole table was re-checked against\n * pi-ai 1.2.0's official model catalog, whose thinkingLevelMap semantics\n * are adopted here -- a level PRESENT in the map is accepted (a null value\n * means it dispatches via omit/budget/toggle channels, NOT an active\n * disable for the openai/anthropic families), and a level ABSENT is\n * refused and must not be declared. Capacities are REFERENCE values:\n * aggregators disagree, so the note says so where the spread is wide, and\n * families whose numbers stay contested simply carry none.\n */\nexport const KNOWLEDGE_BASE: readonly KnowledgeEntry[] = [\n {\n id: 'deepseek-v4-vision',\n // Must precede deepseek-v4 semantically -- guaranteed anyway by the\n // longest-boundary-hit rule, since these patterns are strictly longer.\n patterns: ['deepseek-v4-flash-vision', 'deepseek-v4-vision'],\n efforts: { off: 'none', low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 384_000,\n note: 'DeepSeek \u89C6\u89C9\u5B9E\u9A8C\u7248 id\uFF08deepseek-v4-flash-vision-exp\uFF09\u3002\u5B98\u65B9\u76EE\u5F55\u5DF2\u6807\u6CE8\u8BE5\u6A21\u578B\u9000\u5F79\uFF0C\u540D\u5B57\u4ECD\u88AB\u63A5\u53D7\u3001\u7531\u73B0\u884C deepseek-flash \u63D0\u4F9B\u670D\u52A1\u2014\u2014\u56FE\u7247\u8F93\u5165\u73B0\u5DF2\u7531 deepseek-flash \u539F\u751F\u63D0\u4F9B\u3002',\n },\n {\n id: 'deepseek-v4-1-flash',\n // V4.1-Flash is DeepSeek's CURRENT flagship and it takes image input, which\n // the shared `deepseek-v4` stem cannot express: that entry carries the text\n // floor its pro/legacy siblings share, and one modal answer cannot be both.\n // This entry keys every V4.1 spelling, and it must stay ahead of the base\n // stem -- the longest-hit rule guarantees that, these patterns are strictly\n // longer -- so an id, or a display name, that says \"V4.1 Flash\" declares\n // images even when the relay invented the id itself.\n // 'deepseek-flash' is the CURRENT official id (2026-09-10) and belongs\n // here, not to the stem: the pricing page serves it as V4.1-Flash, and a\n // third-party reseller exposing DeepSeek's own model under that name means\n // the same model.\n patterns: ['deepseek-v4.1-flash', 'deepseek-flash'],\n efforts: { off: 'none', low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 384_000,\n note: 'DeepSeek-V4.1-Flash\uFF082026-09-10 \u53D1\u5E03\u7684\u73B0\u884C\u5B98\u65B9\u6A21\u578B\uFF0C\u5B98\u65B9 id \u4E3A deepseek-flash\uFF1B25 \u4E07\u5E76\u53D1\u3001**\u539F\u751F\u56FE\u7247\u8F93\u5165**\uFF09\u3002V4.1 \u7684\u5404\u5199\u6CD5\uFF08deepseek-flash\u3001deepseek-v4.1-flash\u3001deepseek-v4-1-flash\uFF0C\u4EE5\u53CA\u5E26\u65E5\u671F\u540E\u7F00\u7684\u7B2C\u4E09\u65B9\u53D8\u4F53\uFF09\u90FD\u5F52\u6B64\u6761\u2014\u2014\u7EAF\u6587\u672C\u7684 deepseek-v4 \u4E3B\u5E72\u4E0D\u518D\u541E\u6389\u5B83\u4EEC\u3002\u5B98\u65B9\u679A\u4E3E\u540C V4 \u7CFB\uFF1AOff\uFF08thinking:\"disabled\"\uFF09/ Low / High / Max\uFF0C\u9ED8\u8BA4 High\uFF1B\u5BB9\u91CF 1,048,576 \u4E0A\u4E0B\u6587 / \u6700\u5927\u8F93\u51FA 384K\u3002',\n },\n {\n id: 'deepseek-v4',\n // One pattern covers the family's TEXT-floor members: every serving\n // suffixes the base id (deepseek-v4-flash, deepseek-v4-pro,\n // deepseek-v4-flash-free ...), so the shared stem keys them all --\n // including free/aggregator spellings the official catalog never lists.\n // Closing thinking is the 'thinking: disabled' object, so the off spelling\n // is a non-null placeholder that arms the deepseek format's disabled\n // branch. The placeholder must stay 'none': pi-ai's deepseek completions\n // branch only checks non-null (any string arms thinking:disabled), while\n // the same map rides the Responses API as reasoning.effort, whose official\n // DeepSeek values are none/low/high/max -- 'off' would be a 400 there.\n // The stem deliberately stops at 'deepseek-v4': the image-capable V4.1\n // generation keys its own strictly longer entry above, while this entry\n // keeps the retired deepseek-v4-flash spelling and the text-only\n // deepseek-v4-pro, whose declarations agree with its text floor.\n patterns: ['deepseek-v4'],\n efforts: { off: 'none', low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 1_048_576,\n maxTokens: 384_000,\n note: 'DeepSeek \u5B98\u65B9\u679A\u4E3E Low / High / Max\uFF08\u9ED8\u8BA4 High\uFF1Bminimal\u3001medium\u3001xhigh \u517C\u5BB9\u6620\u5C04\uFF0Cultra\u2192max\uFF09\uFF0COff \u5373 thinking:\"disabled\"\uFF08Responses API \u4E0B off \u4EE5 reasoning.effort:\"none\" \u8868\u793A\uFF09\u3002\u672C\u6761\u76EE\u662F V4 \u5BB6\u65CF\u7684**\u7EAF\u6587\u672C**\u6210\u5458\uFF1Adeepseek-v4-pro\uFF08= DeepSeek-V4-Pro-0813\uFF0C\u5B98\u65B9\u4E0D\u652F\u6301\u56FE\u7247\uFF09\u4E0E\u5DF2\u9000\u5F79\u6A21\u578B\u7684\u517C\u5BB9\u522B\u540D deepseek-v4-flash\uFF08deepseek-v4-flash-vision-exp \u53E6\u6709\u89C6\u89C9\u6761\u76EE\uFF09\u3002**\u6536\u56FE\u7684 V4.1-Flash\uFF08\u5B98\u65B9 id deepseek-flash\uFF09\u53E6\u6709\u4E13\u95E8\u6761\u76EE**\uFF0C\u5176 input \u542B image\u3002\u5BB9\u91CF\uFF1A1,048,576 \u4E0A\u4E0B\u6587 / \u6700\u5927\u8F93\u51FA 384K\uFF08393,216\uFF1B\u9ED8\u8BA4\u975E\u601D\u8003 8K\u3001\u601D\u8003 64K\u3001effort=max \u65F6 128K\uFF09\u3002',\n },\n {\n id: 'deepseek-v3',\n // deepseek-reasoner belongs to the R1 entry: it is the reasoning model's\n // API name and must not match here. The old alias pair\n // (deepseek-chat / deepseek-reasoner) was retired upstream in 2026-07;\n // the id patterns stay for third-party gateways still serving V3.x.\n patterns: ['deepseek-v3', 'deepseek-chat'],\n efforts: { off: 'none', high: 'high', max: 'max' },\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 163_840,\n maxTokens: 65_536,\n note: 'DeepSeek V3 \u6863\u4F4D\uFF1AOff / High / Max\u3002\u5B98\u65B9\u5DF2\u505C\u552E V3 \u4EE3\uFF08\u5B9A\u4EF7\u9875\u4EC5\u5269 V4 \u4E09\u578B\uFF09\uFF0C\u5BB9\u91CF\u53D6\u76EE\u5F55\u73B0\u5F79\u503C\u3002',\n },\n {\n id: 'deepseek-r1',\n patterns: ['deepseek-r1', 'deepseek-reasoner'],\n // R1's reasoning cannot be switched off at the API level; the harness\n // treats it as a thinking model whose only declared level is the default.\n efforts: { high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 163_840,\n maxTokens: 32_768,\n note: 'DeepSeek-R1 \u4E3A\u63A8\u7406\u6A21\u578B\uFF0C\u4EC5\u63D0\u4F9B High\u3002\u5B98\u65B9\u5DF2\u4E0B\u67B6 R1 \u4EE3\uFF0C\u5BB9\u91CF\u53D6\u76EE\u5F55 r1-0528 \u503C\u3002',\n },\n {\n id: 'openai-gpt-5-2',\n patterns: ['gpt-5.2'],\n // gpt-5.2 (2025-12) took 'none' as the explicit no-thinking value\n // (replacing gpt-5's 'minimal') and added xhigh; its default is none.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.2 \u6863\u4F4D\uFF1ANone / Low / Medium / High / XHigh\uFF08\u9ED8\u8BA4 None\uFF09\u3002\u5B98\u65B9\u53E6\u652F\u6301 PDF \u8F93\u5165\uFF08\u6838\u5FC3\u8BCD\u8868\u6682\u4E0D\u542B\uFF09\u3002gpt-5.2-pro \u5B98\u65B9\u9875\u672A\u5355\u5217\u6863\u4F4D\u884C\uFF0C\u6309\u672C\u6761\u76EE\u540C\u6863\u5904\u7406\uFF1Bgpt-5.2-codex \u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'openai-gpt-5-2-codex',\n // The codex variant's official model page names low/medium/high/xhigh\n // only -- NO none -- so the shared gpt-5.2 entry must not claim an off\n // for it (a 'none' request would 400). Longer pattern wins over 'gpt-5.2'.\n patterns: ['gpt-5.2-codex'],\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n // OpenAI's API default for the codex line is medium (Inspect AI's\n // per-model default table, aligned with developers.openai.com).\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.2-Codex \u6863\u4F4D\uFF1ALow / Medium / High / XHigh\uFF08\u65E0 None \u6863\uFF0C\u52FF\u52FE Off\uFF09\uFF0C\u5E26\u56FE\u8F93\u5165\u3001400K\u3002',\n },\n {\n id: 'openai-gpt-5-6',\n patterns: ['gpt-5.6'],\n // gpt-5.6 spans the full modern ladder including max; the sol/luna/terra\n // variants share it (official reasoning guide: values \"can include none\n // minimal low medium high xhigh, and max\"). pi-ai 1.2.0 catalog\n // confirms the FULL ladder at a 272,000 context.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-5.6\uFF08\u522B\u540D\u5373 sol\uFF09\u6863\u4F4D\uFF1ANone / Low / Medium(\u9ED8\u8BA4) / High / XHigh / Max\uFF1Bsol/luna/terra \u540C\u6863\uFF0C\u5E26\u56FE\u8F93\u5165\u30022026-10 \u6821\u51C6\uFF1A\u4E0A\u4E0B\u6587\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8BB0 272,000\uFF08\u6B64\u524D\u8BEF\u8BB0 1,050,000\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-5',\n patterns: ['gpt-5.5'],\n // gpt-5.5 defaults to medium (official reasoning guide) and tops out at\n // xhigh (max is ABSENT from the pi-ai 1.2.0 catalog); the -pro variant\n // (1.05M context, Responses-only) keeps high/xhigh only.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-5.5 \u6863\u4F4D\uFF1ANone / Low / Medium(\u9ED8\u8BA4) / High / XHigh\uFF08\u65E0 Max \u6863\uFF09\uFF0C\u5E26\u56FE\u8F93\u5165\u3002pro \u53D8\u4F53\u4EC5 High(\u9ED8\u8BA4) / XHigh\u30011.05M \u4E0A\u4E0B\u6587\u4E14\u4EC5 Responses API\u30022026-10 \u6821\u51C6\uFF1A\u4E0A\u4E0B\u6587\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8BB0 272,000\uFF08\u6B64\u524D\u8BEF\u8BB0 1,050,000\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-4',\n patterns: ['gpt-5.4'],\n // Official model page: none (default) / low / medium / high / xhigh;\n // pro drops none+low (medium/high/xhigh, 1.05M, Responses-only);\n // mini/nano sit on 400K. pi-ai 1.2.0 catalog: 272,000 context.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-5.4 \u6863\u4F4D\uFF1ANone(\u9ED8\u8BA4) / Low / Medium / High / XHigh\uFF0C\u5E26\u56FE\u8F93\u5165\u3002pro \u53D8\u4F53\u4EC5 Medium/High/XHigh\uFF081.05M\uFF09\uFF1Bmini/nano \u4E3A 400K \u4E0A\u4E0B\u6587\u30022026-10 \u6821\u51C6\uFF1A\u4E0A\u4E0B\u6587\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8BB0 272,000\uFF08\u6B64\u524D\u8BEF\u8BB0 1,050,000\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-3',\n patterns: ['gpt-5.3'],\n // pi-ai 1.2.0 catalog (gpt-5.3-codex): none IS accepted on the codex\n // line, spelled 'none' -- the older \"no none\" reading is retired.\n // gpt-5.3-chat (non-reasoning) keys its own openai-chat entry.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.3-Codex \u6863\u4F4D\uFF1ANone / Low / Medium(\u9ED8\u8BA4) / High / XHigh\uFF0C\u5E26\u56FE\u8F93\u5165\u3001400K\uFF1B2026-10 \u6821\u51C6\uFF1ANone \u6863\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8865\u56DE\uFF08\u6B64\u524D\u6309\u65E7\u6A21\u578B\u9875\u8BB0\u4E3A\u65E0 None\uFF09\u3002gpt-5.3-chat \u4E3A\u975E\u63A8\u7406\u804A\u5929\u6A21\u578B\uFF08\u89C1 chat \u6761\u76EE\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-1',\n patterns: ['gpt-5.1'],\n // gpt-5.1 (2025-11): none replaces minimal; no xhigh outside codex-max.\n // The codex variants split into their own entry: their official pages\n // publish no effort line, and the codex line's 5.2/5.3 successors take\n // no none -- so the conservative declaration there drops both none and\n // xhigh (see openai-gpt-5-1-codex).\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.1 \u6863\u4F4D\uFF1ANone / Low / Medium / High\uFF08\u9ED8\u8BA4 None\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-1-codex',\n // Official model pages for 5.1-codex / -codex-max / -codex-mini publish no\n // reasoning-effort line (unlike gpt-5.1 itself); the codex successors\n // 5.2/5.3 are low/medium/high/xhigh without none, so none is NOT declared\n // here either. xhigh is likewise unproven for 5.1-codex (the 5.1 page's\n // own ladder stops at high) and is withheld.\n patterns: ['gpt-5.1-codex'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.1-Codex \u7CFB\u5217\uFF1A\u5B98\u65B9\u6A21\u578B\u9875\u672A\u5355\u5217 effort \u503C\u57DF\uFF0C\u6309\u540C\u4EE3\u4FDD\u5B88\u6863 Low / Medium / High\uFF08\u65E0 None\uFF1Bxhigh \u672A\u8BC1\u5B9E\uFF09\u3002\u5982\u7AEF\u70B9\u652F\u6301 xhigh/none \u53EF\u624B\u8C03\u3002',\n },\n {\n id: 'openai-gpt-5',\n patterns: ['gpt-5'],\n // The 2025-08 first generation: minimal is the floor, there is no none,\n // and the default (medium) thinks -- so no off level is offered.\n efforts: { minimal: 'minimal', low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5 \u521D\u4EE3\u6863\u4F4D\uFF1AMinimal / Low / Medium / High\uFF0C\u65E0\u5173\u95ED\u6863\u3002',\n },\n {\n id: 'openai-gpt-5-2-chat',\n // pi-ai 1.2.0 catalog: gpt-5.2-chat-latest IS a reasoning model with a\n // tiny ladder (off[omit] / medium / xhigh) at 128K -- it must not fall\n // into the non-reasoning openai-chat entry below, which is why that\n // entry's 'gpt-5.2-chat' pattern moved here.\n patterns: ['gpt-5.2-chat'],\n efforts: { off: null, medium: 'medium', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 16_384,\n note: 'GPT-5.2-Chat\uFF08\u5B98\u65B9 id gpt-5.2-chat-latest\uFF09\uFF1Api-ai 1.2.0 \u76EE\u5F55\u8BB0\u4E3A\u63A8\u7406\u6A21\u578B\uFF0C\u4EC5 Medium / XHigh \u4E24\u6863\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF0C\u975E\u663E\u5F0F\u5173\u95ED\uFF09\uFF0C128K / 16,384 \u8F93\u51FA\u30022026-10 \u65B0\u589E\u6761\u76EE\u3002',\n },\n {\n id: 'openai-chat',\n // Non-reasoning chat lines across generations: they take no\n // reasoning_effort at all (official model pages list no \"Reasoning\").\n // Official ids are the *-chat-latest snapshots; the bare -chat spellings\n // stay for gateways serving them. gpt-5-chat-latest was removed upstream\n // on 2026-07-23 and gpt-chat-latest has no model page anymore -- the\n // patterns persist for compatibility only. ('gpt-5.2-chat' moved to its\n // own reasoning entry above per pi-ai 1.2.0.)\n patterns: [\n 'gpt-5.1-chat-latest', 'gpt-5.3-chat-latest', 'gpt-5-chat-latest',\n 'gpt-chat-latest', 'gpt-5-chat', 'gpt-5.1-chat', 'gpt-5.3-chat',\n ],\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 16_384,\n note: '-chat \u7CFB\u5217\uFF08\u5B98\u65B9 id \u4E3A gpt-5.x-chat-latest\uFF09\u4E3A\u975E\u63A8\u7406\u804A\u5929\u6A21\u578B\uFF0C\u4E0D\u652F\u6301 effort \u53C2\u6570\uFF08\u52FF\u52FE\u601D\u8003\u6863\uFF09\uFF1B\u5B98\u65B9\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF0C128K / 16,384 \u8F93\u51FA\u3002gpt-5-chat-latest \u5DF2\u4E8E 2026-07-23 \u4E0B\u67B6\u3001gpt-chat-latest \u5DF2\u65E0\u5B98\u65B9\u9875\u9762\uFF08\u4FDD\u7559\u6A21\u5F0F\u4F9B\u7F51\u5173\uFF09\u3002gpt-5.2-chat \u53E6\u6709\u63A8\u7406\u6761\u76EE\u3002',\n },\n {\n id: 'openai-o',\n // The o-series scheduled-removal notice (2026-06-11): o1/o1-pro/o3-mini/\n // o4-mini are removed 2026-10-23 and o3/o3-pro on 2026-12-11, with\n // gpt-5.6-sol / gpt-5.6-terra replacing them; the tokens stay for\n // gateways and local deployments still serving them, and match only on\n // word boundaries (see matchKnowledgeBase), so 'o1' hits 'o1-mini' but\n // not 'ko1'.\n patterns: ['o1', 'o3', 'o4'],\n // o-series had no none: not sending the parameter meant medium (think\n // on), so no off level is offered.\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 200_000,\n maxTokens: 100_000,\n note: 'OpenAI o \u7CFB\u6863\u4F4D\uFF1ALow / Medium / High\u3002\u5B98\u65B9\u5DF2\u4E8E 2026-06 \u516C\u544A\u9000\u5F79\uFF08o1/o1-pro/o3-mini/o4-mini 2026-10-23 \u79FB\u9664\u3001o3/o3-pro 2026-12-11\uFF09\uFF0C\u7F51\u5173\u6B8B\u7559\u4ECD\u53EF\u547D\u4E2D\uFF1B\u591A\u6570 o \u7CFB\u7AEF\u70B9\u6536\u56FE\uFF08o3-mini \u4F8B\u5916\uFF09\u3002',\n },\n {\n id: 'openai-gpt-oss',\n // Official README: configurable reasoning effort low / medium / high\n // (CLI default: low); official model page: 131,072 context and exactly\n // the same 131,072 max output tokens, text input only.\n patterns: ['gpt-oss'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'low',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 131_072,\n maxTokens: 131_072,\n note: 'GPT-OSS \u5F00\u6E90\u6743\u91CD\uFF08Ollama/vLLM \u5E38\u89C1\uFF09\uFF1Areasoning effort Low / Medium / High\uFF0C\u7EAF\u6587\u672C\uFF0C131K \u4E0A\u4E0B\u6587 / 131K \u8F93\u51FA\u30022026-09 \u590D\u6838\uFF1A\u5B98\u65B9\u6A21\u578B\u9875\u73B0\u5728\u5199 Chat Completions = Not supported\u3001\u65E0\u56FE\u7247\u8F93\u5165\uFF08\u9ED8\u8BA4 Low \u6765\u81EA\u5B98\u65B9 CLI\uFF0C\u4E0D\u662F API \u9875\uFF09\uFF0C\u56E0\u6B64\u8FD9\u91CC\u4E0D\u518D\u58F0\u660E Off\u3002',\n },\n {\n id: 'openai-gpt-6',\n // GPT-6 luna/sol/terra (2026, after astra): pi-ai 1.2.0 catalog carries\n // the FULL ladder with an explicit 'none' off for luna/sol. astra keys\n // its own entry above (its off is the omit-style null), and 6.1-sol's\n // off is likewise omit-expressed there -- 'none' is not proven manually\n // adjustable on it, so it stays in the astra entry's shape.\n patterns: ['gpt-6-luna', 'gpt-6-sol', 'gpt-6-terra', 'gpt-6.1'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-6 \u7CFB\uFF08luna/sol/terra\uFF0C2026-10 \u6821\u51C6\u65B0\u589E\uFF09\uFF1Api-ai 1.2.0 \u76EE\u5F55\u5168\u6863 None / Low / Medium / High / XHigh / Max\uFF0C\u5E26\u56FE\u8F93\u5165\uFF0C272,000 \u4E0A\u4E0B\u6587 / 128,000 \u8F93\u51FA\u3002gpt-6-astra \u89C1\u5355\u72EC\u6761\u76EE\uFF08\u88F8 \"gpt-6\" \u4E0E 6.1-sol \u7531 astra \u6761\u76EE\u627F\u63A5\uFF0Coff \u4EE5\u7701\u7565\u8868\u8FBE\uFF0C\"none\" \u672A\u8BC1\u5B9E\u53EF\u624B\u8C03\uFF09\u3002',\n },\n {\n id: 'openai-gpt-6-astra',\n // Longest-pattern-wins keeps this ahead of the 5.x entries; 'astra' is the\n // only stable token an aggregator is likely to expose.\n patterns: ['gpt-6-astra', 'gpt-6', 'gpt-6.1-sol'],\n // Official reasoning guide: none returns HTTP 400 on this model, and the\n // model page lists low/medium/high/xhigh/max. pi-ai 1.2.0 catalog adds\n // minimal as present-null (omit-expressed) and keeps astra at 272,000.\n // The bare 'gpt-6' stem lives here (not on the luna/sol/terra sibling)\n // so gateways serving unversioned \"gpt-6\" keep the omit-style off that\n // astra/6.1-sol actually use; 'gpt-6.1' likewise -- only 6.1-sol exists\n // in the 1.2.0 catalog, and its off is omit-expressed like astra's.\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-6 Astra \u6863\u4F4D\uFF1ALow / Medium / High / XHigh / Max\u2014\u2014**\u6CA1\u6709 None \u6863**\uFF08\u5B98\u65B9\u539F\u6587\uFF1A\u8BBE\u4E3A none \u8FD4\u56DE HTTP 400\uFF09\uFF0C\u56E0\u6B64\u672C\u6761\u76EE\u4E0D\u58F0\u660E Off\u3002\u5E26\u56FE\u8F93\u5165\uFF1B2026-10 \u6821\u51C6\uFF1A\u4E0A\u4E0B\u6587\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8BB0 272,000\uFF08\u6B64\u524D\u8BEF\u8BB0 1,050,000\uFF09\u3002\u5DE5\u5177\u8C03\u7528\u9700\u8D70 Responses API\u3002gpt-6 luna/sol/terra \u89C1\u5355\u72EC\u6761\u76EE\uFF1B\u88F8 \"gpt-6\" \u4E0E 6.1-sol\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\u7531\u672C\u6761\u76EE\u627F\u63A5\u3002',\n },\n {\n id: 'openai-gpt-daybreak',\n // pi-ai 1.2.0 catalog: gpt-daybreak-blue-latest (1.05M) and -red-latest\n // (400K) take the FULL modern ladder with an explicit 'none' off.\n patterns: ['gpt-daybreak'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_050_000,\n maxTokens: 128_000,\n note: 'GPT-Daybreak\uFF08blue-latest 1.05M / red-latest 400K\uFF0C2026-10 \u65B0\u589E\uFF09\uFF1Api-ai 1.2.0 \u76EE\u5F55\u5168\u6863 None / Low / Medium / High / XHigh / Max\uFF0C\u5E26\u56FE\u8F93\u5165 / 128,000 \u8F93\u51FA\u3002',\n },\n {\n id: 'openai-gpt-realtime',\n // pi-ai 1.2.0 catalog: gpt-realtime-2.1 -- minimal joins the ladder as a\n // real wire value (off stays omit-style), 128K in / 32K out.\n patterns: ['gpt-realtime'],\n efforts: { minimal: 'minimal', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 32_000,\n note: 'GPT-Realtime 2.1\uFF082026-10 \u65B0\u589E\uFF09\uFF1Api-ai 1.2.0 \u76EE\u5F55\u6863\u4F4D Minimal / Low / Medium / High / XHigh\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF0C128,000 \u4E0A\u4E0B\u6587 / 32,000 \u8F93\u51FA\u3002',\n },\n {\n id: 'openai-gpt-5-6-cyber',\n // Before the family entry: cyber's model page publishes NO effort line and\n // limits Chat Completions, so the family ladder (which includes none/max)\n // must not be offered for it.\n patterns: ['gpt-5.6-cyber'],\n // Conservative: the codex-style successors publish no none, and cyber's\n // page publishes nothing at all -- declare the intersection the other 5.6\n // variants agree on, plus xhigh (every published 5.6 ladder carries it).\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.6-Cyber\uFF1A\u5B98\u65B9\u6A21\u578B\u9875\u672A\u5355\u5217 effort \u503C\u57DF\uFF08\u4E0D\u7B49\u4E8E\u4E0D\u652F\u6301\uFF09\uFF0C\u6545\u6309\u540C\u4EE3\u4FDD\u5B88\u6863 Low / Medium / High / XHigh\uFF1B\u8BE5\u578B\u53F7\u4EC5 Responses API\uFF0C\u5E26\u56FE\u8F93\u5165\u3001400K \u4E0A\u4E0B\u6587\u3002\u5B98\u65B9\u652F\u6301\u7684\u5176\u4ED6\u6863\u4F4D\u53EF\u624B\u8C03\u540E\u5E94\u7528\u3002',\n },\n {\n id: 'openai-gpt-4o',\n // Boundary matching keeps 'gpt-4' from hitting 'gpt-4o', so the vision\n // generation needs its own entry. gpt-4.1 keeps its own entry below\n // (1M context, larger output cap).\n patterns: ['gpt-4o'],\n // GPT-4o is not a reasoning model (official catalog lists no reasoning,\n // the API refuses reasoning_effort): suggest `false` so the editor\n // marks the row \"does not reason\" instead of wiring a rejected ladder.\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 16_384,\n note: 'GPT-4o \u4EE3\u9645\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u4E0D\u652F\u6301 effort \u53C2\u6570\uFF08\u52FF\u52FE\u601D\u8003\u6863\uFF09\uFF1B\u56FE\u7247\u8F93\u5165\u5168\u7CFB\u6807\u914D\uFF0C128K / 16,384 \u8F93\u51FA\u3002',\n },\n {\n id: 'openai-gpt-4-1',\n // Official model page: 1,047,576 context / 32,768 max output, text+image\n // on every variant (4.1 / mini / nano alike -- the old \"nano is\n // text-only\" claim was wrong). No reasoning step at all.\n patterns: ['gpt-4.1'],\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 1_047_576,\n maxTokens: 32_768,\n note: 'GPT-4.1 \u5168\u7CFB\uFF08\u542B mini/nano\uFF09\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u4E0D\u652F\u6301 effort \u53C2\u6570\uFF1B\u5B98\u65B9 1,047,576 \u4E0A\u4E0B\u6587 / 32,768 \u8F93\u51FA\uFF0C\u5168\u7CFB\u5E26\u56FE\u8F93\u5165\u3002',\n },\n {\n id: 'openai-gpt-4-turbo-preview',\n // The preview snapshot is text-only (later turbo snapshots take images;\n // the shared preview spelling must not claim them). Longest-boundary-hit\n // keeps it ahead of 'gpt-4-turbo'.\n patterns: ['gpt-4-turbo-preview'],\n efforts: false,\n input: ['text'],\n contextWindow: 128_000,\n maxTokens: 4_096,\n note: 'GPT-4 Turbo Preview\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u7EAF\u6587\u672C\u8F93\u5165\uFF08\u6B63\u5F0F turbo \u5FEB\u7167\u652F\u6301\u56FE\u7247\uFF0C\u89C1\u4E0B\u6761\uFF09\uFF0C128K\u3002',\n },\n {\n id: 'openai-gpt-4-turbo',\n patterns: ['gpt-4-turbo'],\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 4_096,\n note: 'GPT-4 Turbo\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u5B98\u65B9\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF0C128K / 4,096 \u8F93\u51FA\u3002',\n },\n {\n id: 'openai-gpt',\n patterns: ['gpt-4', 'gpt-3.5'],\n // Same reasoning as gpt-4o above: the GPT-4/3.5 generations take no\n // reasoning_effort -- suggest `false` rather than a rejected ladder.\n // gpt-4 remains text-only (8K window); the vision-bearing 4o/4.1/turbo\n // lines have their own entries.\n efforts: false,\n input: ['text'],\n note: 'GPT-4/3.5 \u4EE3\u9645\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u4E0D\u652F\u6301 effort \u53C2\u6570\uFF08\u52FF\u52FE\u601D\u8003\u6863\uFF09\u3002gpt-4-turbo/4.1 \u8D77\u652F\u6301\u56FE\u7247\uFF0C\u89C1\u5355\u72EC\u6761\u76EE\uFF1B\u65B0\u4EE3\u8BF7\u7528 GPT-5 \u7CFB\uFF08\u89C1 openai-chat/gpt-5.x \u6761\u76EE\uFF09\u3002',\n },\n {\n id: 'anthropic-claude-5-5',\n // Claude 5.5 generation (2026-10): haiku/opus/sonnet-5-5 all take the\n // FULL effort ladder per pi-ai 1.2.0's official catalog (off and\n // minimal are present-null = omit-expressed, the five rungs dispatch as\n // output_config.effort). Absorbs the turn-2 haiku-5.5 entry: pi-ai\n // 1.2.0 names xhigh/max for the whole generation, the catalog size is\n // 1M/128K (not the 200K/64K first read off ofox's aggregator listing),\n // patterns cover the whole generation plus the bare aggregator\n // spelling. ('claude-haiku-5-5' is NOT listed separately: loose\n // normalization folds '-' and '.' identically, so the dotted spelling\n // already keys the dash spelling -- listing both would trip the\n // unique-normalized-pattern hygiene test.)\n patterns: ['claude-haiku-5.5', 'claude-opus-5-5', 'claude-sonnet-5-5', 'haiku-5.5', 'claude-5-5'],\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n defaultEffort: 'high',\n // No thinkingFormat: pi-ai has no 'anthropic' member, and the\n // openai-completions compat gate that takes thinkingFormat is not the\n // protocol an Anthropic endpoint speaks.\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude 5.5 \u4EE3\uFF08Haiku 5.5 / Opus 5.5 / Sonnet 5.5\uFF09\uFF1Api-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u5168\u6863 Low / Medium / High(\u9ED8\u8BA4) / XHigh / Max\uFF0C\u81EA\u9002\u5E94\u601D\u8003\uFF0C1M \u4E0A\u4E0B\u6587 / 128K \u8F93\u51FA\u3002off/minimal \u4EE5\u7701\u7565\u8868\u8FBE\uFF08\u76EE\u5F55\u5C06\u4E24\u952E\u8BB0\u4E3A null\uFF0C\u975E\u663E\u5F0F\u5173\u95ED\uFF09\u3002',\n },\n {\n id: 'anthropic-claude-5',\n // Claude 5th generation (fable/mythos-5/opus-5/sonnet-5, 2026): adaptive\n // thinking. 2026-10 calibration against pi-ai 1.2.0's official catalog:\n // low/medium/high were REMOVED from these models' effort maps (they\n // remain on the 5.5 generation) -- fable-5 and opus-5 keep only\n // xhigh/max (with an omit-expressed off), sonnet-5 keeps xhigh/max with\n // no off at all. Mythos has no pi-ai entry; it stays matched here\n // conservatively on the same-generation shape. Mythos Preview is split\n // into its own entry below.\n patterns: ['claude-fable-5', 'claude-mythos-5', 'claude-opus-5', 'claude-sonnet-5'],\n // Ladder per pi-ai 1.2.0 (claude-fable-5 / claude-opus-5 /\n // claude-sonnet-5). NOTE: Anthropic's own OpenAI-SDK compatibility\n // layer IGNORES reasoning_effort (thinking is driven by its own param,\n // on by default for Claude 5) -- the declaration bites on third-party\n // gateways that map it; on the native anthropic-messages protocol,\n // anthropicAdaptive pins the compat that makes pi-ai dispatch these as\n // output_config.effort.\n efforts: { xhigh: 'xhigh', max: 'max' },\n // pi-ai 1.2.0 publishes no default rung for this generation; the old\n // 'high' default was removed with the low/medium/high rungs themselves.\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude 5 \u4EE3\uFF08Fable 5 / Mythos 5 / Opus 5 / Sonnet 5\uFF09\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u5DF2\u6536\u7D27\u4E3A XHigh / Max\uFF08low/medium/high \u6863\u5DF2\u4ECE\u8BE5\u4EE3 effort \u76EE\u5F55\u79FB\u9664\uFF1BFable 5 \u4E0E Opus 5 \u53E6\u63A5\u53D7\u4EE5\u7701\u7565\u8868\u8FBE\u7684 off\uFF0CSonnet 5 \u65E0 off\uFF09\u30021M \u4E0A\u4E0B\u6587 / 128K \u8F93\u51FA\uFF08Batch 300K\uFF09\u3002\u5B98\u65B9\u652F\u6301 PDF \u8F93\u5165\u3002\u6CE8\u610F\uFF1AAnthropic \u5B98\u65B9 OpenAI \u517C\u5BB9\u5C42\u4F1A\u5FFD\u7565 effort \u53C2\u6570\uFF0C\u58F0\u660E\u5728\u7B2C\u4E09\u65B9\u7F51\u5173\u6620\u5C04\u65F6\u751F\u6548\u3002',\n },\n {\n id: 'anthropic-claude-5-1',\n // Ahead of the claude-5 entry, whose 'claude-fable-5' / 'claude-mythos-5'\n // patterns are prefixes of these ids and would win the equal-length tie.\n // 2026-10 calibration: pi-ai 1.2.0 keeps fable-5-1 on the same tight\n // xhigh/max map as fable-5 (plus mid-conversation effort support,\n // which this plugin does not declare per model).\n patterns: ['claude-fable-5-1', 'claude-mythos-5-1'],\n efforts: { xhigh: 'xhigh', max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude Fable 5.1 / Mythos 5.1\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u76EE\u5F55\u6863\u4F4D XHigh / Max\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF0C\u81EA\u9002\u5E94\u601D\u8003\u5E38\u5F00\uFF08\u4E0D\u63A5\u53D7 enabled/disabled\uFF09\u30021M \u4E0A\u4E0B\u6587 / 128K \u8F93\u51FA\uFF1BFable 5.1 \u652F\u6301\u4F1A\u8BDD\u4E2D\u9014\u6539\u6863\uFF08\u9700 beta header\uFF0C\u672C\u63D2\u4EF6\u4E0D\u6D89\u53CA\uFF09\u3002',\n },\n {\n id: 'anthropic-claude-mythos-preview',\n // Official effort matrix: max is available, xhigh is NOT (the matrix's\n // xhigh list covers Fable 5 / Mythos 5 / Opus 5 / Opus 4.8 / Opus 4.7 /\n // Sonnet 5 only). pi-ai 1.2.0 has no mythos entry at all; this entry\n // keeps its doc-derived ladder unchanged.\n patterns: ['claude-mythos-preview'],\n efforts: { low: 'low', medium: 'medium', high: 'high', max: 'max' },\n // Anthropic's effort page: the API default is HIGH across the whole\n // supported list (omitting effort behaves exactly as high).\n defaultEffort: 'high',\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude Mythos Preview\uFF1A\u5B98\u65B9\u6863\u4F4D Low / Medium / High / Max\uFF08\u65E0 XHigh\uFF09\uFF0C1M \u4E0A\u4E0B\u6587\u3002pi-ai 1.2.0 \u76EE\u5F55\u65E0 mythos \u6761\u76EE\uFF0C\u672C\u6863\u4F4D\u6CBF\u7528\u5B98\u65B9 effort \u77E9\u9635\u3002',\n },\n {\n id: 'anthropic-claude-opus-4-high',\n patterns: ['claude-opus-4-8', 'claude-opus-4-7'],\n // 2026-10 calibration: pi-ai 1.2.0's catalog lists ONLY xhigh/max for\n // opus-4-7/4-8 -- the low/medium/high rungs are gone from the official\n // effort maps (xhigh remains the recommended coding start on 4.7).\n efforts: { xhigh: 'xhigh', max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude Opus 4.7/4.8\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u6863\u4F4D\u4EC5 XHigh / Max\uFF08low/medium/high \u5DF2\u4ECE\u8BE5\u4EE3\u76EE\u5F55\u79FB\u9664\uFF1Bxhigh \u4E3A\u5B98\u65B9\u63A8\u8350\u7684\u7F16\u7801\u8D77\u6B65\u6863\uFF09\u30021M \u4E0A\u4E0B\u6587\u3002',\n },\n {\n id: 'anthropic-claude-4-6',\n patterns: ['claude-opus-4-6', 'claude-sonnet-4-6'],\n // 2026-10 calibration: pi-ai 1.2.0 narrows the 4.6 generation to a\n // single rung -- max only (the official effort page's \"some models that\n // support max don't support xhigh\" reading tightens further).\n efforts: { max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude 4.6 \u4EE3\uFF08Opus 4.6 / Sonnet 4.6\uFF09\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u4EC5\u5269 Max \u4E00\u6863\uFF08low/medium/high/xhigh \u5747\u5DF2\u4ECE\u76EE\u5F55\u79FB\u9664\uFF09\u30021M \u4E0A\u4E0B\u6587\u3002',\n },\n {\n id: 'anthropic-claude-opus-4-5',\n // The only extended-thinking-only model in Anthropic's official effort\n // support list (claude-opus-4-5-20251101): effort works alongside\n // budget_tokens, and the max/xhigh columns of the official matrix do not\n // name it -- so the ladder tops out at high.\n patterns: ['claude-opus-4-5'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'high',\n compat: { supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 200_000,\n maxTokens: 64_000,\n note: 'Claude Opus 4.5\uFF1A\u5B98\u65B9 effort \u652F\u6301\u5217\u8868\uFF0820251101 \u5FEB\u7167\uFF09\uFF0C\u6863\u4F4D Low / Medium / High\uFF08\u65E0 XHigh/Max\uFF09\uFF0C\u53EF\u4E0E budget_tokens \u5E76\u7528\uFF1B200K / 64K\u3002',\n },\n {\n id: 'anthropic-claude',\n // Everything else in the Claude line: 3.x and the 4.5-generation\n // Sonnet/Haiku. Anthropic's official effort support list names exactly\n // the 5.5/5/5.1 generations plus opus-4-5/4-6/4-7/4-8/sonnet-4-6 -- none\n // of the models matching this entry take the effort parameter (their\n // thinking rides thinking.type), so a ladder here would be refused.\n // `false` is the honest \"no effort control\" declaration, matching the\n // openai-chat convention. (The 5.5 generation -- haiku/opus/sonnet-5-5,\n // including aggregator spellings like 'haiku-5.5' -- keys its own\n // strictly longer entry above.)\n patterns: ['claude'],\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 200_000,\n maxTokens: 64_000,\n note: 'Claude 3.x \u4E0E Sonnet 4.5 / Haiku 4.5\uFF1A\u5B98\u65B9 effort \u53C2\u6570\u4E0D\u652F\u6301\uFF08\u4EC5 5.5/5/5.1 \u4EE3\u3001Opus 4.5/4.6/4.7/4.8\u3001Sonnet 4.6 \u652F\u6301\uFF09\uFF0C\u601D\u8003\u7531 thinking.type \u63A7\u5236\u2014\u2014\u52FF\u52FE\u601D\u8003\u6863\u3002\u53C2\u8003\u5BB9\u91CF 200K / 64K\uFF08Haiku 3.5 \u4E3A\u7EAF\u6587\u672C\uFF0C\u6309\u9700\u53D6\u6D88\u56FE\u7247\uFF09\u3002Haiku 5.5 \u53CA\u6574\u4E2A 5.5 \u4EE3\u89C1\u4E0A\u65B9 anthropic-claude-5-5 \u6761\u76EE\u3002',\n },\n {\n id: 'google-gemini',\n patterns: ['gemini'],\n // Gemini over the OpenAI-compat layer maps reasoning_effort per family\n // (3.1+/3.x -> thinking_level, 2.5 -> thinking_budget). The official\n // compatibility sheet is a full grid (minimal / low / medium / high x\n // family), but the declared ladder stays low/medium/high: the safest\n // universal set, since minimal lands on a non-native value on Gemini\n // 3.1 Pro and none is reserved for 2.5 non-Pro. Users wanting the finer\n // grid tune by hand.\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 65_536,\n note: 'Gemini \u901A\u7528\u5B89\u5168\u6863\uFF1ALow / Medium / High\uFF08\u5B98\u65B9 OpenAI \u517C\u5BB9\u6620\u5C04\u8868\u53E6\u6536 minimal\uFF1A2.5 \u7CFB\u6620\u5C04\u4E3A 1,024 \u9884\u7B97\u30013.1 Flash-Lite/3 Flash \u539F\u751F minimal\u30013.1 Pro \u843D low\uFF09\u3002none \u4EC5\u80FD\u5173 2.5 \u975E Pro\uFF1B2.5 Pro \u4E0E 3 \u4EE3\u4E0D\u53EF\u5173\uFF1B\u5404\u578B\u9ED8\u8BA4\u4E0D\u4E00\uFF08flash-lite \u9ED8\u8BA4\u5173\uFF09\u3002\u5B98\u65B9\u53E6\u6536\u97F3\u9891/\u89C6\u9891/PDF\u3002Gemma-4 \u89C1\u4E0B\u6761\u3002',\n },\n {\n id: 'google-gemma-4',\n // 2026-10 calibration NEW entry: pi-ai 1.2.0 keys gemma-4-26b-a4b-it /\n // gemma-4-31b-it with a THREE-slot map {off:null, minimal:'MINIMAL',\n // high:'HIGH'} -- the Google native spelling for this open model goes\n // upper-case enum style, and the medium/low rungs are ABSENT (they are\n // not accepted). Vision per catalog; 262,144 in / 32,768 out.\n patterns: ['gemma-4'],\n efforts: { off: null, minimal: 'MINIMAL', high: 'HIGH' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n maxTokens: 32_768,\n note: 'Gemma 4\uFF0826b/31b-it\uFF09\uFF1A\u4E09\u6863 Minimal / High\uFF08\u6863\u4F4D\u7EBF\u4E3A\u5B98\u65B9\u5927\u5199\u679A\u4E3E\u62FC\u5199\uFF09\uFF0Coff \u4EE5\u7701\u7565\u8868\u8FBE\uFF1BLow/Medium \u4E0D\u88AB\u63A5\u53D7\u3002\u5E26\u56FE\u8F93\u5165\uFF0C262,144 / 32,768\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF09\u3002',\n },\n {\n id: 'xai-grok-4-7',\n // grok-4.7 shipped after the 2026-08 pass that read it as 404 upstream;\n // that reading is retired here. 2026-10 calibration: pi-ai 1.2.0 is\n // now a first-party catalog entry -- the ladder\n // off[omit]/low/medium/high/xhigh is confirmed (max stays ABSENT), and\n // the earlier \"xhigh unverified\" hedge is retired. Capacity: 500K in /\n // 500K out per the catalog, so the \"max output disagrees across\n // catalogs\" note is resolved as 500,000.\n patterns: ['grok-4.7'],\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 500_000,\n maxTokens: 500_000,\n note: 'Grok 4.7\uFF1A\u6863\u4F4D Low / Medium / High / XHigh\uFF0C\u601D\u8003\u4E0D\u53EF\u5173\u95ED\uFF08off \u4EC5\u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF1B\u5E26\u56FE\u8F93\u5165\uFF0C500K \u4E0A\u4E0B\u6587 / 500K \u8F93\u51FA\uFF082026-10 \u6821\u51C6\uFF1Api-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u786E\u8BA4\u6863\u4F4D\u4E0E\u5BB9\u91CF\uFF0C\"\u4E0A\u6E38 404\"\u4E0E\"\u6863\u4F4D\u672A\u8BC1\u5B9E\"\u4E24\u6761\u65E7\u8BB0\u5F55\u4F5C\u5E9F\uFF09\u3002grok-4.5 \u4F20 xhigh \u88AB\u9759\u9ED8\u6309 High \u5904\u7406\u7684\u8BF4\u660E\u89C1\u5176\u6761\u76EE\u3002',\n },\n {\n id: 'xai-grok-high',\n patterns: ['grok-4.6'],\n // grok-4.6 adds xhigh on top of low/medium/high (default) and cannot\n // close thinking (docs.x.ai model page + reasoning capability page).\n // (An earlier pass read grok-4.7 as 404 upstream; it shipped later --\n // see the entry above.)\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 500_000,\n note: 'Grok 4.6 \u6863\u4F4D\uFF1ALow / Medium / High(\u9ED8\u8BA4) / XHigh\uFF0C\u601D\u8003\u4E0D\u53EF\u5173\u95ED\uFF1B\u5E26\u56FE\u8F93\u5165\u3001500K \u4E0A\u4E0B\u6587\u3002Grok 4.7 \u89C1\u4E0A\u4E00\u6761\uFF08\u6B64\u524D\u8BB0\u4E3A\"\u4E0D\u5B58\u5728\"\uFF0C\u5DF2\u968F\u53D1\u5E03\u4F5C\u5E9F\uFF09\u3002',\n },\n {\n id: 'xai-grok-4-5',\n // grok-4.5 keeps the three-step ladder (default high) with image input\n // and a 500K context window; an xhigh request is silently treated as\n // high (official reasoning page), so it is not declared here.\n patterns: ['grok-4.5'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 500_000,\n note: 'Grok 4.5 \u6863\u4F4D\uFF1ALow / Medium / High(\u9ED8\u8BA4)\uFF0C\u601D\u8003\u4E0D\u53EF\u5173\u95ED\uFF1B\u5E26\u56FE\u8F93\u5165\u3002\u4F20\u5165 xhigh \u4F1A\u88AB\u5B98\u65B9\u9759\u9ED8\u6309 High \u5904\u7406\u3002',\n },\n {\n id: 'xai-grok-4-3',\n // Official reasoning-capability pages: grok-4.3 documents FOUR effort\n // levels (none / low / medium / high) with a 1M context window; the\n // deprecated grok-4-fast/grok-4-1-fast/grok-4-0709 slugs redirect to\n // grok-4.3 at low/none. The old \"no none for 4.3\" reading of the docs\n // was wrong and is fixed here. 2026-10 calibration: pi-ai 1.2.0's\n // catalog has NO xhigh for 4.3 (it joins at 4.6/4.7) and puts the\n // output cap at 30,000 -- the xhigh rung from the earlier pass is\n // retired.\n patterns: ['grok-4.3'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'low',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 30_000,\n note: 'Grok 4.3\uFF1A\u5B98\u65B9\u56DB\u7EA7 reasoning effort\uFF08None / Low(\u9ED8\u8BA4) / Medium / High\uFF09\uFF0C1M \u4E0A\u4E0B\u6587 / 30,000 \u8F93\u51FA\uFF082026-10 \u6821\u51C6\uFF1AXHigh \u6863\u6309 pi-ai 1.2.0 \u76EE\u5F55\u79FB\u9664\u2014\u2014\u5B83\u81EA 4.6 \u8D77\u624D\u52A0\u5165\uFF1B\u5E26\u56FE\u8F93\u5165\uFF09\u3002grok-4-fast \u7B49\u65E7 slug 2026-05-15 \u8D77\u81EA\u52A8\u91CD\u5B9A\u5411\u5230\u672C\u578B\u53F7\u3002',\n },\n {\n id: 'xai-grok',\n // grok-4.5 (and 4.1-fast etc.) take the standard three-step ladder;\n // grok-4 and older reject reasoning_effort outright -- gateways serving\n // them will refuse the value and the user can clear it by hand. Grok\n // 4/4.1 and grok-3 retired 2026-05-15 (redirected to grok-4.3), and\n // grok-build-0.1 (early-access coding model) publishes no effort\n // contract.\n patterns: ['grok'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n note: 'Grok \u901A\u7528\u6863\u4F4D\uFF1ALow / Medium / High\u3002\u521D\u4EE3 grok-4\u3001grok-4.20 \u4E0E grok-build-0.1 \u4E0D\u63A5\u53D7\u8BE5\u53C2\u6570\uFF08grok-4 \u7CFB\u4E0E grok-3 \u5DF2\u4E8E 2026-05-15 \u9000\u5F79\u5E76\u91CD\u5B9A\u5411\u81F3 4.3\uFF09\uFF1Bgrok-4.20-multi-agent \u7684\u56DB\u6863\u63A7\u5236\u7684\u662F agent \u6570\u91CF\u800C\u975E\u601D\u8003\u6DF1\u5EA6\u3002\u65B0\u65E7\u4EE3\u9645\u8BF7\u4F18\u5148\u9009 4.5/4.6/4.3\uFF1B\u591A\u6A21\u6001\u53D8\u4F53\u6309\u9700\u52FE\u9009\u56FE\u7247\u3002',\n },\n {\n id: 'mistral-magistral',\n // 2026-10 calibration REVERSAL: pi-ai 1.2.0's official catalog keys\n // magistral-medium-latest on the new mistral-conversations protocol\n // WITH a two-state effort map (none/high, off spelled 'none') -- the\n // earlier \"no effort parameter / deprecated\" reading is retired. The\n // ladder is the same two-state shape the modern mistral-medium/small\n // line takes; vision per the catalog; capacity 262,144 in / 16,384 out.\n patterns: ['magistral'],\n efforts: { off: 'none', high: 'high' },\n // The catalog's no-parameter behaviour maps to the 'none' wire value.\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n maxTokens: 16_384,\n note: 'Magistral\uFF08magistral-medium-latest\uFF09\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u76EE\u5F55\u663E\u793A\u73B0\u5F79 magistral \u8D70 mistral-conversations \u534F\u8BAE\u5E76\u63A5\u53D7 effort\uFF08None / High \u4E24\u6863\uFF0C\u9ED8\u8BA4 None\uFF09\uFF0C\u5E26\u56FE\u8F93\u5165\uFF0C262,144 / 16,384\u3002\u65E9\u524D\"\u8BE5\u7EBF\u65E0 effort \u53C2\u6570\u4E14\u5DF2\u5F03\u7528\"\u7684\u8BB0\u5F55\u4F5C\u5E9F\u3002',\n },\n {\n id: 'mistral-medium-3',\n // Official reasoning page + mistral-common request.py (the first-party\n // protocol enum) name the reasoning_effort models: values are exactly\n // none/high. 2026-10 calibration adds pi-ai 1.2.0's catalog ids: the\n // reasoning line now spans mistral-large-4 (1M/262K, vision),\n // mistral-medium-2604 / mistral-medium-latest (262K/262K, vision) plus\n // the earlier small-2603/small-latest pair -- all on the same\n // two-state none/high map on the mistral-conversations protocol.\n // Normalization folds '.' and '-' to the same space, so the one dotted\n // spelling also keys the API id (mistral-medium-3-5).\n patterns: [\n 'mistral-medium-3.5', 'mistral-large-4', 'mistral-medium-2604',\n 'mistral-medium-latest', 'mistral-small-latest', 'mistral-small-2603',\n ],\n efforts: { off: 'none', high: 'high' },\n // mistral-common's ModelSettings defaults reasoning_effort to None --\n // the endpoint's no-parameter behaviour IS the none/off level.\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n note: 'Mistral \u73B0\u5F79\u63A8\u7406\u6863\uFF082026-10 \u6269\u5145\uFF09\uFF1ANone / High \u4E24\u6863\uFF0C\u5B98\u65B9 reasoning_effort \u679A\u4E3E\u5373 none/high\uFF1B\u73B0\u5F79\u578B\u53F7 mistral-large-4\uFF081M\uFF09\u3001mistral-medium-3.5\uFF082604/latest\uFF09\u3001mistral-small-2603\uFF08Small 4\uFF09\u7ECF\u5B83\u63A7\u5236\uFF0C\u5747\u5E26\u89C6\u89C9\u3002\u5BB9\u91CF\uFF1Alarge-4 262,144 \u8F93\u51FA\u3001medium 262,144 \u8F93\u51FA\u3001small 256,000 \u8F93\u51FA\uFF08\u4E0A\u4E0B\u6587\u5747 262,144\uFF09\u3002\u975E\u63A8\u7406\u65E7\u6B3E\u89C1\u4E0B\u6761\u3002',\n },\n {\n id: 'mistral-legacy',\n // 2026-10 calibration: pi-ai 1.2.0 keys the NON-reasoning mistral line\n // (r=false, no tlm) separately from the two-state reasoning line above.\n // These slugs take no effort parameter at all; matching them here keeps\n // auto-adapt from handing them the reasoning ladder via the generic\n // 'mistral' stem. devstral/ministral/codestral/pixtral/voxtral carry\n // the stem too and are covered by the same false declaration.\n patterns: [\n 'mistral-large-2411', 'mistral-large-latest', 'mistral-large-2512',\n 'mistral-medium-2505', 'mistral-medium-2508', 'mistral-small-2506',\n 'mistral-nemo', 'devstral', 'ministral', 'codestral', 'pixtral', 'voxtral',\n ],\n efforts: false,\n input: ['text', 'image'],\n note: 'Mistral \u975E\u63A8\u7406\u7EBF\uFF082026-10 \u65B0\u589E\u6761\u76EE\uFF09\uFF1Alarge-2411/2512/latest\u3001medium-2505/2508\u3001small-2506\u3001nemo \u53CA devstral/ministral/codestral/pixtral/voxtral \u7B49\u4E13\u7528\u7EBF\u5747\u4E0D\u63A5\u53D7 effort \u53C2\u6570\uFF08\u52FF\u52FE\u601D\u8003\u6863\uFF09\u3002\u591A\u6570\u73B0\u5F79\u6B3E\u5E26\u89C6\u89C9\uFF08large-2411 \u4E3A\u7EAF\u6587\u672C\uFF09\u3002',\n },\n {\n id: 'qwen-vision',\n // The DashScope vision lines: -vl suffixes and QvQ. Normalization folds\n // 'qwen2.5-vl' to 'qwen2 5 vl', hence the spelled-out middle pattern.\n // Note the modern generations (3.8-max / 3.7-plus / 3.7-flash and the\n // 3.5-omni line) are multimodal too -- see the qwen-3-8 entry and the\n // plain qwen entry note.\n patterns: ['qwen-vl', 'qwen2-vl', 'qwen2-5-vl', 'qwen3-vl', 'qvq'],\n // DashScope takes NO reasoning_effort: thinking is the enable_thinking\n // boolean -- pi-ai's 'qwen' format dispatches exactly that switch.\n // Commercial Model Studio deployments default enable_thinking to TRUE\n // (help.aliyun.com) -- the on state, which is High here.\n efforts: { off: null, high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'qwen' },\n input: ['text', 'image'],\n contextWindow: 131_072,\n maxTokens: 8_192,\n note: '\u901A\u4E49\u89C6\u89C9\u7EBF\uFF08Qwen-VL/QvQ\uFF09\uFF1Aenable_thinking \u5F00\u5173\uFF08\u5F00=High\uFF09\uFF0C\u6536\u56FE\u3002qwen3-vl \u5BB9\u91CF\u66F4\u5927\uFF0C\u6309\u9700\u4E0A\u8C03\u3002',\n },\n {\n id: 'qwen-3-8',\n // The 3.8 generation moved from the bare enable_thinking switch to an\n // official reasoning_effort ladder: the Qwen3.8 README (\"Flexible\n // Thinking Control\"), the Qwen3.8-27B model card, the Qwen3.8-Flash-Next\n // card and the qwen.ai Flash-Next blog all document reasoning_effort\n // with xhigh as the DEFAULT (xhigh/medium/low), alongside the\n // per-request enable_thinking toggle (chat_template_kwargs on\n // open-weight serving). qwen3.8-max stays the current flagship (1M\n // context; Model Studio lists it under image/video understanding), so\n // the plain qwen entry's text-only declaration must not claim it.\n patterns: ['qwen3.8'],\n efforts: { off: null, low: 'low', medium: 'medium', xhigh: 'xhigh' },\n defaultEffort: 'xhigh',\n compat: { thinkingFormat: 'qwen', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n note: 'Qwen 3.8 \u7CFB\uFF1A\u5B98\u65B9 reasoning_effort \u6863\u4F4D XHigh(\u9ED8\u8BA4) / Medium / Low\uFF0Cthinking \u9ED8\u8BA4\u5F00\u3001\u53EF\u6309\u8BF7\u6C42\u5173\u95ED\uFF1B\u539F\u751F\u591A\u6A21\u6001\uFF08qwen3.8-max \u56FE\u50CF/\u89C6\u9891\u7406\u89E3\uFF0C\u89C6\u9891\u672A\u5165\u6838\u5FC3\u8BCD\u8868\uFF09\u30021M \u6863\u4E0A\u4E0B\u6587\u300227B \u4E0E Flash-Next \u5F00\u6E90\u6B3E\u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'qwen-3-8-27b',\n // Open-weight dense release (2026-08-14, HF Qwen/Qwen3.8-27B model\n // card): \"native vision-language model\", 262,144 context natively\n // \"extensible up to 1,000,000 tokens\", reasoning_effort xhigh (default)\n // / medium / low with per-request thinking disable. Longer than the\n // bare 'qwen3.8' pattern, so it wins for -27B ids.\n patterns: ['qwen3.8-27b'],\n efforts: { off: null, low: 'low', medium: 'medium', xhigh: 'xhigh' },\n defaultEffort: 'xhigh',\n compat: { thinkingFormat: 'qwen', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: 'Qwen3.8-27B\uFF08dense\uFF0C2026-08-14 \u5F00\u6E90\uFF09\uFF1A\u5B98\u65B9 reasoning_effort \u6863\u4F4D XHigh(\u9ED8\u8BA4) / Medium / Low\uFF0Cthinking \u9ED8\u8BA4\u5F00\u3001\u53EF\u6309\u8BF7\u6C42\u5173\uFF1B\u539F\u751F\u56FE\u50CF+\u89C6\u9891\u7406\u89E3\uFF08\u89C6\u9891\u672A\u5165\u6838\u5FC3\u8BCD\u8868\uFF09\u3002262,144 \u539F\u751F\u4E0A\u4E0B\u6587\u3001\u5B98\u65B9\u58F0\u660E\u53EF\u6269\u81F3 1M\u3002\u6765\u6E90\uFF1AHF Qwen/Qwen3.8-27B \u6A21\u578B\u5361\u3002',\n },\n {\n id: 'qwen-3-8-flash-next',\n // Open-weight experimental architecture preview (HF\n // Qwen/Qwen3.8-Flash-Next card + the qwen.ai blog): the\n // Qwen4-underpinning hybrid (QSA, n-gram embedding; 125B with 6B\n // activated), native vision encoder, 262,144 context natively\n // extensible to 1M. Thinking control identical to the 3.8 generation:\n // enable_thinking toggle plus reasoning_effort xhigh (default) /\n // medium / low. Longest pattern, so it wins for -flash-next ids.\n patterns: ['qwen3.8-flash-next'],\n efforts: { off: null, low: 'low', medium: 'medium', xhigh: 'xhigh' },\n defaultEffort: 'xhigh',\n compat: { thinkingFormat: 'qwen', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: 'Qwen3.8-Flash-Next\uFF08125B-A6B \u5B9E\u9A8C\u67B6\u6784\uFF0CQwen4 \u524D\u8EAB\uFF09\uFF1A\u5B98\u65B9 reasoning_effort \u6863\u4F4D XHigh(\u9ED8\u8BA4) / Medium / Low + enable_thinking \u5F00\u5173\uFF1B\u539F\u751F\u89C6\u89C9\uFF08Vision Encoder\uFF09\u3002262,144 \u539F\u751F\u4E0A\u4E0B\u6587\u3001\u53EF\u6269\u81F3 1M\u3002\u6765\u6E90\uFF1AHF \u6A21\u578B\u5361\u4E0E qwen.ai \u5B98\u65B9\u535A\u5BA2\u3002',\n },\n {\n id: 'qwen',\n patterns: ['qwen', 'qwq'],\n // DashScope takes NO reasoning_effort: thinking is the enable_thinking\n // boolean (plus thinking_budget) -- pi-ai's 'qwen' format dispatches\n // exactly that switch, so the ladder is honestly open/close with one\n // nominal thinking level. QwQ is think-always; clearing the off level\n // there is one click. Commercial DashScope defaults enable_thinking to\n // TRUE (open-weight serving defaults to false) -- the on state is High.\n efforts: { off: null, high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'qwen' },\n input: ['text'],\n contextWindow: 1_000_000,\n maxTokens: 65_536,\n note: '\u901A\u4E49\u5343\u95EE\uFF1Aenable_thinking \u5F00\u5173\uFF08\u65E0 effort \u6863\uFF09\uFF0C\u5F00=High\uFF1B\u73B0\u5F79\u65D7\u8230\u4E3A qwen3.8 \u7CFB\uFF081M \u6863\u4E0A\u4E0B\u6587\uFF0C\u89C1 qwen-3-8 \u6761\u76EE\uFF09\u30023.6/3.7 \u4EE3\u7684 Plus/Flash \u4EA6\u9ED8\u8BA4\u591A\u6A21\u6001\uFF08\u56FE\u7247/\u89C6\u9891\uFF09\uFF0C\u5982\u63A5\u5165\u8BF7\u6309\u9700\u52FE\u9009\u56FE\u7247\uFF1B\u89C6\u89C9\u7EBF\u89C1 qwen-vision \u6761\u76EE\u3002',\n },\n {\n id: 'glm-vision',\n // Zhipu's vision lines: glm-4v / glm-4.6v / glm-4.5v / glm-5v. Longer\n // than the plain 'glm' patterns, so they win for those ids.\n // 'glm-4-6v' (not 'glm-46v'): normalization folds 'glm-4.6v' to\n // 'glm 4 6v', so the pattern must carry the same inner separator; the\n // same fold gives 'glm-4.5v' -> 'glm 4 5v'.\n patterns: ['glm-4v', 'glm-4-6v', 'glm-4-5v', 'glm-5v'],\n efforts: { off: null, high: 'high' },\n // GLM-4.5V is forced-thinking and the 4.x line defaults to enabled\n // (docs.bigmodel.cn thinking page) -- the on state is High.\n defaultEffort: 'high',\n compat: { thinkingFormat: 'zai' },\n input: ['text', 'image'],\n contextWindow: 131_072,\n maxTokens: 32_768,\n note: '\u667A\u8C31\u89C6\u89C9\u7EBF\uFF08GLM-4V/4.5V/4.6V/5V\uFF09\uFF1Athinking \u5F00\u5173\uFF08\u5F00=High\uFF09\uFF0C\u6536\u56FE\u3002GLM-4.5V \u4E3A\u5F3A\u5236\u601D\u8003\uFF08\u4F20 disabled \u62A5\u9519\uFF0C\u8BF7\u624B\u52A8\u5220 Off \u6863\uFF09\u3002',\n },\n {\n id: 'glm-5-3-flash',\n // Official model page (docs.bigmodel.cn/cn/guide/models/vlm/glm-5.3-flash,\n // page dated 2026-08-28): input modalities \"\u89C6\u9891\u3001\u56FE\u50CF\u3001\u6587\u672C\u3001\u6587\u4EF6\", 1M\n // context / 128K max output, and \"thinking.type \u4EC5\u652F\u6301 enabled\" \u2014 forced\n // thinking, no off switch. \"\u6587\u672C\u53C2\u6570\u4E0E GLM-5.3 \u4FDD\u6301\u4E00\u81F4\" gives the flash\n // variant the 5.3 ladder (low/high/max). Native multimodal (320B), which\n // the text-only glm-5.3 entry must NOT claim \u2014 hence this separate entry;\n // the longer pattern wins over plain 'glm-5.3'.\n // 'glm-5.3-flashx' is the same model under a relay spelling (ofox lists\n // 'z-ai/glm-5.3-flashx' named 'GLM-5.3-FlashX'). It must be listed\n // explicitly: boundary matching rejects the bare 'glm 5 3 flash' needle\n // there because the next character is the alnum 'x', and the shorter\n // 'glm-5.3' would then claim the id as the text-only model.\n patterns: ['glm-5.3-flash', 'glm-5.3-flashx'],\n efforts: { low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'max',\n compat: { thinkingFormat: 'zai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: 'GLM-5.3-Flash\uFF08320B\uFF0C\u5B98\u65B9\u6587\u6863 vlm \u5206\u7C7B\uFF09\uFF1A\u5F3A\u5236\u601D\u8003\uFF08thinking.type \u4EC5 enabled\uFF0C\u4E0D\u652F\u6301\u5173\u95ED\uFF09\uFF0C\u6587\u672C\u53C2\u6570\u4E0E GLM-5.3 \u4E00\u81F4\u2014\u2014\u6863\u4F4D Low / High / Max\u3002\u8F93\u5165\u6A21\u6001\uFF1A\u89C6\u9891\u3001\u56FE\u50CF\u3001\u6587\u672C\u3001\u6587\u4EF6\uFF08\u89C6\u9891/\u6587\u4EF6\u672A\u5165\u6838\u5FC3\u8BCD\u8868\uFF0C\u56FE\u7247\u53EF\u52FE\uFF09\u3002\u5B98\u65B9 1M \u4E0A\u4E0B\u6587 / 128K \u6700\u5927\u8F93\u51FA\u3002\u6765\u6E90\uFF1Adocs.bigmodel.cn \u6A21\u578B\u9875\u3002',\n },\n {\n id: 'glm-5-3',\n patterns: ['glm-5.3'],\n // glm-5.3 accepts exactly max/high/low; anything else (including the\n // 5.2 ladder's minimal/none) errors, and thinking cannot be disabled.\n // The API reference names reasoning_effort's default as max.\n efforts: { low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'max',\n compat: { thinkingFormat: 'zai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: 'GLM-5.3 \u6863\u4F4D\uFF1ALow / High / Max\uFF08\u5F3A\u5236\u601D\u8003\uFF0C\u5176\u4F59\u503C\u62A5\u9519\uFF09\u3002\u5B98\u65B9\u5BB9\u91CF 1M / 128K\u3002',\n },\n {\n id: 'glm-5-2',\n patterns: ['glm-5.2'],\n // glm-5.2 takes the widest ladder in the wild: none/minimal/low/medium/\n // high/xhigh/max (default max). The zai format arms thinking:disabled\n // for off and sends the effort for the rest.\n efforts: { off: 'none', minimal: 'minimal', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n defaultEffort: 'max',\n compat: { thinkingFormat: 'zai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n // Official capability page: none/minimal stop thinking, low/medium map\n // to high, xhigh maps to max -- all seven spellings are accepted.\n note: 'GLM-5.2 \u6863\u4F4D\uFF1ANone / Minimal / Low / Medium / High / XHigh / Max\uFF08\u5B98\u65B9\u6620\u5C04\uFF1ALow\u00B7Medium\u2192High\u3001XHigh\u2192Max\u3001None\u00B7Minimal=\u505C\u6B62\u601D\u8003\uFF09\u3002\u89C6\u89C9\u7EBF\u89C1 glm-vision \u6761\u76EE\u3002',\n },\n {\n id: 'glm',\n patterns: ['glm', 'zhipu', 'chatglm'],\n // GLM 4.x: thinking.type enabled/disabled only, no effort ladder --\n // the zai format sends exactly that switch (and no effort value,\n // because supportsReasoningEffort is not declared). GLM-4.5/4.6\n // default to enabled (hybrid reasoning: the model decides per\n // request) -- the on state is High.\n efforts: { off: null, high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'zai' },\n input: ['text'],\n note: 'GLM \u901A\u7528\uFF1Athinking \u5F00\u5173\uFF08\u65E0 effort \u6863\uFF09\uFF0C\u5F00=High\uFF1Beffort \u9636\u68AF\u4EC5 GLM-5.2+ \u652F\u6301\uFF08\u89C1\u4E0A\u4E24\u6761\u76EE\uFF09\u3002\u6CE8\u610F GLM-4.7/GLM-4.5V \u4E3A\u5F3A\u5236\u601D\u8003\uFF0C\u4F20 disabled \u4F1A\u62A5\u9519\uFF08\u8BF7\u624B\u52A8\u5220 Off \u6863\uFF09\u3002\u89C6\u89C9\u7EBF\u89C1 glm-vision \u6761\u76EE\u3002',\n },\n {\n id: 'kimi-k3',\n patterns: ['kimi-k3'],\n // kimi-k3: top-level reasoning_effort low/high/max (default max),\n // always thinking -- the thinking object must not be sent at all.\n efforts: { low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'max',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n note: 'Kimi K3 \u6863\u4F4D\uFF1ALow / High / Max(\u9ED8\u8BA4 Max)\uFF0C\u8D70\u9876\u5C42 reasoning_effort\uFF1B\u59CB\u7EC8\u63A8\u7406\u3001\u52FF\u4F20 thinking \u5BF9\u8C61\u3002\u539F\u751F\u89C6\u89C9\u7406\u89E3\uFF0C1M \u4E0A\u4E0B\u6587\uFF08\u6700\u5927\u8F93\u51FA\u5B98\u65B9\u672A\u5355\u72EC\u5217\uFF0C\u4E0D\u63D0\u4F9B\uFF09\u3002',\n },\n {\n id: 'kimi-k2-vision',\n // K2.5/K2.6 are multimodal thinking models with a toggleable\n // thinking.type switch (official use-thinking-models table); K2.5 was\n // re-verified as MULTIMODAL on 2026-08-24 (the old \"text-only\" note was\n // wrong). Longer patterns beat the plain 'kimi' stem below.\n patterns: ['kimi-k2.6', 'kimi-k2.5'],\n efforts: { off: null, high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek' },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: 'Kimi K2.5/K2.6 \u89C6\u89C9\u4EE3\uFF1Athinking.type \u5F00\u5173\uFF08\u9ED8\u8BA4\u5F00\u3001\u53EF\u5173\uFF09\uFF0C\u5F00=High\uFF1B\u5E26\u89C6\u89C9\uFF0C256K\u3002K2.7 Code \u59CB\u7EC8\u601D\u8003\uFF0C\u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'kimi-k27-code',\n // K2.7 Code (and its highspeed twin) ALWAYS think: thinking.type only\n // accepts \"enabled\", sending \"disabled\" errors -- so no Off level.\n patterns: ['kimi-k2.7'],\n efforts: { high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek' },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: 'Kimi K2.7 Code\uFF08\u542B\u9AD8\u901F\u7248\uFF09\uFF1A\u59CB\u7EC8\u601D\u8003\u2014\u2014thinking.type \u4EC5\u63A5\u53D7 enabled\uFF08\u4F20 disabled \u62A5\u9519\uFF09\uFF0C\u65E0 Off \u6863\uFF1B\u5E26\u89C6\u89C9\uFF0C256K\u3002',\n },\n {\n id: 'kimi-for-coding',\n // 2026-10 calibration NEW entry: pi-ai 1.2.0 keys kimi-for-coding on\n // anthropic-messages with a four-rung map (off omit-expressed, then\n // low/high/max) plus forceAdaptiveThinking -- Moonshot's coding\n // endpoint speaks the Anthropic shape, not the deepseek thinking.type\n // switch the K2 line uses. -highspeed twin has NO tlm (no effort\n // control); 1M in / 32,768 out, vision.\n patterns: ['kimi-for-coding'],\n efforts: { low: 'low', high: 'high', max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 32_768,\n note: 'Kimi for Coding\uFF1AMoonshot \u7F16\u7801\u4E13\u7EBF\u8D70 anthropic-messages \u534F\u8BAE\u3001\u81EA\u9002\u5E94\u601D\u8003\uFF0C\u6863\u4F4D Low / High / Max\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF1B\u5E26\u56FE\u8F93\u5165\uFF0C1M \u4E0A\u4E0B\u6587 / 32,768 \u8F93\u51FA\u3002\u9AD8\u901F\u7248\uFF08-highspeed\uFF09\u65E0 effort \u63A7\u4EF6\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF09\u3002',\n },\n {\n id: 'kimi-moonshot-v1-vision',\n // Legacy Moonshot V1 vision variants (official model list): plain\n // generation models with no thinking control, but they DO accept images\n // -- the generic 'moonshot' pattern must not declare text-only for them.\n patterns: ['moonshot-v1-8k-vision', 'moonshot-v1-32k-vision', 'moonshot-v1-128k-vision'],\n efforts: false,\n input: ['text', 'image'],\n note: 'Moonshot V1 \u89C6\u89C9\u65E7\u4EE3\uFF088k/32k/128k \u5404\u4E00\uFF09\uFF1A\u65E0\u601D\u8003\u63A7\u4EF6\uFF08\u751F\u6210\u6A21\u578B\uFF09\u3001\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF1B\u8BE5\u7EBF\u5DF2\u505C\u6B62\u5BF9\u65B0\u7528\u6237\u5F00\u653E\uFF082026-08-31 \u5168\u91CF\u4E0B\u7EBF\uFF0C\u7F51\u5173\u6B8B\u7559\u4ECD\u53EF\u547D\u4E2D\uFF09\u3002',\n },\n {\n id: 'kimi',\n // k2.5/2.6 use the DeepSeek-shaped thinking.type enabled/disabled\n // switch, which the 'deepseek' format dispatches; the old k2 preview\n // ids and moonshot-v1 names are retired upstream (2026-05/08) but live\n // on gateways. Effort ladders are not part of their contract.\n patterns: ['kimi', 'moonshot'],\n efforts: { off: null, high: 'high' },\n compat: { thinkingFormat: 'deepseek' },\n input: ['text'],\n contextWindow: 262_144,\n note: 'Kimi \u901A\u7528\uFF1Athinking \u5F00\u5173\uFF08\u65E0 effort \u6863\uFF09\uFF0C\u5F00=High\u3002k2 \u7CFB\u5217 2026-05-25 \u4E0B\u7EBF\u3001kimi-latest 2026-01-28 \u4E0B\u7EBF\u3001moonshot-v1 \u7CFB 2026-08-31 \u5168\u91CF\u4E0B\u7EBF\uFF08\u7F51\u5173\u6B8B\u7559\u4ECD\u53EF\u547D\u4E2D\uFF1Bmoonshot-v1 \u672C\u8EAB\u975E\u601D\u8003\u6A21\u578B\uFF09\u3002\u89C6\u89C9\u4EE3\u4E0E K2.7 Code \u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'hunyuan-hy3',\n // Open-weight contract (Tencent-Hunyuan/Hy3 README): reasoning_effort\n // travels inside chat_template_kwargs as \"no_think\" (default) / \"low\" /\n // \"high\"; the same README's spec table states a 256K context length.\n patterns: ['hy3'],\n efforts: { low: 'low', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 262_144,\n note: '\u6DF7\u5143 hy3\uFF1A\u5F00\u6E90\u5951\u7EA6\u7ECF chat_template_kwargs.reasoning_effort = no_think(\u9ED8\u8BA4)/low/high\uFF1B\u5B98\u65B9\u6A21\u578B\u5361 256K \u4E0A\u4E0B\u6587\uFF08295B MoE\uFF0C2026 \u5F00\u6E90\uFF09\u3002',\n },\n {\n id: 'hunyuan-hy4',\n // Open-weight contract (Tencent-Hunyuan/Hy4-preview README): reasoning\n // defaults to \"high\" (deep chain-of-thought) and is disabled with\n // extra_body={\"chat_template_kwargs\": {\"reasoning_effort\": \"no_think\"}}\n // \u2014 the same chat-template channel as hy3, with the default flipped to\n // high. The spec table states a 1M context length; the model is a\n // 770B-A49B MoE with Gated DSA attention. The README documents no levels\n // beyond high/no_think, so a low rung is NOT declared without evidence.\n patterns: ['hy4-preview', 'hy-4-preview'],\n efforts: { off: 'no_think', high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n contextWindow: 1_000_000,\n note: '\u6DF7\u5143 Hy4 preview\uFF1A\u5B98\u65B9 README\u2014\u2014reasoning \u9ED8\u8BA4 high\uFF08\u6DF1\u5EA6\u601D\u8003\uFF09\uFF0C\u5173\u95ED\u7ECF chat_template_kwargs.reasoning_effort=no_think\uFF1B\u5B98\u65B9\u89C4\u683C\u8868 1M \u4E0A\u4E0B\u6587\uFF08770B-A49B MoE\uFF0CGated DSA\uFF09\u3002low \u6863\u5B98\u65B9\u672A\u5217\uFF0C\u5982\u6709\u8BF7\u624B\u8C03\uFF1B\u89C6\u89C9\u672A\u58F0\u660E\uFF0C\u6309\u9700\u624B\u52FE\u3002\u6765\u6E90\uFF1ATencent-Hunyuan/Hy4-preview \u5B98\u65B9 README\u3002',\n },\n {\n id: 'step-5-preview',\n // StepFun's official model is 'step-5-preview' (there is no bare\n // 'step-5'), carrying the same three-step reasoning_effort ladder as the\n // 3.x line with no way to close thinking -- hence no `off`. The official\n // page calls medium the \"default recommendation\". 1M context, 64K max\n // output, native image + video input.\n patterns: ['step-5'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 65_536,\n note: '\u9636\u8DC3 Step-5-Preview\uFF08\u5B98\u65B9 id \u5373 step-5-preview\uFF0C\u65E0\u88F8 step-5\uFF1Bpattern \u53D6\u5BB6\u65CF\u4E3B\u5E72\u4EE5\u517C\u5BB9\u7F51\u5173\u5199\u6CD5\uFF09\uFF1A\u6863\u4F4D Low / Medium(\u5B98\u65B9\u6807\"\u9ED8\u8BA4\u63A8\u8350\") / High\uFF0C\u601D\u8003\u4E0D\u53EF\u5173\u95ED\uFF1B\u539F\u751F\u56FE\u7247 + \u89C6\u9891\u8F93\u5165\uFF1B1M \u4E0A\u4E0B\u6587\u300164K \u6700\u5927\u8F93\u51FA\uFF08\u5B98\u65B9\u53E6\u6CE8 max_tokens \u9ED8\u8BA4 INF\u3001\u4E0E 64K \u4E0A\u9650\u5E76\u5B58\uFF0C\u4EE5\u7AEF\u70B9\u5B9E\u6D4B\u4E3A\u51C6\uFF09\u3002',\n },\n {\n id: 'step-3-7',\n // StepFun step-3.7 is the vision-capable generation; 3.5 stayed\n // text-only on the official serving plan.\n patterns: ['step-3.7', 'step-3.6'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: '\u9636\u8DC3 Step-3.6/3.7 \u6863\u4F4D\uFF1ALow / Medium(\u9ED8\u8BA4\u63A8\u8350) / High\uFF0C\u539F\u751F\u56FE\u7247+\u89C6\u9891\u7406\u89E3\u3002\u4E0A\u4E0B\u6587\u4E3A\u8F93\u5165+\u8F93\u51FA\u603B\u548C\u4E0A\u9650\u3002',\n },\n {\n id: 'step-3-5',\n // step-3.5-flash (official listing): only low/high, text-only.\n patterns: ['step-3.5'],\n efforts: { low: 'low', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 262_144,\n note: '\u9636\u8DC3 Step-3.5 Flash \u6863\u4F4D\uFF1ALow / High\uFF08\u7EAF\u6587\u672C\u63A8\u7406\u65D7\u8230\uFF09\u3002\u4E0A\u4E0B\u6587\u4E3A\u8F93\u5165+\u8F93\u51FA\u603B\u548C\u4E0A\u9650\u3002',\n },\n {\n id: 'step',\n // StepFun step-3.x: reasoning_effort low/medium/high (default medium);\n // thinking cannot be turned off, only tuned.\n patterns: ['step-3', 'step-2'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n note: '\u9636\u8DC3 Step \u6863\u4F4D\uFF1ALow / Medium / High\uFF08\u9ED8\u8BA4 Medium\uFF0C\u4E0D\u53EF\u5173\u95ED\uFF09\u30023.6/3.7 \u89C6\u89C9\u4EE3\u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'doubao',\n // Volcengine Ark: officially documented is the thinking.type\n // enabled/disabled/auto switch; the reasoning_effort ladder on\n // seed-2.x has community evidence (chatbox/compshare) but no first-\n // party doc yet -- kept as the conventional ladder, verify per gateway.\n // 'doubao' already covers every doubao-* spelling; the bare 'seed' token\n // (boundary-checked) catches seed-first ids some gateways serve. The\n // seed generations are vision-capable; doubao-1.5-pro stays text-only.\n patterns: ['doubao', 'seed'],\n efforts: { off: null, low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n note: '\u8C46\u5305\u6863\u4F4D\uFF1AOff / Low / Medium / High\u2014\u2014effort \u9636\u68AF\u4ECD\u662F\u793E\u533A\u8BC1\u636E\u3001\u5B98\u65B9 Ark \u6587\u6863\u660E\u5217\u7684\u4E3A thinking.type \u5F00\u5173\uFF082026-08-24 \u590D\u6838\u4ECD\u672A\u89C1\u5230 effort \u5B98\u65B9\u660E\u6587\uFF09\u3002seed \u4EE3\u6536\u56FE\uFF081.5-pro \u4F8B\u5916\uFF09\u3002',\n },\n {\n id: 'minimax-m2',\n // 2026-10 calibration NEW entry: pi-ai 1.2.0 keys MiniMax-M2.5 (and the\n // M2 line) with NO thinkingLevelMap and supportsReasoningEffort:false\n // on the anthropic-messages protocol -- unlike M3 below, the M2\n // generation predates the thinking parameter entirely. `false` keeps\n // auto-adapt from handing it the M3 declaration. Text-only;\n // 204,800 in / 131,072 out.\n patterns: ['minimax-m2'],\n efforts: false,\n input: ['text'],\n contextWindow: 204_800,\n maxTokens: 131_072,\n note: 'MiniMax-M2 / M2.5\uFF08\u542B -highspeed\uFF09\uFF1A\u65E0\u601D\u8003\u63A7\u4EF6\u3001\u65E0 effort \u53C2\u6570\uFF08M3 \u624D\u5F15\u5165 thinking \u53C2\u6570\uFF09\uFF0C\u7EAF\u6587\u672C\uFF0C204,800 / 131,072\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF1BM3 \u89C1\u4E0B\u6761\uFF09\u3002',\n },\n {\n id: 'minimax-m3',\n // Official M3 README: a thinking parameter with enabled / adaptive /\n // disabled -- NO reasoning_effort ladder. That is exactly the\n // deepseek-shaped toggle, so the kimi-style declaration fits; \"adaptive\"\n // is not expressible in the level vocabulary and defaults apply.\n // 2026-10 calibration adds the catalog's 512,000 output cap.\n patterns: ['minimax-m3'],\n efforts: { off: null, high: 'high' },\n compat: { thinkingFormat: 'deepseek' },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 512_000,\n note: 'MiniMax-M3\uFF1A\u5B98\u65B9 thinking \u53C2\u6570 enabled/adaptive/disabled\uFF08\u65E0 effort \u6863\uFF09\uFF0C\u5F00=High\u3001\u5173=disabled\uFF1B\u539F\u751F\u591A\u6A21\u6001\uFF08\u56FE/\u89C6\u9891\uFF0C\u6838\u5FC3\u8BCD\u8868\u4EC5\u542B\u56FE\uFF09\uFF0C1M \u4E0A\u4E0B\u6587 / 512,000 \u8F93\u51FA\uFF082026-10 \u6821\u51C6\u8865\u5BB9\u91CF\uFF09\u3002',\n },\n {\n id: 'mimo-v2-6',\n // Xiaomi MiMo v2.6 (and the v2.5 generation it supersedes) takes a required\n // thinking.type toggle (enabled/disabled, default enabled) plus a required\n // reasoning.effort. The official page lists the accepted effort values as\n // none/minimal/low/medium/high/xhigh/max/ultra and normalizes minimal to\n // low and xhigh/max/ultra to high -- but says outright that reasoning\n // strength is not differentiated yet, so the ladder below is what the\n // endpoint ACCEPTS, not a set of levels that behave differently today.\n // xhigh/max are deliberately absent: the endpoint folds them into high.\n // One entry covers both generations: the same models are documented under\n // one contract, and the family's only text-only member (v2.5-pro) keys its\n // own entry with a strictly longer pattern.\n patterns: ['mimo-v2.6', 'mimo-v2.5'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: '\u5C0F\u7C73 MiMo v2.6 \u7CFB\u5217\uFF08mimo-v2.6-pro / -flash / -pro-ultraspeed\uFF1B1M \u4E0A\u4E0B\u6587 / 128K \u6700\u5927\u8F93\u51FA\u3001\u539F\u751F\u5168\u6A21\u6001\uFF09\u4E0E\u5176\u524D\u4EE3 mimo-v2.5\u3002\u5B98\u65B9\u6587\u6863\uFF1Athinking.type\uFF08enabled/disabled\uFF0C\u9ED8\u8BA4 enabled\uFF09+ reasoning.effort\uFF08none \u5173\u95ED\uFF1B\u5176\u4F59\u5408\u6CD5\u503C\u5747\u5F00\u542F\uFF0C\u4E14**\u73B0\u9636\u6BB5\u6682\u672A\u533A\u5206\u63A8\u7406\u5F3A\u5EA6**\u2014\u2014minimal \u5F52\u4E00\u4E3A low\u3001xhigh/max/ultra \u5F52\u4E00\u4E3A high\uFF09\uFF0C\u56E0\u6B64\u8FD9\u91CC\u58F0\u660E\u7684\u662F\u7AEF\u70B9**\u63A5\u53D7**\u7684\u6863\u4F4D Off / Low / Medium / High\uFF08xhigh\u3001max \u4E0D\u58F0\u660E\uFF0C\u7AEF\u70B9\u53EA\u4F1A\u6298\u53E0\u4E3A high\uFF09\u3002\u601D\u8003\u6A21\u5F0F\u4E0B temperature / top_p \u4E0D\u53EF\u81EA\u5B9A\u4E49\uFF08\u5F3A\u5236 1.0 / 0.95\uFF09\uFF1B\u5E26\u5DE5\u5177\u8C03\u7528\u7684\u5386\u53F2\u8F6E\u5FC5\u987B\u5B8C\u6574\u56DE\u4F20 reasoning_content\uFF0C\u5426\u5219 400\u3002mimo-v2.5 \u4E0E v2.5-pro \u5B98\u65B9\u5B9A\u4E8E 2026-10-21 \u4E0B\u7EBF\u3002',\n },\n {\n id: 'mimo-v2-5-pro',\n // The v2.5 flagship is the family's only text-only member -- the official\n // capability table lists no multimodal understanding for it (models.dev\n // agrees, attachment=false), while every v2.6 model and mimo-v2.5 do.\n // Strictly longer pattern than the family entry's 'mimo-v2.5', so the\n // longest-hit rule routes it here.\n patterns: ['mimo-v2.5-pro'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: '\u5C0F\u7C73 MiMo v2.5-Pro\uFF1A\u8BE5\u5BB6\u65CF\u552F\u4E00\u7684**\u7EAF\u6587\u672C**\u6210\u5458\uFF08\u5B98\u65B9\u80FD\u529B\u8868\u672A\u5217\u5168\u6A21\u6001\u7406\u89E3\uFF09\uFF0C1M \u4E0A\u4E0B\u6587 / 128K \u6700\u5927\u8F93\u51FA\uFF0C\u63A8\u7406\u5951\u7EA6\u4E0E v2.6 \u7CFB\u5217\u76F8\u540C\uFF08thinking.type + reasoning.effort\uFF0Cnone \u5173\u95ED\u3001\u5176\u4F59\u6863\u4F4D\u6682\u4E0D\u533A\u5206\u5F3A\u5EA6\uFF09\u3002\u5B98\u65B9\u5B9A\u4E8E 2026-10-21 \u4E0B\u7EBF\u3002',\n },\n {\n id: 'baidu-ernie',\n // Baidu Qianfan's OpenAI-compatible surface accepts no reasoning_effort\n // parameter (the v2 API parameter tables carry none); thinking is a\n // per-variant property: the -Thinking / ERNIE 5.0-Thinking-* family is\n // always-on thinking, the plain ERNIE 4.5/5.0/5.1 generations are not\n // thinking models at all. The official pricing page (2026-08) lists\n // ERNIE 5.1 / 5.0 / 5.0-Thinking-Preview|Latest|Exp / 4.5-Turbo(-VL).\n patterns: ['ernie'],\n efforts: false,\n input: ['text'],\n contextWindow: 131_072,\n note: '\u767E\u5EA6\u5343\u5E06 ERNIE \u7CFB\uFF1A\u5B98\u65B9 OpenAI \u517C\u5BB9\u63A5\u53E3\u65E0 reasoning_effort \u53C2\u6570\u2014\u2014\u601D\u8003\u7531\u6A21\u578B\u53D8\u4F53\u51B3\u5B9A\uFF08-Thinking \u7CFB\u5217\u59CB\u7EC8\u601D\u8003\u3001\u666E\u901A\u7CFB\u5217\u4E0D\u601D\u8003\uFF09\uFF0C\u52FF\u52FE\u601D\u8003\u6863\u3002ERNIE 4.5 Turbo VL \u652F\u6301\u56FE\u7247\uFF0C\u6309\u9700\u624B\u52FE\uFF1B\u53C2\u8003\u5BB9\u91CF\u53D6 Turbo 128K \u6863\u3002',\n },\n {\n id: 'fireworks-ember',\n // 2026-10 calibration NEW entry: Fireworks' ember-1 keys on\n // anthropic-messages in pi-ai 1.2.0 with a five-rung map (off spelled\n // 'none') plus forceAdaptiveThinking/allowEmptySignature -- a relay\n // model that genuinely dispatches output_config.effort. Vision;\n // 1,048,576 in / 131,072 out.\n patterns: ['ember-1'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: 'Fireworks ember-1\uFF1Aanthropic-messages \u534F\u8BAE\u81EA\u9002\u5E94\u601D\u8003\uFF0C\u6863\u4F4D None(\u5173) / Low / Medium / High / Max\uFF08off \u663E\u5F0F none \u62FC\u5199\uFF09\uFF1B\u5E26\u56FE\u8F93\u5165\uFF0C1M \u4E0A\u4E0B\u6587 / 131,072 \u8F93\u51FA\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF09\u3002',\n },\n {\n id: 'thinkingmachines-inkling',\n // 2026-10 calibration NEW entry: pi-ai 1.2.0 keys inkling (Thinking\n // Machines) with the FULL seven-rung ladder incl. explicit max, vision,\n // 524,288 in / 131,072 out. On together.ai the relay exposes\n // supportsReasoningEffort:false -- the ladder below still keys the\n // model name first; relays that forward it accept the rungs.\n patterns: ['inkling'],\n efforts: {\n off: 'none', minimal: 'minimal', low: 'low', medium: 'medium',\n high: 'high', xhigh: 'xhigh', max: 'max',\n },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 524_288,\n maxTokens: 131_072,\n note: 'Thinking Machines Inkling\uFF1A\u5168\u6863 Minimal / Low / Medium(\u9ED8\u8BA4) / High / XHigh / Max\uFF0Coff \u663E\u5F0F none\uFF1B\u5E26\u56FE\u8F93\u5165\uFF0C512K \u4E0A\u4E0B\u6587 / 131,072 \u8F93\u51FA\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF1Btogether \u4E2D\u7EE7\u4FA7 effort \u53C2\u6570\u672A\u5F00\u653E\uFF0C\u9700\u652F\u6301\u65B9\u8F6C\u53D1\uFF09\u3002',\n },\n {\n id: 'antling-ring',\n // 2026-10 calibration NEW entry: Ant Ling's Ring-2.6-1T takes a\n // two-rung map (high/xhigh) with off omit-expressed; Ling-2.6(-flash)\n // is r=false (non-reasoning) and keys the second entry. 262,144 in /\n // 65,536 out per pi-ai 1.2.0.\n patterns: ['ring-2.6'],\n efforts: { high: 'high', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 262_144,\n maxTokens: 65_536,\n note: '\u8682\u8681 Ling Ring-2.6-1T\uFF1A\u6863\u4F4D High / XHigh\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF1B262,144 / 65,536\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF09\u3002',\n },\n {\n id: 'antling-ling',\n // 2026-10 calibration NEW entry: Ling-2.6-1T / Ling-2.6-flash are\n // non-reasoning (r=false, no tlm in pi-ai 1.2.0) -- declared false so\n // auto-adapt does not hand them the Ring ladder.\n patterns: ['ling-2.6'],\n efforts: false,\n input: ['text'],\n note: '\u8682\u8681 Ling-2.6\uFF08\u542B -flash\uFF09\uFF1A\u975E\u601D\u8003\u6A21\u578B\uFF0C\u65E0 effort \u63A7\u4EF6\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF1BRing-2.6 \u601D\u8003\u7EBF\u89C1\u4E0A\u6761\uFF09\u3002',\n },\n]\n\n/**\n * The generic OpenAI-compatible ladder -- the single source for every\n * OpenAI-shaped protocol row below and the fallback when nothing matches.\n */\nexport const GENERIC_OPENAI_EFFORTS: ReasoningEfforts = {\n off: null,\n low: 'low',\n medium: 'medium',\n high: 'high',\n}\n\n/**\n * Level sets keyed by pi-ai's REAL wire protocols -- the only values a\n * route's 'api' may take are 'openai-completions' | 'openai-responses' |\n * 'anthropic-messages' (llm-pi-ai provider.ts PROTOCOLS) -- plus the\n * 'deepseek' URL dialect for routes that name no api but point at DeepSeek's\n * own endpoint, which takes its native off/high/max ladder.\n *\n * 'off: null' is only offered where a no-thinking mode is plausible; the\n * conservative choice elsewhere is to omit it so the picker never promises an\n * Off the endpoint would reject. Exported for the vocabulary grid tests that\n * pin these ladders against pi-ai's resolution rules.\n */\nexport const PROTOCOL_INFERENCE: Readonly<Record<string, ReasoningEfforts>> = {\n 'openai-completions': GENERIC_OPENAI_EFFORTS,\n 'openai-responses': GENERIC_OPENAI_EFFORTS,\n 'anthropic-messages': GENERIC_OPENAI_EFFORTS,\n // The live V4 contract: low/high/max (+ thinking toggle for off, spelled\n // 'none' so an off selection also maps to the official Responses-API value\n // reasoning.effort: none).\n deepseek: { off: 'none', low: 'low', high: 'high', max: 'max' },\n}\n\n/** A best-effort generic declaration when even the protocol is unknown. */\nconst GENERIC_FALLBACK: ReasoningEfforts = { low: 'low', medium: 'medium', high: 'high' }\n\n/** Normalize one route fact for matching/inference. */\nfunction normalize(value: string | undefined): string {\n return (value ?? '').toLowerCase().trim()\n}\n\n/** Whether a character is a lowercase letter or digit (word-boundary test). */\nfunction isAlnum(ch: string | undefined): boolean {\n return ch !== undefined && /[a-z0-9]/.test(ch)\n}\n\n/**\n * Lowercase and collapse every non-alphanumeric run to one space, so id /\n * display-name / pattern separators ('-', '_', '.', spaces) compare equal:\n * pattern 'deepseek-v3' matches display name \"DeepSeek V3\".\n */\nfunction normalizeLoose(value: string): string {\n return value.toLowerCase().trim().replace(/[^a-z0-9]+/g, ' ')\n}\n\n/**\n * Whether the occurrence of a pattern at index 'at' sits on a word boundary\n * in the haystack: neither neighbor may be a letter/digit. Keeps short family\n * tokens from false-hitting ('o1' must hit 'o1 mini' but not 'ko1 pro';\n * 'seed' hits 'doubao seed 1 6' but not 'seedling').\n */\nfunction onBoundary(haystack: string, at: number, length: number): boolean {\n const before = at === 0 ? undefined : haystack[at - 1]\n const after = haystack[at + length]\n return !isAlnum(before) && !isAlnum(after)\n}\n\n/** Match the knowledge base: first match wins, longest boundary hit wins. */\nexport function matchKnowledgeBase(modelId: string, displayName?: string): KnowledgeEntry | undefined {\n const haystack = normalizeLoose(modelId) + ' ' + normalizeLoose(displayName ?? '')\n let best: { entry: KnowledgeEntry; length: number } | undefined\n for (const entry of KNOWLEDGE_BASE) {\n for (const pattern of entry.patterns) {\n const needle = normalizeLoose(pattern)\n let at = haystack.indexOf(needle)\n while (at >= 0) {\n if (onBoundary(haystack, at, needle.length)) {\n if (best === undefined || needle.length > best.length) {\n best = { entry, length: needle.length }\n }\n break\n }\n at = haystack.indexOf(needle, at + 1)\n }\n }\n }\n return best?.entry\n}\n\n/**\n * Infer which PROTOCOL_INFERENCE key applies to a route. A configured 'api'\n * is already a pi-ai protocol name and wins as-is; otherwise the endpoint's\n * HOST names the dialect -- matched on the registrable domain so an aggregator\n * path like https://gw.example.com/deepseek/v1 stays generic -- and anything\n * unrecognized resolves to the OpenAI-compatible ladder (the overwhelming\n * majority of gateways).\n */\nconst NATIVE_DIALECT_DOMAINS: Readonly<Record<string, string>> = {\n // api.deepseek.com is the official endpoint (api-docs.deepseek.com). The\n // 'deepseek.ai' form was dropped: it resolves to a Vercel-hosted site\n // (76.76.21.21), not DeepSeek infrastructure, so nothing warrants assuming\n // the native dialect for it.\n 'deepseek.com': 'deepseek',\n 'anthropic.com': 'anthropic-messages',\n}\n\nexport function inferProtocol(route: RouteFacts): string {\n const api = normalize(route.api)\n if (api.length > 0) return api\n const baseURL = route.baseURL\n if (baseURL !== undefined && baseURL.length > 0) {\n try {\n const host = new URL(baseURL).hostname.toLowerCase()\n const parts = host.split('.')\n if (parts.length >= 2) {\n const dialect = NATIVE_DIALECT_DOMAINS[parts.slice(-2).join('.')]\n if (dialect !== undefined) return dialect\n }\n } catch {\n // Malformed URL: fall through to the generic ladder.\n }\n }\n // Former 'gemini' guessing removed: pi-ai has no gemini protocol, and\n // Gemini gateways speak the OpenAI-compatible dialect.\n return 'openai-completions'\n}\n\n/**\n * The one wire protocol whose compat gate offers thinkingFormat /\n * supportsReasoningEffort (llm-pi-ai COMPLETIONS_COMPAT_GATE). pi-ai refuses\n * a model-level compat field its resolved protocol does not take\n * (assertServiceable throws at the write), so compat suggestions are gated to\n * this protocol only -- with one exception: the anthropic-messages gate\n * offers forceAdaptiveThinking, which is what makes declared efforts reach\n * the wire as output_config.effort (see {@link KnowledgeEntry.anthropicAdaptive}).\n */\nconst COMPAT_CAPABLE_PROTOCOL = 'openai-completions'\nconst ANTHROPIC_PROTOCOL = 'anthropic-messages'\n\n/** Whether a baseURL names a self-hosted endpoint (loopback, private LAN, .local, custom port). */\nexport function isSelfHostedEndpoint(baseURL: string | undefined): boolean {\n if (baseURL === undefined || baseURL.length === 0) return false\n let host = ''\n try {\n host = new URL(baseURL).hostname.toLowerCase()\n } catch {\n return false\n }\n if (host === 'localhost' || host === '::1' || host.endsWith('.local') || host.endsWith('.internal')) return true\n if (/^(127\\.|10\\.|192\\.168\\.)/.test(host)) return true\n if (/^172\\.(1[6-9]|2[0-9]|3[01])\\./.test(host)) return true\n return host.includes(':')\n}\n\n/**\n * Drop catalog-withheld keys pi-ai never accepts from a profile (defensive).\n *\n * openai-responses now falls through to `undefined`: the plugin suggests no\n * compat field on that gate since its max_output_tokens control was retired, so\n * such a profile keeps exactly what it already stores.\n */\nexport function sanitizeCompatForProtocol(compat: CompatSuggestion, api: string): CompatSuggestion | undefined {\n const norm = normalize(api)\n const copy: Record<string, unknown> = { ...compat }\n delete copy['supportsMidConvoEffort']\n delete copy['allowedFallbackModels']\n if (norm === ANTHROPIC_PROTOCOL) {\n for (const key of ['thinkingFormat', 'supportsReasoningEffort', 'thinkingTokenBudgetField', 'supportsThinkingTokenBudget', 'vllmPriority'] as const) delete copy[key]\n if (copy['forceAdaptiveThinking'] === undefined) return undefined\n return { forceAdaptiveThinking: copy['forceAdaptiveThinking'] as boolean }\n }\n if (norm !== COMPAT_CAPABLE_PROTOCOL) return undefined\n delete copy['forceAdaptiveThinking']\n return Object.keys(copy).length === 0 ? undefined : (copy as CompatSuggestion)\n}\n\n/** Gate a compat block against the route's real protocol. */\nfunction compatForRoute(entry: KnowledgeEntry, route: RouteFacts): CompatSuggestion | undefined {\n const api = normalize(route.api)\n if (api === COMPAT_CAPABLE_PROTOCOL) {\n let compat = entry.compat\n if (compat !== undefined) compat = sanitizeCompatForProtocol(compat, api) ?? undefined\n if (compat === undefined && !isSelfHostedEndpoint(route.baseURL)) return undefined\n if (compat === undefined) return { thinkingTokenBudgetField: 'thinking_token_budget' }\n if (compat.thinkingTokenBudgetField === undefined && compat.supportsThinkingTokenBudget !== true && isSelfHostedEndpoint(route.baseURL)) {\n return { ...compat, thinkingTokenBudgetField: 'thinking_token_budget' }\n }\n return compat\n }\n if (api === ANTHROPIC_PROTOCOL && entry.anthropicAdaptive === true) {\n return { forceAdaptiveThinking: true }\n }\n return undefined\n}\n\n/**\n * Official endpoint roots where pi-ai may send role:developer, so no pin is\n * needed. Matching is a DNS-suffix match, so multi-level roots (e.g.\n * openai.azure.com) work while a relay merely hosted on the same cloud\n * (e.g. *.cloudapp.azure.com) still counts as self-hosted.\n *\n * Deliberately fail-safe: hosts outside this set get the pin. `system` is\n * accepted everywhere, `developer` is not, so an unknown host keeps the\n * universally accepted role -- the pin is harmless on official endpoints\n * too. Only add a root after verifying its endpoints accept\n * role:developer (vendor docs or a wire capture); when in doubt, leave it\n * out. The pi-ai-parity entries change no bytes (pi-ai already detects\n * those hosts as nonstandard, i.e. supportsDeveloperRole false); they are\n * listed so the two detectors cannot drift apart silently.\n */\nconst OFFICIAL_RELAY_DOMAINS: readonly string[] = [\n // First-party OpenAI-compatible endpoints (developer accepted).\n 'openai.com',\n 'openai.azure.com',\n 'deepseek.com',\n 'openrouter.ai',\n 'z.ai',\n 'bigmodel.cn',\n 'moonshot.ai',\n 'moonshot.cn',\n 'aliyuncs.com',\n 'anthropic.com',\n 'x.ai',\n 'together.ai',\n 'together.xyz',\n 'nvidia.com',\n 'cerebras.ai',\n 'cloudflare.com',\n // pi-ai-parity: detected nonstandard upstream (pin would be a no-op).\n 'chutes.ai',\n 'opencode.ai',\n 'ant-ling.com',\n]\n\n/**\n * Whether a route is a self-hosted relay whose upstreams cannot be assumed\n * to accept role:developer: openai-completions protocol on a baseURL whose\n * host no official root claims. Absent or malformed URLs answer false --\n * with nothing to judge the host by, pi-ai's detection default stands.\n */\nexport function isSelfHostedRelay(route: RouteFacts): boolean {\n if (normalize(route.api) !== COMPAT_CAPABLE_PROTOCOL) return false\n const baseURL = route.baseURL\n if (baseURL === undefined || baseURL.length === 0) return false\n try {\n const host = new URL(baseURL).hostname.toLowerCase()\n if (!host.includes('.')) return false\n return !OFFICIAL_RELAY_DOMAINS.some((root) => host === root || host.endsWith('.' + root))\n } catch {\n return false\n }\n}\n\n/**\n * Pin the system role on self-hosted relays: merge\n * `supportsDeveloperRole: false` into a compat block that would otherwise\n * let pi-ai rewrite the system prompt to role:developer (issue #2 -- the\n * upstream answers \u89D2\u8272\u4FE1\u606F\u4E0D\u6B63\u786E). An explicitly declared value always\n * wins; non-reasoning suggestions (efforts === false) never carry compat.\n */\nfunction withRolePin(\n compat: CompatSuggestion | undefined,\n route: RouteFacts,\n reasons: boolean,\n): CompatSuggestion | undefined {\n if (compat === undefined || !reasons) return compat\n if (compat.supportsDeveloperRole !== undefined) return compat\n if (!isSelfHostedRelay(route)) return compat\n return { ...compat, supportsDeveloperRole: false }\n}\n\n/** Conservative ladder offered when the endpoint confirms reasoning but nothing names the levels. */\nconst ENDPOINT_CONFIRMED_LADDER: ReasoningEfforts = { off: null, low: 'low', medium: 'medium', high: 'high' }\n\n/**\n * Name-heuristic modality tokens -- the last-resort tier (the practice\n * one-api/new-api bake into code): vision-flavored tokens that appear in\n * vendor ids often enough to suggest image input at LOW confidence. Boundary\n * matching keeps 'vl' from hitting 'eval' or 'svelte'.\n */\nconst VISION_NAME_TOKENS: readonly string[] = [\n 'vl',\n 'vision',\n 'omni',\n '4o',\n 'pixtral',\n 'internvl',\n]\n\n/** Lowest-confidence modality guess from the model id alone, or undefined. */\nexport function inferModalitiesFromName(modelId: string): InputModalities | undefined {\n const haystack = normalizeLoose(modelId)\n for (const token of VISION_NAME_TOKENS) {\n const needle = normalizeLoose(token)\n let at = haystack.indexOf(needle)\n while (at >= 0) {\n if (onBoundary(haystack, at, needle.length)) return ['text', 'image']\n at = haystack.indexOf(needle, at + 1)\n }\n }\n return undefined\n}\n\n/**\n * Intersect a raw listing disclosure with the core vocabulary. Returns\n * undefined when the listing never named a modality field OR named one whose\n * members all fall outside the core vocabulary (an audio-only declaration\n * must NOT read as \"text only\"). A present disclosure always yields at least\n * text-only when image is absent -- so an explicit text-only listing can\n * strip an image claim.\n */\nfunction declaredCoreInput(raw: readonly string[] | undefined): InputModalities | undefined {\n if (raw === undefined) return undefined\n const lowered = raw.map(value => value.toLowerCase())\n if (!lowered.some(value => (INPUT_MODALITIES as readonly string[]).includes(value))) return undefined\n return lowered.includes('image') ? ['text', 'image'] : ['text']\n}\n\n/**\n * Resolve the suggestion for one model on one route, fusing the available\n * signals by confidence:\n *\n * L1 endpoint listing signal (when supplied) -- answers \"does it reason at\n * all\" and, independently, \"what does it accept\": an explicit false\n * wins the effort ladder outright (suggest false, high); a modality\n * disclosure or a context length feeds those parts regardless;\n * L2 knowledge base -- the ONLY source of wire spellings and compat, plus\n * modality/capacity references when the endpoint stays silent;\n * L3 name heuristic -- a low-confidence image guess for vision-flavored\n * ids when both sources above are silent;\n * L4 protocol inference -- level-ladder skeleton when nothing better exists.\n *\n * @param modelId - the model id (or display name) to match.\n * @param route - route facts used when the knowledge base misses; its\n * displayName participates in knowledge-base matching.\n * @param endpoint - optional raw-listing facts for this model (from the\n * host's same-origin probe route); omit when the endpoint was not asked.\n * @returns a suggestion (always derivable -- protocol inference has a fallback).\n */\nexport function suggestEfforts(\n modelId: string,\n route: RouteFacts,\n endpoint?: EndpointFacts,\n): EffortSuggestion {\n const entry = matchKnowledgeBase(modelId, route.displayName)\n\n // ---- Modality + capacity parts (orthogonal to the effort ladder) ----\n let input: InputModalities | undefined\n let inputSource: InputSource | undefined\n let contextWindow: number | undefined\n let maxTokens: number | undefined\n\n if (entry?.input !== undefined) {\n input = entry.input\n inputSource = 'knowledge'\n }\n if (entry?.contextWindow !== undefined) contextWindow = entry.contextWindow\n if (entry?.maxTokens !== undefined) maxTokens = entry.maxTokens\n\n // An endpoint disclosure outranks the knowledge base; a disclosed context\n // length likewise replaces the reference value. Silence changes nothing.\n const listedInput = declaredCoreInput(endpoint?.input)\n if (listedInput !== undefined) {\n input = listedInput\n inputSource = 'endpoint'\n }\n if (endpoint?.contextLength !== undefined && Number.isFinite(endpoint.contextLength) && endpoint.contextLength > 0) {\n contextWindow = endpoint.contextLength\n }\n\n // L3: nothing named the modalities -- fall back to the name heuristic.\n if (input === undefined) {\n const guessed = inferModalitiesFromName(modelId)\n if (guessed !== undefined) {\n input = guessed\n inputSource = 'heuristic'\n }\n }\n\n const modalityParts = {\n ...(input === undefined ? {} : { input }),\n ...(inputSource === undefined ? {} : { inputSource }),\n ...(contextWindow === undefined ? {} : { contextWindow }),\n ...(maxTokens === undefined ? {} : { maxTokens }),\n }\n\n const endpointPart = endpoint === undefined\n ? {}\n : { endpoint: { reasoning: endpoint.reasoning, source: endpoint.source } }\n\n // L1: an explicit \"does not reason\" from the endpoint outranks everything.\n if (endpoint?.reasoning === false) {\n return {\n efforts: false,\n matched: false,\n source: 'endpoint:' + (endpoint.source ?? 'listing'),\n confidence: 'high',\n ...endpointPart,\n ...modalityParts,\n }\n }\n\n if (entry !== undefined) {\n const compat = withRolePin(compatForRoute(entry, route), route, entry.efforts !== false)\n return {\n efforts: entry.efforts,\n // The vendor default rides along only when the suggested ladder\n // actually carries it (a declaration may deliberately drop a level).\n ...(entry.efforts !== false\n && entry.defaultEffort !== undefined\n && entry.efforts[entry.defaultEffort] !== undefined\n ? { defaultEffort: entry.defaultEffort }\n : {}),\n ...(compat === undefined ? {} : { compat }),\n matched: true,\n entryId: entry.id,\n source: entry.id,\n // Knowledge base carries the wire values; an agreeing endpoint signal\n // only reinforces it. A DISAGREEING signal (endpoint says no reasoning)\n // was handled above; unknown changes nothing.\n confidence: 'high',\n ...endpointPart,\n ...modalityParts,\n }\n }\n\n // L2 missed: the ladder comes from protocol inference. An explicit endpoint\n // \"reasons\" upgrades confidence to medium -- support is confirmed, but the\n // level set and spellings are inferred, so the user should double-check.\n const protocol = inferProtocol(route)\n const efforts = PROTOCOL_INFERENCE[protocol] ?? GENERIC_FALLBACK\n const compatBase: CompatSuggestion | undefined = normalize(route.api) === COMPAT_CAPABLE_PROTOCOL\n ? { thinkingFormat: 'openai', supportsReasoningEffort: true }\n : undefined\n const compatWithBudget = compatBase !== undefined && isSelfHostedEndpoint(route.baseURL)\n ? { ...compatBase, thinkingTokenBudgetField: 'thinking_token_budget' as const }\n : compatBase\n const compat = withRolePin(compatWithBudget, route, true)\n if (endpoint?.reasoning === true) {\n return {\n efforts: { ...ENDPOINT_CONFIRMED_LADDER },\n ...(ENDPOINT_CONFIRMED_LADDER['medium'] !== undefined ? { defaultEffort: 'medium' as const } : {}),\n // compat was already gated to the protocol above; no second gate.\n ...(compat === undefined ? {} : { compat }),\n matched: false,\n source: 'endpoint:' + (endpoint.source ?? 'listing'),\n confidence: 'medium',\n ...endpointPart,\n ...modalityParts,\n }\n }\n return {\n efforts,\n // Inferred ladders default to medium (the convention codex/OpenAI set for\n // their own ladders) whenever the inferred set carries it.\n ...(efforts['medium'] !== undefined ? { defaultEffort: 'medium' as const } : {}),\n ...(compat === undefined ? {} : { compat }),\n matched: false,\n source: 'protocol:' + protocol,\n confidence: 'low',\n ...endpointPart,\n ...modalityParts,\n }\n}\n", "/**\n * Default-guard decision: which effort-less calls may take the vendor\n * default instead of the wire's off-equivalent (issue #2).\n *\n * Pi-ai always emits a thinking parameter for reasoning models, so an\n * effort-less call to a forced-thinking ladder (no `off` key) becomes\n * `thinking: {type: disabled}` / `enable_thinking: false` -- a guaranteed\n * 400 on upstreams that cannot switch thinking off. Rewriting exactly that\n * class into the ladder's vendor default produces bytes identical to the\n * user picking the level by hand, a request class that already works.\n *\n * Pure data logic (no harness imports): the host half feeds it the declared\n * ladder, the knowledge-base vendor default, and the route default, and\n * injects the returned level -- or nothing when it answers undefined.\n *\n * @module dsh-model-think-level/guard\n */\n\nimport type { ReasoningEfforts, ThinkingLevel } from './knowledge.js'\n\n/** Inputs to the guard decision, all optional except the declaration. */\nexport interface GuardInput {\n /** The model's declared ladder (`false` = non-reasoning). */\n declared: ReasoningEfforts | false | undefined\n /** The knowledge-base vendor default for the family, when one is known. */\n vendorDefault?: ThinkingLevel\n /** The route profile's configured reasoning default, when one is set. */\n profileDefault?: string\n /** The call's explicit effort, when the caller named one. */\n requested?: string\n}\n\n/**\n * The level to inject for an effort-less call, or undefined to pass through.\n * Refusals are silent and total: explicit selections, off-capable ladders,\n * undeclared/non-reasoning models, an explicit route default, and vendor\n * defaults outside the ladder all pass through untouched.\n */\nexport function resolveGuardEffort(input: GuardInput): string | undefined {\n if (input.requested !== undefined) return undefined\n const declared = input.declared\n if (declared === undefined || declared === false) return undefined\n if ('off' in declared) return undefined\n if (input.profileDefault !== undefined) return undefined\n const fallback = input.vendorDefault\n if (fallback === undefined || !(fallback in declared)) return undefined\n return fallback\n}\n", "/**\n * Shape guards and settings-dict readers shared by the host and browser\n * halves. Pure data logic only: esbuild inlines this module into both\n * bundles, so it must never import a harness package or touch DOM/node APIs.\n *\n * @module dsh-model-think-level/shared\n */\n\nimport type { RouteFacts } from './knowledge.js'\n\n/** Whether a value is a plain-ish object (not null, not an array). */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Whether a settings refusal reads like \"this kernel does not know the newer\n * compat keys\". The host autofill and the browser write path each downgrade\n * once on this signal, so they must answer identically.\n */\nexport function looksLikeCompatRefusal(message: string): boolean {\n const msg = message.toLowerCase()\n return msg.includes('compat')\n || msg.includes('thinkingtokenbudget')\n || msg.includes('vllmpriority')\n || msg.includes('supportsmaxoutput')\n}\n\n/** The models array of one route in a providers dict, as records. */\nexport function modelsOf(providers: unknown, route: string): Record<string, unknown>[] {\n if (!isRecord(providers)) return []\n const profile = providers[route]\n if (!isRecord(profile) || !Array.isArray(profile['models'])) return []\n return profile['models'].filter(isRecord)\n}\n\n/** One provider profile's route facts, as suggestion inference reads them. */\nexport function routeFactsOf(providers: unknown, route: string): RouteFacts {\n if (!isRecord(providers)) return {}\n const profile = providers[route]\n if (!isRecord(profile)) return {}\n const api = typeof profile['api'] === 'string' ? profile['api'] : undefined\n const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'] : undefined\n const displayName = typeof profile['displayName'] === 'string' ? profile['displayName'] : undefined\n return { api, baseURL, displayName }\n}\n", "/**\n * Provider request-header overlay, PURE half: the origin index and the header\n * value rules shared by the fetch-layer installer and the conflict report.\n *\n * Why this exists at all (issue #12): a route's `headers` dict can be merged or\n * overwritten by the official adapter's attribution headers, with `user-agent`\n * being the most visible case. A gateway that depends on any configured client\n * header therefore may not see the value stored in the profile. The overlay\n * reapplies the complete configured dictionary at the fetch layer, the last\n * public seam before the request reaches the wire.\n *\n * The index keeps every route's endpoint path and configured model ids. The URL\n * alone cannot distinguish two routes that share an origin, while an OpenAI-\n * compatible chat request carries the selected model in its JSON body. The\n * origin map remains as a backwards-compatible fallback for requests that do\n * not expose enough identity (for example a GET /models probe).\n *\n * @module dsh-model-think-level/headers-core\n */\n\nimport { isRecord } from './shared.js'\n\n/**\n * Upper bound on one header value the plugin will send. Fetch itself refuses\n * newline-bearing values (a header-injection guard); this plugin additionally\n * refuses anything unreasonable long rather than letting a paste of a whole\n * certificate turn every request into an upstream 400.\n */\nconst MAX_UA_LENGTH = 512\n\n/** One route's configured request headers and its fetch matching metadata. */\nexport interface HeaderOverride {\n /** `scheme://host:port` of the route's endpoint, exactly as Fetch would print it. */\n origin: string\n /** Normalized pathname prefix from the route's baseURL. */\n pathPrefix: string\n /**\n * The string header pairs to apply at the fetch layer. Empty when the route\n * declares none: the route still participates in matching, so a request that\n * clearly belongs to it is NOT given another route's headers.\n */\n headers: Record<string, string>\n /** The route key that declared them (diagnostics and UI labelling). */\n route: string\n /** Model IDs declared by this route, used to disambiguate shared endpoints. */\n modelIds: string[]\n /** The configured `user-agent`, retained for compatibility and diagnostics. */\n userAgent?: string\n /** Whether this route actually declares sendable request headers. */\n hasHeaders: boolean\n}\n\n/** Backwards-compatible name retained for callers that only knew the UA seam. */\nexport type UserAgentOverride = HeaderOverride\n\n/** A same-origin header disagreement that the URL-only fetch seam cannot disambiguate. */\nexport interface HeaderConflict {\n origin: string\n header: string\n routes: string[]\n values: string[]\n}\n\n/** The route index plus what could not be indexed or was ambiguous. */\nexport interface HeaderIndex {\n /** Every route with a usable endpoint, headers included or not. */\n routes: HeaderOverride[]\n /** Every route with sendable headers, retained for diagnostics and the UI. */\n overrides: HeaderOverride[]\n /** origin \u2192 first complete header override, used as a conservative fallback. */\n byOrigin: Map<string, HeaderOverride>\n /** Same-origin routes that declare different header values. */\n conflicts: { origin: string; routes: string[]; values: string[] }[]\n /** Same-origin disagreements for any configured header. */\n headerConflicts: HeaderConflict[]\n}\n\n/** Backwards-compatible name retained for the original public index contract. */\nexport type UserAgentIndex = HeaderIndex\n\n/** An empty index, for the \"no route declares headers\" case. */\nexport function emptyIndex(): HeaderIndex {\n return { routes: [], overrides: [], byOrigin: new Map(), conflicts: [], headerConflicts: [] }\n}\n\n/** The `scheme://host:port` of a URL string, or undefined when unparseable. */\nexport function originOf(url: string | undefined): string | undefined {\n if (url === undefined || url.trim().length === 0) return undefined\n try {\n return new URL(url).origin\n } catch {\n // A relative or malformed endpoint is not an origin this seam can match.\n return undefined\n }\n}\n\n/**\n * Whether a configured value can ride a Fetch `user-agent` field. Refused\n * rather than sanitized: a header carrying a newline is a request-splitting\n * hazard, and quietly rewriting the user's value would send something they\n * never asked for.\n * @param value - the configured header value.\n * @returns whether it is safe to `Headers.set()`.\n */\nexport function isSendableUserAgent(value: string): boolean {\n if (value.length === 0 || value.length > MAX_UA_LENGTH) return false\n // CR/LF and NUL are what Fetch's own guard rejects; refusing them here keeps\n // the refusal at configuration time instead of on every request.\n return !/[\\r\\n\\0]/.test(value)\n}\n\n/**\n * Whether a configured name/value pair can ride a Fetch header. Fetch is the\n * authority for the exact token grammar, so this accepts arbitrary legal names\n * instead of maintaining a brittle allow-list.\n */\nexport function isSendableHeader(name: string, value: string): boolean {\n if (name.length === 0) return false\n try {\n const headers = new Headers()\n headers.set(name, value)\n return true\n } catch {\n return false\n }\n}\n\n/** The `headers` dict of one route profile, as string pairs, or undefined. */\nexport function headersOf(profile: Record<string, unknown> | undefined): Record<string, string> | undefined {\n if (profile === undefined) return undefined\n const headers = profile['headers']\n if (!isRecord(headers)) return undefined\n const pairs: Record<string, string> = {}\n for (const [name, value] of Object.entries(headers)) {\n if (typeof value === 'string') pairs[name] = value\n }\n return Object.keys(pairs).length === 0 ? undefined : pairs\n}\n\n/**\n * The subset of a profile's headers that Fetch can send. An invalid stored\n * entry must not make the wrapper throw and break an otherwise valid request.\n */\nfunction sendableHeadersOf(profile: Record<string, unknown> | undefined): Record<string, string> | undefined {\n const headers = headersOf(profile)\n if (headers === undefined) return undefined\n const sendable: Record<string, string> = {}\n for (const [name, value] of Object.entries(headers)) {\n if (!isSendableHeader(name, value)) continue\n // Keep the historical UA guard: it avoids sending a malformed or\n // unexpectedly huge client identity while leaving every other legal header\n // available to the arbitrary-header editor.\n if (name.toLowerCase() === 'user-agent' && !isSendableUserAgent(value)) continue\n sendable[name] = value\n }\n return Object.keys(sendable).length === 0 ? undefined : sendable\n}\n\n/**\n * The `user-agent` a route's `headers` dict declares, case-insensitively.\n *\n * A `user-agent` stored here is the user's DECLARATION of the identity their\n * gateway wants, even though the official adapter discards it; the plugin reads\n * the same key so the settings document stays the single source of truth.\n * @param profile - one route's profile record.\n * @returns the value, or undefined when the route declares none.\n */\nexport function declaredUserAgent(profile: Record<string, unknown> | undefined): string | undefined {\n const headers = headersOf(profile)\n if (headers === undefined) return undefined\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() === 'user-agent') return isSendableUserAgent(value) ? value : undefined\n }\n return undefined\n}\n\n/** Normalize a route endpoint's pathname for boundary-safe prefix matching. */\nfunction pathPrefixOf(url: string): string {\n try {\n const pathname = new URL(url).pathname.replace(/\\/+$/, '')\n return pathname.length === 0 ? '/' : pathname\n } catch {\n return '/'\n }\n}\n\n/** Model IDs that can appear in a pi-ai request body for one route. */\nfunction modelIdsOf(profile: Record<string, unknown>): string[] {\n const ids = new Set<string>()\n const models = profile['models']\n if (Array.isArray(models)) {\n for (const model of models) {\n if (!isRecord(model) || typeof model['id'] !== 'string' || model['id'].length === 0) continue\n ids.add(model['id'])\n }\n }\n // modelOverrides is keyed by model id and can carry entries not repeated in\n // the explicit models array, so include it as another source of route identity.\n const overrides = profile['modelOverrides']\n if (isRecord(overrides)) {\n for (const id of Object.keys(overrides)) if (id.length > 0) ids.add(id)\n }\n return [...ids]\n}\n\n/** Normalize names the way Fetch's Headers object compares them. */\nfunction normalizedHeaders(headers: Record<string, string>): Map<string, { name: string; value: string }> {\n const normalized = new Map<string, { name: string; value: string }>()\n for (const [name, value] of Object.entries(headers)) {\n normalized.set(name.toLowerCase(), { name, value })\n }\n return normalized\n}\n\n/** Record a same-origin difference that the URL-only fetch seam cannot route. */\nfunction recordHeaderConflicts(index: HeaderIndex, existing: HeaderOverride, route: string, headers: Record<string, string>): void {\n const first = normalizedHeaders(existing.headers)\n const next = normalizedHeaders(headers)\n const names = new Set([...first.keys(), ...next.keys()])\n for (const name of names) {\n const oldEntry = first.get(name)\n const nextEntry = next.get(name)\n if (oldEntry?.value === nextEntry?.value) continue\n const reportedName = nextEntry?.name ?? oldEntry?.name ?? name\n const reported = index.headerConflicts.find(entry => entry.origin === existing.origin && entry.header.toLowerCase() === name)\n if (reported === undefined) {\n index.headerConflicts.push({\n origin: existing.origin,\n header: reportedName,\n routes: [existing.route, route],\n values: [oldEntry?.value ?? '<not configured>', nextEntry?.value ?? '<not configured>'],\n })\n } else if (!reported.routes.includes(route)) {\n reported.routes.push(route)\n reported.values.push(nextEntry?.value ?? '<not configured>')\n }\n }\n}\n\n/** Build the route index from each provider profile's endpoint and header declaration. */\nexport function buildHeaderIndex(\n providers: Record<string, Record<string, unknown>>,\n): HeaderIndex {\n const index = emptyIndex()\n const claimedUserAgents = new Map<string, { routes: string[]; values: string[] }>()\n for (const [route, profile] of Object.entries(providers)) {\n const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'] : undefined\n const origin = originOf(baseURL)\n if (origin === undefined) continue\n\n const sendable = sendableHeadersOf(profile) ?? {}\n const hasHeaders = Object.keys(sendable).length > 0\n const userAgent = Object.entries(sendable).find(([name]) => name.toLowerCase() === 'user-agent')?.[1]\n const override: HeaderOverride = {\n origin,\n pathPrefix: pathPrefixOf(baseURL ?? origin),\n headers: sendable,\n route,\n modelIds: modelIdsOf(profile),\n hasHeaders,\n ...(userAgent === undefined ? {} : { userAgent }),\n }\n // Every route is registered, headers or not: a route that declares no\n // headers must still be able to claim its own requests so another route on\n // the same endpoint cannot leak its headers onto them.\n index.routes.push(override)\n if (!hasHeaders) continue\n index.overrides.push(override)\n const existing = index.byOrigin.get(origin)\n if (existing === undefined) {\n index.byOrigin.set(origin, override)\n } else {\n recordHeaderConflicts(index, existing, route, sendable)\n }\n\n if (userAgent === undefined) continue\n const claimed = claimedUserAgents.get(origin)\n if (claimed === undefined) {\n claimedUserAgents.set(origin, { routes: [route], values: [userAgent] })\n continue\n }\n claimed.routes.push(route)\n claimed.values.push(userAgent)\n // Idempotent declaration (two routes, same identity) is not a UA conflict.\n if (claimed.values.every(value => value === claimed.values[0])) continue\n const reported = index.conflicts.find(entry => entry.origin === origin)\n if (reported === undefined) index.conflicts.push({ origin, routes: [...claimed.routes], values: [...claimed.values] })\n else {\n reported.routes = [...claimed.routes]\n reported.values = [...claimed.values]\n }\n }\n return index\n}\n\n/** Original public name retained while callers migrate to the generic index. */\nexport function buildUserAgentIndex(\n providers: Record<string, Record<string, unknown>>,\n): UserAgentIndex {\n return buildHeaderIndex(providers)\n}\n\n/** The pathname of a request URL, normalized the way {@link pathPrefixOf} is. */\nexport function requestPathOf(url: string): string | undefined {\n try {\n return new URL(url).pathname\n } catch {\n return undefined\n }\n}\n\n/** Whether a request path sits under a route's baseURL path prefix. */\nfunction pathMatches(requestPath: string, prefix: string): boolean {\n if (prefix === '/') return true\n return requestPath === prefix || requestPath.startsWith(`${prefix}/`)\n}\n\n/**\n * The model id carried by a JSON request body, or undefined when the body is\n * not JSON / names no string `model`. OpenAI-compatible chat completions and\n * responses both put the selected model in the top-level `model` field.\n */\nexport function modelOfJsonBody(body: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(body)\n if (!isRecord(parsed)) return undefined\n const model = parsed['model']\n return typeof model === 'string' && model.length > 0 ? model : undefined\n } catch {\n // A non-JSON body (multipart, SSE upload, empty) carries no model identity.\n return undefined\n }\n}\n\n/**\n * The routes that could own a request, narrowed by origin and endpoint path.\n *\n * The result is the set the fetch layer must disambiguate: one element means\n * the URL already identifies the route (no body read is needed), several means\n * only the request's own `model` can decide, and zero means no route matches.\n * @param index - the live route index.\n * @param url - the request URL.\n * @returns the candidate overrides, in declaration order.\n */\nexport function pathCandidatesOf(index: HeaderIndex, url: string): HeaderOverride[] {\n const origin = originOf(url)\n if (origin === undefined) return []\n // A hand-built index may carry only the origin map; honour it as the legacy\n // single-candidate shape.\n const known = index.routes.length === 0 ? index.overrides : index.routes\n const byOrigin = known.length === 0\n ? (() => { const only = index.byOrigin.get(origin); return only === undefined ? [] : [only] })()\n : known.filter(entry => entry.origin === origin)\n if (byOrigin.length <= 1) return byOrigin\n const requestPath = requestPathOf(url)\n if (requestPath === undefined) return byOrigin\n const matched = byOrigin.filter(entry => pathMatches(requestPath, entry.pathPrefix))\n // An empty path match means the route paths were not describable (or the\n // request targets a prefix no route declares): keep every candidate.\n return matched.length === 0 ? byOrigin : matched\n}\n\n/**\n * Pick one route out of already-narrowed candidates by the request body's model.\n *\n * The model only decides when exactly one candidate declares it; a model no\n * candidate declares, or a model several candidates share, falls back to the\n * first declarer \u2014 the same conservative rule as a request with no model at\n * all.\n * @param candidates - the path-narrowed candidates, in declaration order.\n * @param model - the model id read from the request body, when one was found.\n * @returns the override to apply, or undefined when there are no candidates.\n */\nexport function selectOverrideFrom(candidates: HeaderOverride[], model?: string): HeaderOverride | undefined {\n if (candidates.length <= 1) return candidates[0]\n if (model !== undefined) {\n const byModel = candidates.filter(entry => entry.modelIds.includes(model))\n if (byModel.length === 1) return byModel[0]\n }\n return candidates[0]\n}\n\n/**\n * Pick the route whose configured headers belong on one request.\n *\n * Two routes can share an origin, which the URL alone cannot separate. The\n * choice is therefore narrowed in three steps: the endpoint path prefix (see\n * {@link pathCandidatesOf}), then the `model` carried by the JSON body (see\n * {@link selectOverrideFrom}), then the first declarer. A request that cannot\n * be pinned down therefore keeps the conservative behaviour the plugin shipped\n * with, and the index's conflict report tells the user the endpoints overlap.\n * @param index - the live route index.\n * @param url - the request URL.\n * @param model - the model id read from the request body, when one was found.\n * @returns the override to apply, or undefined when no route matches.\n */\nexport function selectOverride(\n index: HeaderIndex,\n url: string,\n model?: string,\n): HeaderOverride | undefined {\n return selectOverrideFrom(pathCandidatesOf(index, url), model)\n}\n\n/**\n * The request URL a Fetch call is aimed at, or undefined when it cannot be\n * classified. A `Request` from another realm fails the `instanceof` test and is\n * reported as unclassifiable rather than mis-read \u2014 the same conservative\n * posture the official fetch seam takes.\n * @param input - the fetch input.\n * @returns the URL string, when one can be read.\n */\nexport function requestUrlOf(input: unknown): string | undefined {\n if (typeof input === 'string') return input\n if (typeof URL !== 'undefined' && input instanceof URL) return input.href\n if (typeof Request !== 'undefined' && input instanceof Request) return input.url\n return undefined\n}\n", "/**\n * The fetch-layer installer for provider request-header overrides. The decision of\n * WHAT to override lives in `headers-core.ts`; this module owns the global seam.\n *\n * Shape of the seam: one process-wide wrapper owns `globalThis.fetch`, and\n * every activation is an ENTRY inside it. That is what makes the plugin safe\n * next to itself (an HMR remount, a second composer, two plugin instances) and\n * what makes unloading exact: an entry leaves the registry and the wrapper is\n * restored only once the last entry is gone \u2014 never a blind\n * `globalThis.fetch = original` that would clobber a wrapper installed after\n * this one, and never a wrapper left behind holding the process's fetch.\n *\n * The wrapper is deliberately narrow: a request whose URL is not in the index\n * passes through with its ORIGINAL arguments (same object identity), so\n * unconfigured traffic pays exactly one URL classification and one index\n * lookup \u2014 no allocation beyond that, and no way for a bug in the merge path\n * to alter a request that never matched.\n *\n * Why fetch rather than the pi-ai `transformHeaders` option, which would be\n * narrower: reaching that option means holding the adapter's private `models`\n * collection, and every sanctioned seam (`llm/stream` waterfall,\n * `registerAdapter`) stops at the stream, above the wire. Fetch is the only\n * public surface that sees the merged headers. Both were probed against the\n * real runtime \u2014 see `.tmp-rel/headers-probe/`.\n *\n * @module dsh-model-think-level/headers-fetch\n */\n\nimport {\n emptyIndex,\n modelOfJsonBody,\n pathCandidatesOf,\n requestUrlOf,\n selectOverrideFrom,\n type HeaderIndex,\n type HeaderOverride,\n} from './headers-core.js'\n\n/** Registry key on `globalThis`, so a second plugin load shares the one wrapper. */\nconst REGISTRY = Symbol.for('dsh-model-think-level.fetch-overrides')\n\n/** One activation's contribution to the process-wide wrapper. */\ninterface Entry {\n /**\n * Reads the current index. A source rather than a value because the settings\n * document is live: a route added, edited, or removed on the Models page must\n * reach the next request without a plugin reload.\n */\n index: () => HeaderIndex\n}\n\n/** The process-wide wrapper state. */\ninterface Registry {\n base: typeof globalThis.fetch\n wrapper: typeof globalThis.fetch\n entries: Map<symbol, Entry>\n}\n\nfunction registryOf(): Registry | undefined {\n const holder = globalThis as unknown as Record<symbol, Registry | undefined>\n return holder[REGISTRY]\n}\n\n/**\n * Read a request body as text without consuming the request itself.\n *\n * The body is only read when the URL alone leaves the route ambiguous, so the\n * common single-route case still pays nothing. A `Request` is cloned (its\n * stream must survive for the real send); an `init.body` string is used\n * directly, and any other body shape (stream, FormData) yields undefined\n * rather than being disturbed.\n */\nasync function bodyTextOf(input: unknown, init: RequestInit | undefined): Promise<string | undefined> {\n if (typeof init?.body === 'string') return init.body\n if (typeof Request !== 'undefined' && input instanceof Request) {\n try {\n return await input.clone().text()\n } catch {\n // A body that cannot be cloned (already disturbed, or streamed) simply\n // leaves the route ambiguous and the first declarer serves.\n return undefined\n }\n }\n return undefined\n}\n\n/**\n * The caller's request headers as a mutable copy, seeded the way Fetch itself\n * resolves them: an explicit `init.headers` replaces a `Request`'s own headers,\n * and the `Request`'s are inherited only when the init names none. Seeding from\n * the wrong one would either drop the caller's headers or resurrect the ones\n * the caller replaced.\n */\nfunction seedHeaders(input: unknown, init: RequestInit | undefined): Headers {\n if (init?.headers !== undefined && init.headers !== null) return new Headers(init.headers as HeadersInit)\n if (typeof Request !== 'undefined' && input instanceof Request) return new Headers(input.headers)\n return new Headers()\n}\n\n/** The wrapper: inject the matched route's request headers and delegate everything else. */\nfunction makeWrapper(base: typeof globalThis.fetch, entries: Map<symbol, Entry>): typeof globalThis.fetch {\n return async function fetchWithProviderHeaders(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const url = requestUrlOf(input)\n if (url === undefined) return base(input, init)\n // The URL (origin + endpoint path) narrows the route. Only when it leaves\n // several candidates does the request body's `model` have to decide -- so a\n // single-route deployment keeps the zero-read, zero-allocation fast path.\n let candidates: HeaderOverride[] = []\n for (const entry of entries.values()) {\n candidates = pathCandidatesOf(entry.index(), url)\n if (candidates.length > 0) break\n }\n if (candidates.length === 0) return base(input, init)\n let override = candidates.length === 1 ? candidates[0] : undefined\n if (override === undefined) {\n const body = await bodyTextOf(input, init)\n const model = body === undefined ? undefined : modelOfJsonBody(body)\n override = selectOverrideFrom(candidates, model)\n }\n if (override === undefined) return base(input, init)\n // A route that claims the request but declares no headers is a deliberate\n // \"send nothing\": another route's identity must not leak onto it.\n if (!override.hasHeaders) return base(input, init)\n const headers = seedHeaders(input, init)\n for (const [name, value] of Object.entries(override.headers)) {\n // The index already filters invalid entries. Keep the seam defensive for\n // a live source supplied by another caller or a stale settings snapshot.\n try {\n headers.set(name, value)\n } catch {\n // A malformed stored pair must not prevent the remaining headers or the\n // underlying request from being sent.\n }\n }\n const nextInit = { ...init, headers }\n if (typeof Request !== 'undefined' && input instanceof Request) {\n return base(new Request(input, { headers }), nextInit)\n }\n return base(input, nextInit)\n }\n}\n\n/** Handle one activation keeps; `dispose` is idempotent. */\nexport interface HeaderOverlayHandle {\n /** Remove this activation's entry, restoring the original fetch when it was the last. */\n dispose(): void\n}\n\n/** Handle for tests and the caller to swap the index a live activation reads. */\nexport interface HeaderOverlay extends HeaderOverlayHandle {\n /** Whether this activation's entry is still installed. */\n readonly active: boolean\n}\n\n/** A mutable index source an activation reads on every request. */\nexport interface OverlaySource {\n current: HeaderIndex\n}\n\n/**\n * Install (or join) the process-wide header wrapper.\n * @param source - the live index this activation contributes.\n * @returns a handle whose `dispose` removes exactly this activation.\n */\nexport function installHeaderOverlay(source: OverlaySource): HeaderOverlay {\n const holder = globalThis as unknown as Record<symbol, Registry | undefined>\n let registry = holder[REGISTRY]\n const token = Symbol('bre-header-overlay')\n if (registry === undefined) {\n const base = globalThis.fetch\n const entries = new Map<symbol, Entry>()\n const wrapper = makeWrapper(base, entries)\n registry = { base, wrapper, entries }\n holder[REGISTRY] = registry\n globalThis.fetch = wrapper\n }\n registry.entries.set(token, { index: () => source.current })\n const owned = registry\n return {\n get active(): boolean {\n return owned.entries.has(token)\n },\n dispose(): void {\n owned.entries.delete(token)\n if (owned.entries.size > 0) return\n // Last one out restores the ORIGINAL function, and only when this\n // wrapper still holds the global: a later installer's wrapper must not be\n // clobbered by our teardown.\n if (globalThis.fetch === owned.wrapper) globalThis.fetch = owned.base\n if (holder[REGISTRY] === owned) delete holder[REGISTRY]\n },\n }\n}\n\n/** Whether this plugin's wrapper currently owns the global fetch (diagnostics). */\nexport function headerOverlayInstalled(): boolean {\n const registry = registryOf()\n return registry !== undefined && globalThis.fetch === registry.wrapper\n}\n\n/** The empty index, re-exported so callers building one need a single import. */\nexport { emptyIndex }\n", "/**\n * Request-level header bridge for the pi-ai-backed Harness adapter.\n *\n * The model-list probe has its own direct fetch path, but conversation requests\n * are assembled inside dsh-llm-pi-ai and then passed to pi-ai's Models service.\n * pi-ai exposes `transformHeaders` exactly after auth and request headers have\n * been merged, so it is the right place to restore the profile values that the\n * Harness attribution layer reserves (most visibly `user-agent`).\n *\n * dsh-llm-pi-ai does not expose its private Models collection through a public\n * plugin API. Its adapter is nevertheless registered in the public llm runtime,\n * and the runtime object keeps that registration in a normal `adapters` Map. The\n * bridge uses a narrow structural adapter of that implementation detail and\n * fails open for other adapters or older runtimes.\n *\n * @module dsh-model-think-level/headers-pi-ai\n */\n\nimport { isRecord } from './shared.js'\nimport { selectOverride, type HeaderIndex, type HeaderOverride } from './headers-core.js'\n\n/** A live route index shared with the fetch overlay. */\nexport interface PiAiHeaderSource {\n current: HeaderIndex\n}\n\ntype ProviderHeaders = Record<string, string | null>\ntype HeaderTransformer = (headers: ProviderHeaders) => ProviderHeaders | Promise<ProviderHeaders>\ntype UnknownFunction = (...args: unknown[]) => unknown\n\ntype ObjectLike = Record<PropertyKey, unknown>\n\ninterface PiAiPatchState {\n originalCurrent: UnknownFunction\n wrappedCurrent: UnknownFunction\n source: PiAiHeaderSource\n users: number\n}\n\ninterface RegisterPatchState {\n originalRegister: UnknownFunction\n wrappedRegister: UnknownFunction\n users: number\n}\n\nconst PATCH_STATE = Symbol.for('dsh-model-think-level.pi-ai-header-transform')\nconst REGISTER_PATCH_STATE = Symbol.for('dsh-model-think-level.pi-ai-header-register')\nconst CORDIS_ORIGINAL = Symbol.for('cordis.original')\n\nfunction objectOf(value: unknown): ObjectLike | undefined {\n return typeof value === 'object' && value !== null ? value as ObjectLike : undefined\n}\n\nfunction runtimeObjectOf(value: unknown): ObjectLike | undefined {\n const object = objectOf(value)\n if (object === undefined) return undefined\n const original = object[CORDIS_ORIGINAL]\n return objectOf(original) ?? object\n}\n\nfunction noOpHandle(): PiAiHeaderTransformHandle {\n return {\n active: false,\n dispose(): void {},\n }\n}\n\nfunction routeOverrideOf(source: PiAiHeaderSource, model: unknown): HeaderOverride | undefined {\n try {\n if (!isRecord(model)) return undefined\n const baseURL = model['baseUrl']\n if (typeof baseURL !== 'string' || baseURL.length === 0) return undefined\n const modelId = typeof model['id'] === 'string' ? model['id'] : undefined\n return selectOverride(source.current, baseURL, modelId)\n } catch {\n // A stale or partially written settings snapshot must never break a chat.\n return undefined\n }\n}\n\nfunction modelsProxyOf(models: ObjectLike, source: PiAiHeaderSource): ObjectLike {\n return new Proxy(models, {\n get(target, property, receiver): unknown {\n if (property !== 'streamSimple') return Reflect.get(target, property, receiver)\n const streamSimple = Reflect.get(target, property, target)\n if (typeof streamSimple !== 'function') return streamSimple\n return (...args: unknown[]): unknown => {\n const model = args[0]\n const context = args[1]\n const options = args[2]\n const modelObject = isRecord(model) ? model : undefined\n if (modelObject === undefined || typeof modelObject['baseUrl'] !== 'string' || !isRecord(options)) {\n return (streamSimple as UnknownFunction).call(target, model, context, options)\n }\n\n const existing = typeof options['transformHeaders'] === 'function'\n ? options['transformHeaders'] as HeaderTransformer\n : undefined\n const transformHeaders: HeaderTransformer = async (headers) => {\n // Preserve any transform supplied by the adapter/provider first; the\n // user's route headers are the final request-level values by design.\n const merged = existing === undefined ? headers : await existing(headers)\n const override = routeOverrideOf(source, model)\n return override?.hasHeaders ? { ...merged, ...override.headers } : merged\n }\n return (streamSimple as UnknownFunction).call(target, model, context, {\n ...options,\n transformHeaders,\n })\n }\n },\n })\n}\n\nfunction snapshotProxyOf(snapshot: ObjectLike, source: PiAiHeaderSource): ObjectLike {\n const models = snapshot['models']\n const modelObject = objectOf(models)\n if (modelObject === undefined || typeof modelObject['streamSimple'] !== 'function') return snapshot\n const proxiedModels = modelsProxyOf(modelObject, source)\n return new Proxy(snapshot, {\n get(target, property, receiver): unknown {\n if (property === 'models') return proxiedModels\n return Reflect.get(target, property, receiver)\n },\n })\n}\n\n/** Handle returned for one adapter patch. */\nexport interface PiAiHeaderTransformHandle {\n readonly active: boolean\n dispose(): void\n}\n\n/** Install the request-level transform on one pi-ai-shaped adapter. */\nexport function installPiAiHeaderTransform(adapter: unknown, source: PiAiHeaderSource): PiAiHeaderTransformHandle {\n const target = objectOf(adapter)\n if (target === undefined || typeof target['current'] !== 'function') return noOpHandle()\n\n const current = target['current'] as UnknownFunction\n const stored = target[PATCH_STATE] as PiAiPatchState | undefined\n if (stored !== undefined && current === stored.wrappedCurrent) {\n stored.source = source\n stored.users += 1\n let active = true\n return {\n get active(): boolean { return active && stored.users > 0 },\n dispose(): void {\n if (!active) return\n active = false\n stored.users -= 1\n if (stored.users > 0) return\n if (target['current'] === stored.wrappedCurrent) target['current'] = stored.originalCurrent\n if (target[PATCH_STATE] === stored) delete target[PATCH_STATE]\n },\n }\n }\n\n const originalCurrent = current\n const wrappedCurrent: UnknownFunction = function (this: unknown, ...args: unknown[]): unknown {\n const snapshot = originalCurrent.apply(this, args)\n const snapshotObject = objectOf(snapshot)\n return snapshotObject === undefined ? snapshot : snapshotProxyOf(snapshotObject, state.source)\n }\n const state: PiAiPatchState = { originalCurrent, wrappedCurrent, source, users: 1 }\n target['current'] = wrappedCurrent\n Object.defineProperty(target, PATCH_STATE, { configurable: true, value: state })\n\n let active = true\n return {\n get active(): boolean { return active && state.users > 0 },\n dispose(): void {\n if (!active) return\n active = false\n state.users -= 1\n if (state.users > 0) return\n if (target['current'] === state.wrappedCurrent) target['current'] = state.originalCurrent\n if (target[PATCH_STATE] === state) delete target[PATCH_STATE]\n },\n }\n}\n\n/** Diagnostic snapshot of the bridge's live attach state. */\nexport interface PiAiHeaderBridgeState {\n runtimeFound: boolean\n registerPatched: boolean\n adaptersInRuntime: number\n adaptersPatched: number\n adapters: string[]\n routes: number\n overrides: number\n}\n\n/**\n * Describe what the bridge is currently attached to. Read-only; used by the\n * probe route's `?diag=1` arm to make the request-header takeover observable\n * from the running host instead of only from a test harness.\n */\nexport function describePiAiHeaderState(llm: unknown, source: PiAiHeaderSource): PiAiHeaderBridgeState {\n const runtime = runtimeObjectOf(llm)\n const adapters = runtime?.['adapters']\n const names: string[] = []\n let total = 0\n let patched = 0\n if (adapters instanceof Map) {\n for (const registration of adapters.values()) {\n const adapter = objectOf(objectOf(registration)?.['adapter'])\n if (adapter === undefined || typeof adapter['current'] !== 'function') continue\n total += 1\n const state = adapter[PATCH_STATE] as PiAiPatchState | undefined\n const isPatched = state !== undefined && adapter['current'] === state.wrappedCurrent\n if (isPatched) patched += 1\n const name = typeof adapter['constructor'] === 'function' ? adapter['constructor'].name : 'unknown'\n names.push(`${name}${isPatched ? '+' : '-'}`)\n }\n }\n const registerState = runtime?.[REGISTER_PATCH_STATE] as RegisterPatchState | undefined\n return {\n runtimeFound: runtime !== undefined,\n registerPatched: registerState !== undefined && runtime?.['registerAdapter'] === registerState.wrappedRegister,\n adaptersInRuntime: total,\n adaptersPatched: patched,\n adapters: names,\n routes: source.current.routes.length,\n overrides: source.current.overrides.length,\n }\n}\n\n/**\n * Install the bridge on every current pi-ai-shaped registration and expose a\n * refresh for the runtime's `llm/adapters-updated` event.\n */\nexport interface PiAiHeaderTransformsHandle {\n refresh(): void\n dispose(): void\n}\n\nexport function installPiAiHeaderTransforms(llm: unknown, source: PiAiHeaderSource): PiAiHeaderTransformsHandle {\n const installed = new Map<object, PiAiHeaderTransformHandle>()\n const runtime = runtimeObjectOf(llm)\n let disposed = false\n\n const install = (adapter: unknown): void => {\n if (disposed) return\n const adapterObject = objectOf(adapter)\n if (adapterObject === undefined || typeof adapterObject['current'] !== 'function') return\n if (!installed.has(adapterObject)) installed.set(adapterObject, installPiAiHeaderTransform(adapterObject, source))\n }\n\n const refresh = (): void => {\n if (disposed) return\n const adapters = runtime?.['adapters']\n if (!(adapters instanceof Map)) return\n const seen = new Set<object>()\n for (const registration of adapters.values()) {\n const registrationObject = objectOf(registration)\n const adapterObject = objectOf(registrationObject?.['adapter'])\n if (adapterObject === undefined || typeof adapterObject['current'] !== 'function') continue\n seen.add(adapterObject)\n install(adapterObject)\n }\n for (const [adapter, handle] of installed) {\n if (seen.has(adapter)) continue\n handle.dispose()\n installed.delete(adapter)\n }\n }\n\n // dsh-llm-pi-ai registers its adapter through this public method. Install\n // before delegating so a registration cannot emit an update and dispatch a\n // request in between the registry mutation and our refresh listener.\n let registerHandle: PiAiHeaderTransformHandle | undefined\n const originalRegister = runtime?.['registerAdapter']\n if (runtime !== undefined && typeof originalRegister === 'function') {\n const registerState = runtime[REGISTER_PATCH_STATE] as RegisterPatchState | undefined\n if (registerState !== undefined && runtime['registerAdapter'] === registerState.wrappedRegister) {\n registerState.users += 1\n registerHandle = {\n get active(): boolean { return !disposed && registerState.users > 0 },\n dispose(): void {\n if (registerState.users <= 0) return\n registerState.users -= 1\n if (registerState.users > 0) return\n if (runtime['registerAdapter'] === registerState.wrappedRegister) runtime['registerAdapter'] = registerState.originalRegister\n if (runtime[REGISTER_PATCH_STATE] === registerState) delete runtime[REGISTER_PATCH_STATE]\n },\n }\n } else {\n const original = originalRegister as UnknownFunction\n const wrappedRegister: UnknownFunction = function (this: unknown, ...args: unknown[]): unknown {\n const adapter = args[1]\n install(adapter)\n try {\n return original.apply(this, args)\n } finally {\n refresh()\n }\n }\n const state: RegisterPatchState = {\n originalRegister: original,\n wrappedRegister,\n users: 1,\n }\n runtime['registerAdapter'] = wrappedRegister\n Object.defineProperty(runtime, REGISTER_PATCH_STATE, { configurable: true, value: state })\n registerHandle = {\n get active(): boolean { return !disposed && state.users > 0 },\n dispose(): void {\n if (state.users <= 0) return\n state.users -= 1\n if (state.users > 0) return\n if (runtime['registerAdapter'] === state.wrappedRegister) runtime['registerAdapter'] = state.originalRegister\n if (runtime[REGISTER_PATCH_STATE] === state) delete runtime[REGISTER_PATCH_STATE]\n },\n }\n }\n }\n refresh()\n\n return {\n refresh,\n dispose(): void {\n if (disposed) return\n disposed = true\n registerHandle?.dispose()\n for (const handle of installed.values()) handle.dispose()\n installed.clear()\n },\n }\n}\n", "/**\n * Coexistence report for the user-agent takeover (issue #12, MVP-3).\n *\n * Overriding `user-agent` is not a private act: the stock adapter drops the\n * profile's value, so at least one published plugin patches the adapter itself\n * to keep it, and several more wrap fetch. Two of them active at once means the\n * LAST writer on the wire wins and the user sees a `user-agent` they did not\n * choose \u2014 with no error anywhere. This module reports what it found instead of\n * silently fighting.\n *\n * Three signals, in descending reliability:\n * 1. The adapter file already carries a user-agent patch (its `requestHeaders`\n * body no longer drops the profile's `user-agent`) \u2014 readable fact.\n * 2. A known sibling plugin's package is installed in a reachable tree.\n * 3. Nothing found.\n *\n * Everything here is best-effort and side-effect-free: an unreadable path, an\n * absent tree, or a hostile `package.json` yields `unknown`, never a throw \u2014\n * this report must not be able to disable the plugin.\n *\n * @module dsh-model-think-level/headers-conflict\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join, resolve } from 'node:path'\n\n/**\n * Sibling plugins that rewrite the same request surface. The list is by PACKAGE\n * NAME, matched anywhere in a reachable `node_modules`: a plugin installed\n * under a profile but not enabled is reported as installed, and the report says\n * so rather than guessing at enablement (which a patch file or a hand-edited\n * profile can decide several ways).\n */\nconst SIBLING_PACKAGES = [\n 'dsh-client-masquerade',\n 'dsh-llm-headers',\n 'dsh-llm-pi-ai-headers',\n 'dsh-custom-provider-settings',\n] as const\n\n/**\n * Fragments proving the installed adapter already preserves a profile\n * `user-agent`. The published patch rewrites `requestHeaders()` to look for a\n * configured value; older revisions of it used the same identifier, so the\n * check survives their textual reshuffle while staying specific enough that the\n * stock function cannot match (it contains neither).\n */\nconst ADAPTER_PATCH_MARKERS = ['configuredUserAgent', 'masquerade routes rely on'] as const\n\n/** What the report found about the adapter the requests actually flow through. */\nexport type AdapterPatchState = 'patched' | 'stock' | 'unknown'\n\n/** One sibling plugin package found on disk. */\nexport interface InstalledSibling {\n /** Package name. */\n name: string\n /** Absolute path of the resolved package directory (or entry file). */\n path: string\n}\n\n/** The coexistence report. */\nexport interface HeaderConflictReport {\n /** Whether the installed `@deepseek-ai/dsh-llm-pi-ai` adapter carries a UA patch. */\n adapter: AdapterPatchState\n /** Path of the inspected adapter file, when one was found. */\n adapterPath?: string\n /** Known sibling plugins present on disk. */\n siblings: InstalledSibling[]\n /**\n * Whether this deployment should prefer the official layer instead of this\n * plugin's fetch takeover: true exactly when the adapter is already patched\n * (a profile `user-agent` reaches the wire on its own then, and a fetch\n * override on top would fight the patch).\n */\n preferOfficialLayer: boolean\n}\n\n/** Candidate `node_modules` roots to look in, most specific first. */\nfunction searchRoots(): string[] {\n const roots = new Set<string>()\n const entry = process.argv[1]\n if (typeof entry === 'string' && entry.length > 0) {\n let dir = dirname(resolve(entry))\n // Walk up a bounded number of levels: the shim, the bin dir, the package,\n // the install root.\n for (let depth = 0; depth < 8; depth += 1) {\n roots.add(join(dir, 'node_modules'))\n const parent = dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n }\n // The cwd tree covers a profile-relative launch; the require chain covers\n // everything the process itself can no longer name.\n roots.add(join(process.cwd(), 'node_modules'))\n try {\n const require = createRequire(import.meta.url)\n for (const name of SIBLING_PACKAGES) {\n try {\n roots.add(join(dirname(dirname(dirname(require.resolve(`${name}/package.json`)))), 'node_modules'))\n } catch {\n // Not resolvable from here; the path search below covers the rest.\n }\n }\n } catch {\n // No require chain: path search alone.\n }\n return [...roots]\n}\n\n/** Locate the installed pi-ai adapter's bundle, or undefined when unreachable. */\nfunction findAdapterFile(): string | undefined {\n const relative = join('@deepseek-ai', 'dsh-llm-pi-ai', 'lib', 'index.js')\n const candidates: string[] = []\n try {\n const require = createRequire(import.meta.url)\n candidates.push(require.resolve('@deepseek-ai/dsh-llm-pi-ai'))\n } catch {\n // Resolve by location instead.\n }\n // dsh ships the adapter inside its own tree; probing the entry's ancestry\n // finds it for a global install, a profile install, and a monorepo alike.\n for (const root of searchRoots()) candidates.push(join(root, relative))\n for (const candidate of candidates) {\n if (existsSync(candidate)) return candidate\n }\n return undefined\n}\n\n/**\n * Whether a source text of the pi-ai adapter bundle carries a user-agent patch.\n *\n * Pure, so the decision is testable without touching a real installation: the\n * stock `requestHeaders()` filters the profile's `user-agent` into the reserved\n * set and contains neither marker, while every published revision of the patch\n * names the value it found.\n * @param source - the adapter bundle's text.\n * @returns whether the patch is present.\n */\nexport function adapterSourcePatched(source: string): boolean {\n return ADAPTER_PATCH_MARKERS.some(marker => source.includes(marker))\n}\n\n/** Whether the adapter bundle at one path carries a user-agent patch. */\nfunction adapterPatchState(path: string): AdapterPatchState {\n try {\n return adapterSourcePatched(readFileSync(path, 'utf8')) ? 'patched' : 'stock'\n } catch {\n return 'unknown'\n }\n}\n\n/** Known sibling plugins present in a reachable tree. */\nfunction findSiblings(): InstalledSibling[] {\n const found: InstalledSibling[] = []\n const seen = new Set<string>()\n for (const root of searchRoots()) {\n for (const name of SIBLING_PACKAGES) {\n if (seen.has(name)) continue\n const dir = join(root, name)\n const manifest = join(dir, 'package.json')\n if (!existsSync(manifest)) continue\n seen.add(name)\n found.push({ name, path: dir })\n }\n }\n return found\n}\n\n/**\n * Produce the coexistence report. Never throws: every probe degrades to\n * `unknown` / an empty list.\n * @returns the report.\n */\nexport function detectHeaderConflicts(): HeaderConflictReport {\n let adapter: AdapterPatchState = 'unknown'\n let adapterPath: string | undefined\n let siblings: InstalledSibling[] = []\n try {\n adapterPath = findAdapterFile()\n if (adapterPath !== undefined) adapter = adapterPatchState(adapterPath)\n } catch {\n adapter = 'unknown'\n }\n try {\n siblings = findSiblings()\n } catch {\n siblings = []\n }\n return {\n adapter,\n ...(adapterPath === undefined ? {} : { adapterPath }),\n siblings,\n preferOfficialLayer: adapter === 'patched',\n }\n}\n", "/**\n * The knowledge-base auto-fill: build the settings patch that declares\n * `reasoningEfforts` -- and, unless declined, the input-modality declaration --\n * on every undeclared model of a providers dict.\n *\n * Shared by BOTH halves on purpose. The host builds its boot fill with it, and\n * the browser half builds the very same patch from its own read, so one\n * suggestion can never produce two different documents. Pure data logic: no\n * harness package, no node or DOM API.\n *\n * @module dsh-model-think-level/autofill\n */\n\nimport { AUTOFILL_MARKER, INPUT_UNSET_MARKER, UNSET_MARKER } from './constants.js'\nimport { isSelfHostedRelay, NEW_COMPAT_KEYS, suggestEfforts } from './knowledge.js'\nimport { isRecord, routeFactsOf } from './shared.js'\n\n/** A JSON object patch. */\ntype JsonObject = Record<string, unknown>\n\n/**\n * Whether a model row carries an input-modality declaration the document\n * already answers with. An absent key and an empty array both read as \"no\n * answer here\" -- mirroring how llm-pi-ai's own resolution treats them.\n */\nfunction declaresInput(model: JsonObject): boolean {\n const input = model['input']\n return Array.isArray(input) && input.length > 0\n}\n\n/**\n * Build a patch that adds reasoningEfforts -- and, unless declined, the\n * input-modality declaration -- to every undeclared model of the given\n * routes, from the knowledge base / protocol inference. Returns the partial\n * providers patch, or undefined when nothing needs filling.\n * @param providers - the resolved providers dict.\n * @param routeFilter - optional route filter (defaults to all routes).\n * @param options - fill switches; both default on.\n * @param revision - settings revision this read is based on; recorded as the\n * provenance marker of every ladder filled here (see {@link AUTOFILL_MARKER}).\n */\nexport function buildAutofillPatch(\n providers: unknown,\n routeFilter: (route: string) => boolean = () => true,\n options: { efforts?: boolean; modalities?: boolean } = {},\n revision = 0,\n): JsonObject | undefined {\n const fillEfforts = options.efforts !== false\n const fillModalities = options.modalities !== false\n if (!isRecord(providers)) return undefined\n const patchRoutes: JsonObject = {}\n for (const route of Object.keys(providers)) {\n if (!routeFilter(route)) continue\n // Read the RAW models array: this builder rebuilds the array verbatim,\n // so a route carrying a row it cannot represent (non-record) is left\n // alone \u2014 a filtered rebuild would silently DELETE that row.\n const profile = providers[route]\n const rawModels = isRecord(profile) && Array.isArray(profile['models']) ? profile['models'] : undefined\n if (rawModels === undefined || rawModels.length === 0) continue\n if (!rawModels.every(isRecord)) continue\n const models = rawModels as Record<string, unknown>[]\n const nextModels: JsonObject[] = []\n let changed = false\n for (const model of models) {\n // Declared parts are untouched \u2014 and so are parts the user\n // deliberately unset: the durable markers record those absences as\n // decisions, so auto-fill never reads them back as gaps (the bug this\n // guards: a refill one event after every user \"unset\").\n const effortsDeclared = model['reasoningEfforts'] !== undefined || model[UNSET_MARKER] === true\n const inputDeclared = declaresInput(model) || model[INPUT_UNSET_MARKER] === true\n if ((effortsDeclared || !fillEfforts) && (inputDeclared || !fillModalities)) {\n // Versioned exception to never-touch-declared (issue #2): a declared\n // ladder whose compat lacks the role pin on a self-hosted relay gets\n // exactly that field merged in -- the declaration itself is untouched.\n const backfilled = backfillRolePin(model, providers, route)\n if (backfilled !== undefined) {\n changed = true\n nextModels.push(backfilled)\n } else {\n nextModels.push(model)\n }\n continue\n }\n const id = typeof model['id'] === 'string' ? model['id'] : ''\n if (id.length === 0) {\n nextModels.push(model)\n continue\n }\n const routeInfo = routeFactsOf(providers, route)\n const name = typeof model['name'] === 'string' ? model['name'] : undefined\n const suggestion = suggestEfforts(id, { ...routeInfo, displayName: name ?? routeInfo.displayName })\n if (suggestion.efforts === undefined) {\n nextModels.push(model)\n continue\n }\n const fill: JsonObject = { ...model }\n let touched = false\n // Capacities are never filled here: contextWindow / maxTokens are\n // display-only reference values in the browser half, and writing them\n // host-side would silently override the route defaults.\n // Reaching this branch means neither part was declared and no durable\n // unset marker stands on the row -- so there is no stale marker inside\n // `fill` to scrub; the guards above already excluded it.\n if (!effortsDeclared && fillEfforts) {\n touched = true\n fill['reasoningEfforts'] = suggestion.efforts as JsonObject\n // Provenance: the browser flush has to be able to tell this knowledge\n // base suggestion apart from a declaration the user made, or a staged\n // intent that differs in one spelling is dropped as a takeover (see\n // AUTOFILL_MARKER). The value is the revision this fill read.\n fill[AUTOFILL_MARKER] = revision\n if (suggestion.compat !== undefined) {\n const stored = isRecord(model['compat']) ? (model['compat'] as JsonObject) : {}\n fill['compat'] = { ...stored, ...(suggestion.compat as JsonObject) }\n }\n }\n if (!inputDeclared && fillModalities && suggestion.input !== undefined) {\n touched = true\n fill['input'] = [...suggestion.input]\n }\n if (!touched) {\n nextModels.push(model)\n continue\n }\n changed = true\n nextModels.push(fill)\n }\n if (changed) patchRoutes[route] = { models: nextModels }\n }\n return Object.keys(patchRoutes).length === 0 ? undefined : { providers: patchRoutes }\n}\n\n/** Strip newer-only compat keys from an autofill patch (older-kernel downgrade). */\nexport function stripNewCompatKeysDeep(patch: JsonObject): JsonObject | undefined {\n const providers = isRecord(patch['providers']) ? (patch['providers'] as JsonObject) : undefined\n if (providers === undefined) return undefined\n let strippedAny = false\n const nextProviders: JsonObject = {}\n for (const [route, profile] of Object.entries(providers)) {\n if (!isRecord(profile) || !Array.isArray(profile['models'])) {\n nextProviders[route] = profile as JsonObject\n continue\n }\n nextProviders[route] = {\n ...(profile as JsonObject),\n models: (profile['models'] as JsonObject[]).map(model => {\n if (!isRecord(model) || !isRecord(model['compat'])) return model\n const compat = { ...(model['compat'] as JsonObject) }\n for (const key of NEW_COMPAT_KEYS) {\n if (key in compat) {\n delete compat[key]\n strippedAny = true\n }\n }\n return { ...model, compat }\n }),\n }\n }\n if (!strippedAny) return undefined\n return { providers: nextProviders }\n}\n\n/**\n * Merge the role pin into one declared model row, or refuse it.\n *\n * Refusals (all silent, all deliberate): the row carries no ladder dict\n * (`false`, absent, or a deliberate-unset marker -- bare rows keep the bare\n * wire behavior they were chosen for); its compat already names an explicit\n * role value; or the route is not a self-hosted relay. A refusal changes\n * nothing; an acceptance touches exactly one compat field.\n */\nfunction backfillRolePin(\n model: Record<string, unknown>,\n providers: unknown,\n route: string,\n): JsonObject | undefined {\n if (!isRecord(model['reasoningEfforts'])) return undefined\n if (model[UNSET_MARKER] === true) return undefined\n const compat = model['compat']\n const base: JsonObject = isRecord(compat) ? { ...compat } : {}\n if (base['supportsDeveloperRole'] !== undefined) return undefined\n if (!isSelfHostedRelay(routeFactsOf(providers, route))) return undefined\n return { ...model, compat: { ...base, supportsDeveloperRole: false } }\n}\n"],
5
- "mappings": ";AA0BA,OAAO,YAAY;;;ACnBZ,IAAM,YAAY;AAGlB,IAAM,aAAa;AAEnB,IAAM,YAAY;AAelB,IAAM,oBAAoB;AAmB1B,IAAM,iBAAiB;AASvB,IAAM,uBAAuB;AAS7B,IAAM,sBAAsB;AAG5B,IAAM,WAAW;AASjB,IAAM,eAAe;AAOrB,IAAM,qBAAqB;AAuB3B,IAAM,kBAAkB;;;AC3ExB,IAAM,uBAAuB;AAkB7B,SAAS,aAAa,OAAuB;AAClD,SAAO,GAAG,MAAM,YAAY,EAAE,QAAQ,eAAe,GAAG,CAAC;AAC3D;AAaO,SAAS,WAA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AAAA,cAEvB,aAAa;AAAA,YACf;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AACH;",
6
- "names": ["compat", "name", "name", "name", "active", "name", "readFileSync", "dirname", "join", "require", "name", "name", "name", "resolve", "ref"]
3
+ "sources": ["../src/index.ts", "../src/constants.ts", "../src/key-refs.ts", "../src/key-index.ts", "../src/key-route-core.ts", "../src/knowledge.ts", "../src/guard.ts", "../src/shared.ts", "../src/listing.ts", "../src/discovery-merge.ts", "../src/key-probe.ts", "../src/multi-key-listing.ts", "../src/headers-core.ts", "../src/headers-fetch.ts", "../src/headers-pi-ai.ts", "../src/headers-conflict.ts", "../src/autofill.ts"],
4
+ "sourcesContent": ["/**\n * Host half of dsh-model-think-level.\n *\n * One job: settings auto-adaptation. Whenever the `llm-pi-ai` section gains a\n * hand-declared model that carries no `reasoningEfforts`, fill one in from the\n * knowledge base + protocol inference (see {@link suggestEfforts}). The fill\n * is a *suggestion* written to the user layer \u2014 the user can still edit it on\n * the Models page \u2014 and a model that already declares efforts, or an explicit\n * `false`, is never touched. All interactive editing (per-model editors and\n * per-model auto-adapt) lives in the browser half, which reuses the same\n * knowledge base as a pure module.\n *\n * @module dsh-model-think-level\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Context } from '@deepseek-ai/cordis'\n// Type-only: pulls the webServer service merge into this program's Context.\nimport type {} from '@deepseek-ai/dsh-host-webserver'\n// Type-only: the `declare module '@deepseek-ai/cordis'` merge that types\n// `ctx.settings` as the profile-form service. `describe()` returns one\n// descriptor per active entry: an ARRAY, not the wire `{namespaces}` envelope.\n// The kernel ships no `settingsNamespace` value export (it is a private parse\n// + a compile-time SettingsNamespaceInput); the brand is a compile-time\n// concept, so a typed constant is enough.\nimport type { SettingsNamespace } from '@deepseek-ai/dsh-settings'\nimport Schema from '@deepseek-ai/schemastery'\nimport {\n AUTOFILL_CONFIG_PATH,\n DIAG_PATH,\n HEADERS_CONFIG_PATH,\n KEY_INDEX_PATH,\n PI_AI_NS,\n PLUGIN_ID,\n PROBE_PATH,\n PROVIDER_KEY_PATH,\n} from './constants.js'\nimport {\n endpointFamilyOf,\n isLegalKeyValue,\n maskKeyValue,\n nextKeyRef,\n normalizeKeyAlias,\n normalizeKeyModels,\n normalizeKeyProtocol,\n normalizeRouteEndpoints,\n type RouteEndpoints,\n type RouteProtocol,\n} from './key-refs.js'\nimport {\n hasKeyEntry,\n keyEntriesOf,\n keyIndexFilePath,\n readKeyIndex,\n updateKeyIndex,\n withKeyAlias,\n withKeyDisabled,\n withKeyEntry,\n withKeyModels,\n withKeyProtocol,\n withRouteEndpoints,\n withoutKeyEntry,\n} from './key-index.js'\nimport { keyRest, keysForModel, restKeyOf, type KeyCandidate } from './key-route-core.js'\nimport { suggestEfforts } from './knowledge.js'\nimport type { ReasoningEfforts } from './knowledge.js'\nimport { resolveGuardEffort } from './guard.js'\nimport { isRecord, looksLikeCompatRefusal, modelsOf, routeFactsOf } from './shared.js'\nimport {\n ANTHROPIC_VERSION,\n LISTABLE_PROTOCOLS,\n composeProbeHeaders,\n displayUrl,\n listingEntries,\n probeListingUrl,\n readBounded,\n type ListedModel,\n} from './listing.js'\nimport { probeListing } from './discovery-merge.js'\nimport { FAMILY_PROTOCOL, probeKeyModels, type KeyProbeResult } from './key-probe.js'\nimport type { EndpointFamily } from './key-refs.js'\nimport { collectKeyListings, mergeKeyListings, type MergedListing } from './multi-key-listing.js'\nimport { buildHeaderIndex, emptyIndex, type UserAgentIndex } from './headers-core.js'\nimport { headerOverlayBypass, headerOverlayInstalled, installHeaderOverlay, type OverlaySource } from './headers-fetch.js'\nimport { describePiAiHeaderState, installPiAiHeaderTransforms } from './headers-pi-ai.js'\nimport { detectHeaderConflicts, type HeaderConflictReport } from './headers-conflict.js'\n// The knowledge-base patch builder lives in its own module: the browser half\n// builds the SAME patch from its own idle-time read, so one suggestion can\n// never produce two different documents.\nimport { buildAutofillPatch, stripNewCompatKeysDeep } from './autofill.js'\n\n/** Re-exported so the package entry keeps naming the patch builder. */\nexport { buildAutofillPatch }\n\n/** Re-exported so the package entry keeps naming the probe-header composer. */\nexport { composeProbeHeaders }\n\n/** Stable plugin id, matching the cordis.patch.yml row and the bundle id. */\nexport const name = PLUGIN_ID\n\n/** Hard dependencies: the loader waits for these before calling apply. */\nexport const inject = ['settings', 'llm']\n\n/** The branded settings namespace this plugin reads and fills. */\nconst PI_NS = PI_AI_NS as SettingsNamespace\n\n/**\n * Exponential backoff for the boot fill: llm-pi-ai may register its namespace\n * well after this plugin on a slow start, and registration emits no event of\n * its own \u2014 the schedule must outlast a realistically slow profile instead of\n * giving up after a few flat seconds.\n */\nconst BOOT_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000] as const\n\n/** Probe fetch budget: a gateway that cannot answer /models in 15s will not answer the composer either. */\nconst PROBE_TIMEOUT_MS = 15_000\n\n/**\n * Plugin configuration, supplied through the profile's cordis layer\n * (the row's `config:` block). Every tunable two deployments may want\n * to set differently lives here rather than as a code constant.\n */\nexport interface Config {\n /** Auto-fill undeclared pi-ai models on boot and after settings updates (default true). */\n autofill?: boolean\n /**\n * Whether the auto-fill above also fills the input-modality declaration\n * (default true). Effort auto-fill is governed by {@link autofill} alone.\n */\n modalityAutofill?: boolean\n /** Upstream fetch timeout for the raw /models probe route, in milliseconds (default 15000). */\n probeTimeoutMs?: number\n /**\n * Boot-fill retry backoff schedule in milliseconds; an empty list means\n * \"try exactly once\" (default [1000, 2000, 4000, 8000, 16000, 30000]).\n */\n bootRetryDelaysMs?: number[]\n /**\n * Rewrite effort-less calls to forced-thinking ladders into the ladder's\n * vendor default (default true). Only the request class that today becomes\n * `thinking: {type: disabled}` on a ladder that cannot switch thinking off\n * is rewritten (issue #2); everything else passes through byte-identical.\n */\n defaultGuard?: boolean\n /**\n * Take over the configured request headers at the fetch layer for every route\n * whose `headers` declare one (default true). The official adapter may merge\n * attribution headers over profile values, so the overlay reapplies the\n * profile dictionary before the request reaches the wire. The historical\n * `uaOverride` name is retained for configuration compatibility.\n */\n uaOverride?: boolean\n}\n\n/** Schemastery schema: Cordis validates the row config and fills defaults before apply(). */\nexport const Config: Schema<Config> = Schema.object({\n autofill: Schema.boolean().default(true),\n modalityAutofill: Schema.boolean().default(true),\n probeTimeoutMs: Schema.natural().min(1).default(PROBE_TIMEOUT_MS),\n bootRetryDelaysMs: Schema.array(Schema.natural().min(1)).default([...BOOT_RETRY_DELAYS_MS]),\n defaultGuard: Schema.boolean().default(true),\n uaOverride: Schema.boolean().default(true),\n})\n\ninterface CredentialsService {\n resolve(ref: string): Promise<{ value?: string } | undefined>\n /** Per-reference configuration facts \u2014 never the values themselves. */\n describe?(refs: string[]): Promise<unknown>\n /** Store one value under one reference. */\n set?(ref: string, value: string): Promise<unknown>\n /** Forget one reference's value. */\n unset?(ref: string): Promise<unknown>\n}\n\n/** One row of the key manager's list, as the browser half reads it. */\ninterface KeyEntryView {\n /** Credential reference holding the value. */\n ref: string\n /** Stored label, when the user gave one. */\n alias?: string\n /** Whether the key is switched into the routing pool (its check is lit). */\n enabled: boolean\n /** Whether the store holds a value; null when the store cannot say. */\n configured: boolean | null\n /** The value in its display form, when the store let it be read. */\n masked?: string\n /** Model ids this key was discovered to serve; absent means \"unscoped\". */\n models?: readonly string[]\n /** The protocol this key pins, when it pins one (else the route's own). */\n protocol?: RouteProtocol\n /**\n * The key's cooldown, when it is resting after a failure: how long until it\n * is a normal candidate again, and how many consecutive failures produced\n * the period. Absent means the key is a normal candidate right now.\n */\n rest?: { readonly kind: string; readonly remainingMs: number; readonly failures: number }\n}\n\n/**\n * One key's routing scope as the fetch seam needs it: the reference and the\n * models it may serve, WITHOUT the secret (the seam resolves a value only for\n * the keys a request can actually reach). Kept in a small in-memory snapshot so\n * the per-request path pays no disk read.\n */\ninterface RouteKeyScope {\n readonly ref: string\n readonly models?: readonly string[]\n /** The protocol this key pins, when it pins one (else resolved per model). */\n readonly protocol?: RouteProtocol\n /** Base URL this key must use, resolved for its protocol family. */\n readonly endpoint?: string\n /**\n * The route's family addresses, carried by an UNPINNED key: its wire is\n * resolved per model (`autoWireOf`), and a model whose family names one of\n * these addresses is dispatched there. A pinned key does not need the map \u2014\n * its endpoint is already resolved above.\n */\n readonly endpoints?: RouteEndpoints\n}\n\n/** One route's profile inside a pi-ai section value, or undefined. */\nfunction providerProfileOf(section: unknown, route: string): Record<string, unknown> | undefined {\n if (!isRecord(section)) return undefined\n const providers = section['providers']\n if (!isRecord(providers)) return undefined\n const profile = providers[route]\n return isRecord(profile) ? profile : undefined\n}\n\n/** The reference one profile names as the key in use, when it names one. */\nfunction enabledRefOf(profile: Record<string, unknown> | undefined): string | undefined {\n const ref = profile?.['apiKeyEnv']\n return typeof ref === 'string' && ref.length > 0 ? ref : undefined\n}\n\n/**\n * Read the key index into the per-route scope snapshot the fetch seam reads.\n * This is metadata only \u2014 references and their discovered model lists, never a\n * secret \u2014 so it is safe to hold in memory across requests. A malformed or\n * missing index degrades to \"no scopes\", which leaves every request on the\n * adapter's own single-key path (exactly today's behaviour).\n *\n * Preference order IS the list order, so the FIRST key is the default: a model\n * every key can serve signs with it and fails over to the next (user rule A).\n * The profile's `apiKeyEnv` (the key the official page configured) is appended\n * last, unscoped, when the index has never listed it \u2014 it is a real key the\n * store holds, so it must stay reachable, but as a catch-all fallback.\n * @param providers - the live pi-ai providers map (per route's `apiKeyEnv`).\n */\nfunction readRouteKeyScopes(\n providers: Record<string, Record<string, unknown>>,\n): Record<string, readonly RouteKeyScope[]> {\n let document: ReturnType<typeof readKeyIndex>\n try {\n document = readKeyIndex(keyIndexFilePath())\n } catch {\n return {}\n }\n const scopes: Record<string, readonly RouteKeyScope[]> = {}\n const routes = new Set<string>(Object.keys(document.providers))\n for (const route of Object.keys(providers)) routes.add(route)\n for (const route of routes) {\n const endpoints = document.endpoints?.[route]\n const listed = keyEntriesOf(document, route)\n // A switched-off key leaves the pool entirely: its metadata stays on the\n // list (so switching it back on restores exactly what it served), but no\n // request may be signed with it while it is off.\n const active = listed.filter(entry => entry.disabled !== true)\n const ordered: RouteKeyScope[] = active.map(entry => {\n const scope: RouteKeyScope = { ref: entry.ref }\n if (entry.models !== undefined) (scope as { models?: readonly string[] }).models = entry.models\n if (entry.protocol !== undefined) {\n ;(scope as { protocol?: RouteProtocol }).protocol = entry.protocol\n // A key that pins a protocol also pins the endpoint of that family: the\n // provider keeps one URL per family (OpenAI, Anthropic, Gemini), and the\n // key states which wire it speaks, so the matching URL must ride along.\n const family = endpointFamilyOf(entry.protocol)\n const endpoint = endpoints?.[family]\n if (endpoint !== undefined) (scope as { endpoint?: string }).endpoint = endpoint\n } else if (endpoints !== undefined) {\n // An unpinned key is automatic: its wire is chosen per model from the\n // families the provider addressed, so the whole map rides along.\n ;(scope as { endpoints?: RouteEndpoints }).endpoints = endpoints\n }\n return scope\n })\n const seat = enabledRefOf(isRecord(providers[route]) ? providers[route] : undefined)\n // The seat joins only when the index has never listed it: a listed seat\n // speaks through its own entry, on or off \u2014 appending a switched-off seat\n // here would put the very key the user disabled back on the wire.\n if (seat !== undefined && !listed.some(entry => entry.ref === seat)) {\n // The seat is an automatic key like any listed unpinned one: it resolves\n // its wire per model family, so the route's family addresses ride along.\n // Without them a single-key provider (the key never listed in the panel)\n // would neither route to nor list the models of the families whose\n // addresses the user configured.\n const seatScope: RouteKeyScope = { ref: seat }\n if (endpoints !== undefined) (seatScope as { endpoints?: RouteEndpoints }).endpoints = endpoints\n ordered.push(seatScope)\n }\n if (ordered.length > 0) scopes[route] = ordered\n }\n return scopes\n}\n\n/** Whether a host-service answer is the refusal envelope (`{ok: false}`). */\nfunction isRefusal(answer: unknown): boolean {\n return isRecord(answer) && answer['ok'] === false\n}\n\n/** The message a host-service answer carries when it refuses. */\nfunction refusalMessage(answer: unknown): string | undefined {\n if (!isRecord(answer)) return undefined\n const error = answer['error']\n if (typeof error === 'string') return error\n if (isRecord(error) && typeof error['message'] === 'string') return error['message']\n return typeof answer['message'] === 'string' ? answer['message'] : undefined\n}\n\n/**\n * The per-reference info map a `credentials.describe()` answer carries. The\n * host service is documented to answer the map itself while the Remote face\n * wraps it in the `{ok, value}` envelope; both are read here.\n */\nfunction describeRecords(answer: unknown): Record<string, unknown> | undefined {\n const candidate = isRecord(answer) && answer['value'] !== undefined ? answer['value'] : answer\n return isRecord(candidate) ? candidate : undefined\n}\n\n/** Store one value under one reference; the refusal text, or undefined. */\nasync function storeCredential(\n credentials: CredentialsService | undefined,\n ref: string,\n value: string,\n): Promise<string | undefined> {\n const set = credentials?.set\n if (credentials === undefined || typeof set !== 'function') {\n return 'this deployment cannot write the credential store'\n }\n try {\n const answer = await set.call(credentials, ref, value)\n if (!isRefusal(answer)) return undefined\n return refusalMessage(answer) ?? `the credential store refused ${ref}`\n } catch (error) {\n return error instanceof Error ? error.message : String(error)\n }\n}\n\n/** Forget one reference's value; the refusal text, or undefined. */\nasync function forgetCredential(credentials: CredentialsService | undefined, ref: string): Promise<string | undefined> {\n const unset = credentials?.unset\n if (credentials === undefined || typeof unset !== 'function') {\n return 'this deployment cannot write the credential store'\n }\n try {\n const answer = await unset.call(credentials, ref)\n if (!isRefusal(answer)) return undefined\n return refusalMessage(answer) ?? `the credential store refused to forget ${ref}`\n } catch (error) {\n return error instanceof Error ? error.message : String(error)\n }\n}\n\n/** A host dependency failed to answer a read; never report this as absence. */\nclass HostReadError extends Error {}\n\nasync function resolveCredential(credentials: CredentialsService | undefined, ref: string): Promise<string | undefined> {\n if (credentials === undefined || typeof credentials.resolve !== 'function') {\n throw new HostReadError('the credential store is unavailable')\n }\n let hit: unknown\n try {\n hit = await credentials.resolve(ref)\n } catch {\n throw new HostReadError('the credential store could not read the reference')\n }\n if (isRefusal(hit) || (hit !== undefined && !isRecord(hit))) {\n throw new HostReadError('the credential store could not read the reference')\n }\n if (hit === undefined) return undefined\n const value = (hit as Record<string, unknown>)['value']\n if (value !== undefined && typeof value !== 'string') {\n throw new HostReadError('the credential store returned an invalid value')\n }\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/** What the store will say about one reference: configured, and its masked value. */\ninterface CredentialFacts {\n configured: boolean\n masked?: string\n}\n\n/**\n * What the store will say about each reference: whether it holds a value, and \u2014\n * when the value can be read \u2014 the display form the list shows beside it.\n *\n * `describe` answers `configured` without handing the secret over, which is all\n * a badge needs; the masked preview needs the value itself, so it comes from\n * `resolve`, the same call the eye already makes. `describe` stays authoritative\n * about `configured` when both answer. A reference neither can speak about is\n * simply absent from the map.\n */\nasync function credentialFacts(\n credentials: CredentialsService | undefined,\n refs: readonly string[],\n): Promise<Record<string, CredentialFacts>> {\n const out: Record<string, CredentialFacts> = {}\n if (credentials === undefined || refs.length === 0) return out\n const describe = credentials.describe\n if (typeof describe === 'function') {\n try {\n const answer = await describe.call(credentials, [...refs])\n const records = isRefusal(answer) ? undefined : describeRecords(answer)\n for (const ref of refs) {\n const info = records?.[ref]\n if (isRecord(info) && typeof info['configured'] === 'boolean') {\n out[ref] = { configured: info['configured'] }\n }\n }\n } catch {\n // Unanswered references fall through to resolve() below.\n }\n }\n for (const ref of refs) {\n try {\n const value = await resolveCredential(credentials, ref)\n const configured = out[ref]?.configured ?? (value !== undefined && value.length > 0)\n const masked = value === undefined ? undefined : maskKeyValue(value)\n out[ref] = masked === undefined || masked.length === 0 ? { configured } : { configured, masked }\n } catch {\n // Leave it unknown: a badge is not worth failing the list over.\n }\n }\n return out\n}\n\n/**\n * Which references hold a value, as far as the store will say.\n *\n * Kept as the narrow question for callers that only badge the list; the list\n * itself asks `credentialFacts` so one read answers both.\n */\nasync function credentialConfigured(\n credentials: CredentialsService | undefined,\n refs: readonly string[],\n): Promise<Record<string, boolean>> {\n const facts = await credentialFacts(credentials, refs)\n const out: Record<string, boolean> = {}\n for (const ref of refs) {\n const configured = facts[ref]?.configured\n if (configured !== undefined) out[ref] = configured\n }\n return out\n}\n\n/** Whether a settings write was refused because the document moved under it. */\nfunction isConflictError(error: unknown): boolean {\n return isRecord(error) && error['code'] === 'SETTINGS_CONFLICT'\n}\n\n/** Read a small JSON request body; undefined when there is nothing to read. */\nasync function readJsonBody(req: IncomingMessage, limit = 8192): Promise<unknown> {\n const decoder = new TextDecoder()\n let text = ''\n try {\n for await (const chunk of req as AsyncIterable<Uint8Array | string>) {\n text += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true })\n // A provider key is short; anything larger is not a body this route serves.\n if (text.length > limit) return undefined\n }\n } catch {\n return undefined\n }\n if (text.length === 0) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return undefined\n }\n}\n\nfunction isLoopbackHostname(hostname: string): boolean {\n return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1'\n}\n\n/** WHATWG-parse a Host/Origin authority (`host` or `host:port`). */\nfunction parseAuthority(authority: string): URL | undefined {\n try {\n // http: is a WHATWG special scheme: parsing yields a hostname or throws,\n // and normalizes casing the raw header keeps. Note the hostname of an\n // IPv6 authority KEEPS its brackets (`[::1]`) \u2014 the literal check below\n // deliberately matches on the colon.\n return new URL(`http://${authority}`)\n } catch {\n return undefined\n }\n}\n\n/**\n * Whether a parsed hostname is an IP literal (IPv4 dotted quad, or IPv6 whose\n * brackets URL parsing already stripped). A browser fills Host from the URL it\n * believes it is talking to, so a DNS-rebound page ALWAYS carries the\n * attacker's domain here \u2014 it can never produce an IP-literal Host short of\n * the user genuinely navigating to that IP.\n */\nfunction isIpLiteralHostname(hostname: string): boolean {\n return /^\\d{1,3}(\\.\\d{1,3}){3}$/.test(hostname) || hostname.includes(':')\n}\n\n/**\n * Browser trust fence for the probe route. It mirrors the core /api fence's\n * DEFENSE (packages/client/connection/src/api-request-trust.ts) minus one\n * feature: there is no `trustedHosts` escape hatch yet.\n *\n * - Cross-site requests are refused outright; a same-origin/same-site\n * marker never ADMITS anything by itself.\n * - An attached Origin must name exactly this authority; the literal\n * `null` (sandboxed iframe, file: page) is refused.\n * - The Host fence binds every request and is the rebinding defense:\n * only loopback names and IP literals are answered. A rebound page\n * names the attacker's DOMAIN in Host even though the socket lands on\n * this server, so named hosts are always 403.\n *\n * The route proxies only endpoints the user's own settings already name, but\n * it does so with the stored credential attached \u2014 so it must not be callable\n * from elsewhere. LAN deployments serving the GUI under a DOMAIN name get 403\n * here by design (IP-literal LAN hosts keep working); see README known\n * limitations until a trustedHosts seam exists.\n */\nfunction isTrustedRequest(req: IncomingMessage): boolean {\n const host = req.headers.host\n if (typeof host !== 'string' || host.length === 0) return false\n const hostUrl = parseAuthority(host)\n if (hostUrl === undefined) return false\n const secFetchSite = req.headers['sec-fetch-site']\n if (secFetchSite === 'cross-site') return false\n const origin = req.headers.origin\n if (typeof origin === 'string') {\n if (origin === 'null') return false\n try {\n if (new URL(origin).host !== hostUrl.host) return false\n } catch {\n return false\n }\n }\n const hostname = hostUrl.hostname.toLowerCase()\n return isLoopbackHostname(hostname) || isIpLiteralHostname(hostname)\n}\n\nfunction sendJson(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json; charset=utf-8')\n res.end(JSON.stringify(body))\n}\n\n/**\n * The llm-service surface the default-guard wraps: only the two dispatch\n * entries, typed structurally so no new dependency is needed.\n */\ninterface LlmDispatchLike {\n prepareCall(config: Record<string, unknown>, signal?: unknown): Promise<Record<string, unknown>>\n stream(options: Record<string, unknown>): AsyncIterable<unknown>\n}\n\n/**\n * Fill one call config with the vendor default when it names no effort and\n * its declared ladder cannot switch thinking off (issue #2).\n *\n * Reads the resolved pi-ai section (never the user layer -- this only reads).\n * Fails open: any unreadable shape returns the config untouched, reproducing\n * today's behavior exactly.\n */\nfunction guardCallConfig(cfg: Record<string, unknown>, section: unknown): Record<string, unknown> {\n try {\n if (typeof cfg['reasoningEffort'] !== 'undefined') return cfg\n const provider = cfg['provider']\n const modelId = cfg['model']\n if (typeof provider !== 'string' || typeof modelId !== 'string') return cfg\n if (!isRecord(section)) return cfg\n const providers = section['providers']\n if (!isRecord(providers)) return cfg\n const profile = providers[provider]\n if (!isRecord(profile)) return cfg\n const rawModels = profile['models']\n if (!Array.isArray(rawModels)) return cfg\n const row = rawModels.find((candidate): candidate is Record<string, unknown> =>\n isRecord(candidate) && candidate['id'] === modelId)\n if (row === undefined || !isRecord(row['reasoningEfforts'])) return cfg\n const profileDefault = typeof profile['reasoning'] === 'string' ? profile['reasoning'] : undefined\n const facts = routeFactsOf({ providers: { [provider]: profile } }, provider)\n const suggestion = suggestEfforts(modelId, facts)\n const level = resolveGuardEffort({\n declared: row['reasoningEfforts'] as ReasoningEfforts,\n vendorDefault: suggestion.defaultEffort,\n profileDefault,\n requested: undefined,\n })\n return level === undefined ? cfg : { ...cfg, reasoningEffort: level }\n } catch {\n return cfg\n }\n}\n\n/**\n * Apply the plugin: autofill undeclared models on boot and after every commit\n * that touches the pi-ai namespace.\n * @param ctx - host context.\n */\nexport function apply(ctx: Context, config: Config = {}): void {\n // Cordis fills schema defaults; direct calls (tests) may omit fields.\n const resolved = {\n autofill: config.autofill !== false,\n modalityAutofill: config.modalityAutofill !== false,\n probeTimeoutMs: config.probeTimeoutMs ?? PROBE_TIMEOUT_MS,\n bootRetryDelaysMs: config.bootRetryDelaysMs ?? [...BOOT_RETRY_DELAYS_MS],\n defaultGuard: config.defaultGuard !== false,\n uaOverride: config.uaOverride !== false,\n }\n\n // Module-level `inject` already guarantees the settings service; using it\n // directly (instead of a redundant inner ctx.inject) keeps one dependency\n // declaration as the single source of truth.\n const settings = ctx.settings\n\n // The guard and probe route read the pi-ai section through this cached\n // closure slot. Describing every active form on every model call is both\n // needless work and, on 0.1.7+, can publish revision invalidation; retain the\n // last resolved section until the settings document reports that it moved.\n let piSectionCache: unknown\n let piSectionCached = false\n const piSection = (required = false): unknown => {\n if (piSectionCached) return piSectionCache\n let value: unknown\n try {\n value = settings.describe().find(entry => entry.ns === PI_NS)?.value\n } catch {\n if (required) throw new HostReadError('the llm-pi-ai settings could not be read')\n // Dispatch guards remain advisory while interactive routes report errors.\n return undefined\n }\n // A missing namespace is expected during boot and must be retried.\n if (value === undefined) {\n if (required) throw new HostReadError('the llm-pi-ai settings entry is unavailable')\n return undefined\n }\n piSectionCache = value\n piSectionCached = true\n return value\n }\n ctx.on('settings/document-updated', (ns) => {\n if (ns === PI_NS) piSectionCached = false\n })\n\n if (resolved.autofill) {\n /** One autofill pass; resolves false while the pi-ai namespace is unregistered. */\n const autofillOnce = async (): Promise<boolean> => {\n const descriptor = settings.describe().find(entry => entry.ns === PI_NS)\n if (!isRecord(descriptor?.value)) return false\n // Build the patch from the RAW USER layer, never the resolved value:\n // the fill merges into the user document, and building from the\n // resolved view would materialize schema defaults / composition-base\n // models into it wholesale the moment pi-ai grows such layers for its\n // profile. A namespace whose user section holds no providers has\n // nothing this plugin may fill.\n const user = descriptor?.user\n const userProviders = isRecord(user) && isRecord(user['providers']) ? user['providers'] : undefined\n if (userProviders === undefined) return true\n const fullPatch = buildAutofillPatch(userProviders, () => true, { modalities: resolved.modalityAutofill }, descriptor?.revision ?? 0)\n if (fullPatch === undefined) return true\n // Optimistic lock: only write while the namespace has not moved past\n // this read. The fill is a background suggestion -- losing the race to a\n // user edit is fine; a later boot, or the browser half's idle pass,\n // simply fills whatever is still undeclared. Without the lock every fill\n // would bump the revision and invalidate the one the settings page read,\n // surfacing as SettingsConflictError on the next user save.\n try {\n await settings.update(PI_NS, fullPatch, descriptor?.revision)\n } catch (error) {\n const msg = String(error instanceof Error ? error.message : error)\n if (!looksLikeCompatRefusal(msg)) throw error\n const stripped = stripNewCompatKeysDeep(fullPatch)\n if (stripped === undefined) throw error\n await settings.update(PI_NS, stripped, settings.describe().find(entry => entry.ns === PI_NS)?.revision)\n }\n return true\n }\n\n /** Auto-fill must never break the settings pipeline; log and move on. */\n const logFailure = (error: unknown): void => {\n console.error(`[dsh-model-think-level] autofill failed: ${error instanceof Error ? error.message : String(error)}`)\n }\n\n // Pending boot-retry timers, cleared with the fiber (a disposed plugin\n // must not fire into a torn-down service graph).\n const timers = new Set<ReturnType<typeof setTimeout>>()\n ctx.effect(() => () => {\n for (const timer of timers) clearTimeout(timer)\n timers.clear()\n }, 'dsh-model-think-level: boot-fill retries')\n\n // Fill once at boot for models declared before this plugin was installed,\n // backing off exponentially while llm-pi-ai has not registered yet.\n const bootFill = (attempt: number): void => {\n void autofillOnce().then((ready) => {\n if (ready || attempt >= resolved.bootRetryDelaysMs.length) return\n const timer = setTimeout(() => {\n timers.delete(timer)\n bootFill(attempt + 1)\n }, resolved.bootRetryDelaysMs[attempt])\n timers.add(timer)\n }, logFailure)\n }\n bootFill(0)\n\n // Deliberately NOT re-run on `settings/document-updated`. The boot pass is safe\n // (no settings surface is open yet); a fill the moment a commit lands is\n // not: the official Models card freezes its own revision baseline while it\n // is open, so a background write there makes the user's very next save in\n // that card fail with `settings/conflict` and their edit reads as lost\n // (issue #7). The browser half carries the running complement instead: it\n // builds this SAME patch and writes it on its idle pass, once no card is\n // open. A headless composition has no editing surface to break and no\n // browser half either -- boot covers it.\n }\n\n // Default-guard (issue #2): wrap the llm dispatch entries so effort-less\n // calls to forced-thinking ladders ride the ladder's vendor default instead\n // of the wire's off-equivalent. Deferred inject: the wrap lands whenever\n // the llm service registers, and ctx.effect restores the originals on\n // dispose (disable/HMR leaves no trace).\n if (resolved.defaultGuard) {\n ctx.inject(['llm'], (llmCtx) => {\n const llm = (llmCtx as unknown as { llm?: unknown }).llm as LlmDispatchLike | undefined\n if (llm === undefined || typeof llm.prepareCall !== 'function' || typeof llm.stream !== 'function') return\n // Unbound originals: restore assigns back the exact references, and\n // dispatch keeps the service as receiver through .call.\n const origPrepare = llm.prepareCall\n const origStream = llm.stream\n let disposed = false\n const prepare: LlmDispatchLike['prepareCall'] = (callConfig, signal) =>\n origPrepare.call(llm, disposed ? callConfig : guardCallConfig(callConfig, piSection()), signal)\n const stream: LlmDispatchLike['stream'] = (options) =>\n origStream.call(llm, disposed ? options : guardCallConfig(options, piSection()))\n llm.prepareCall = prepare\n llm.stream = stream\n ctx.effect(() => () => {\n disposed = true\n if (llm.prepareCall === prepare) llm.prepareCall = origPrepare\n if (llm.stream === stream) llm.stream = origStream\n }, 'dsh-model-think-level: default-guard')\n })\n }\n\n // Request-header takeover (issue #12): the official adapter can merge\n // attribution headers over the profile's own dictionary, so configured\n // values may be lost before the request reaches the wire. The plugin keeps\n // the fetch overlay as a compatibility fallback and also uses pi-ai's\n // request-level transform, which runs after auth/default headers are merged.\n // This mirrors the request-scoped header handling used by PI-Desktop and\n // covers SDK transports that do not call the current global fetch function.\n //\n // The index is keyed by the endpoint's ORIGIN and rebuilt from the live\n // settings section, so a route added, edited, or removed on the Models page\n // reaches the next request with no reload. `uaOverride: false` empties the\n // index instead of skipping the install: both seams stay installed and\n // simply stop matching anything.\n /** Live index the overlay reads; never undefined once apply has run. */\n const overlaySource: OverlaySource = { current: emptyIndex() }\n // Per-route key scopes (references + discovered model lists, never secrets)\n // the fetch seam uses to choose and fail over across keys. Kept as a live\n // snapshot so the hot request path reads memory, not disk.\n const keyScopes: { current: Record<string, readonly RouteKeyScope[]> } = { current: {} }\n const providersOf = (): Record<string, Record<string, unknown>> => {\n const section = piSection()\n return isRecord(section) && isRecord(section['providers'])\n ? (section['providers'] as Record<string, Record<string, unknown>>)\n : {}\n }\n const refreshKeyScopes = (): void => { keyScopes.current = readRouteKeyScopes(providersOf()) }\n const headerRetryTimers = new Set<ReturnType<typeof setTimeout>>()\n let headerRetryAttempt = 0\n const stopHeaderRetries = (): void => {\n for (const timer of headerRetryTimers) clearTimeout(timer)\n headerRetryTimers.clear()\n headerRetryAttempt = 0\n }\n const scheduleHeaderRefresh = (refresh: () => void): void => {\n // A settings event may arrive while a retry is already pending. Keep one\n // timer per activation so repeated document notifications cannot accelerate\n // or multiply the boot retry sequence.\n if (headerRetryTimers.size > 0 || headerRetryAttempt >= resolved.bootRetryDelaysMs.length) return\n const delay = resolved.bootRetryDelaysMs[headerRetryAttempt]\n headerRetryAttempt += 1\n const timer = setTimeout(() => {\n headerRetryTimers.delete(timer)\n refresh()\n }, delay)\n headerRetryTimers.add(timer)\n }\n const refreshHeaders = (): void => {\n if (!resolved.uaOverride) {\n overlaySource.current = emptyIndex()\n stopHeaderRetries()\n return\n }\n const section = piSection()\n if (section === undefined) {\n // llm-pi-ai can register its settings namespace after this plugin. The\n // model probe has an independent direct-header path, but chat needs this\n // index ready before the adapter's first stream reaches fetch().\n overlaySource.current = emptyIndex()\n scheduleHeaderRefresh(refreshHeaders)\n return\n }\n stopHeaderRetries()\n const providers = isRecord(section) && isRecord(section['providers'])\n ? (section['providers'] as Record<string, Record<string, unknown>>)\n : {}\n overlaySource.current = buildHeaderIndex(providers)\n }\n refreshHeaders()\n refreshKeyScopes()\n ctx.effect(() => () => stopHeaderRetries(), 'dsh-model-think-level: header retries')\n ctx.on('settings/document-updated', (ns) => {\n if (ns === PI_NS) {\n refreshHeaders()\n refreshKeyScopes()\n }\n })\n /**\n * Resolve the ordered keys that may sign one matched request. The preference\n * order is the key index's list order; `keysForModel` narrows to the keys\n * whose scope can serve this model, falling back to the full list so a stale\n * or over-eager scope can never strand a model that some key can reach. Each\n * candidate's value is resolved fresh (a rotated/replaced key is honoured on\n * the next request); a reference whose value the store cannot confirm is\n * skipped, leaving the remaining keys \u2014 and, if none resolve, the adapter's\n * own single-key path \u2014 to serve.\n */\n overlaySource.keys = async ({ route, model }) => {\n const scopes = keyScopes.current[route] ?? []\n if (scopes.length === 0) return []\n const ordered = keysForModel(\n scopes.map(scope => ({ ref: scope.ref, value: '', models: scope.models })),\n model,\n )\n // Resolve every reference in parallel (this sits on the request hot path:\n // sequential IPC per key would stack latency per key) and keep the planned\n // order; a reference whose value the store cannot confirm resolves to\n // undefined and is skipped, leaving the remaining keys \u2014 and, if none\n // resolve, the adapter's own single-key path \u2014 to serve.\n const credentials = ctx.get('credentials') as CredentialsService | undefined\n const values = await Promise.all(ordered.map(async candidate => {\n try {\n return await resolveCredential(credentials, candidate.ref)\n } catch {\n return undefined\n }\n }))\n const candidates: KeyCandidate[] = []\n for (let index = 0; index < ordered.length; index += 1) {\n const value = values[index]\n if (value === undefined) continue\n const candidate = ordered[index]\n const scope = scopes.find(entry => entry.ref === candidate.ref)\n const resolved: KeyCandidate = { ref: candidate.ref, value, models: candidate.models }\n if (scope?.protocol !== undefined) (resolved as { protocol?: RouteProtocol }).protocol = scope.protocol\n if (scope?.endpoint !== undefined) (resolved as { endpoint?: string }).endpoint = scope.endpoint\n // An unpinned key is automatic: it carries the family addresses its wire\n // resolution (`wireOf`) may pick from, one per endpoint family.\n if (scope?.endpoints !== undefined) (resolved as { endpoints?: KeyCandidate['endpoints'] }).endpoints = scope.endpoints\n candidates.push(resolved)\n }\n return candidates\n }\n overlaySource.modelListing = async ({ route, headers, keys, signal, send }) => {\n const profile = providerProfileOf(piSection(), route)\n const api = normalizeKeyProtocol(profile?.['api'])\n const baseURL = typeof profile?.['baseURL'] === 'string' ? profile['baseURL'].trim() : ''\n if (api === undefined || !LISTABLE_PROTOCOLS.has(api) || baseURL.length === 0) return undefined\n\n // Shares the probe-and-merge the panel and the `discover` operation use, so\n // the catalogue the host's own discovery sees is the census the plugin would\n // report: bounded concurrency, and one key's refusal never drops the others.\n // A listing record carries more than its id (display name, limits), so the\n // full records are kept per key and stitched back in merged order below.\n const recordsByRef = new Map<string, ListedModel[]>()\n const { results } = await collectKeyListings({\n keys,\n refOf: key => key.ref,\n probe: async key => {\n // A pinned key is asked on its own wire; an automatic key is asked on\n // every wire it could dispatch on \u2014 the route's wire, plus each\n // cross-family address it carries \u2014 so the catalogue covers the models\n // of all of them, the same union `probeKeyModels` records for the key\n // panel. A same-family address is skipped: the route's own URL serves\n // that family, and requests would never be dispatched elsewhere.\n const targets: { api: RouteProtocol; baseURL: string }[] = key.protocol !== undefined\n ? [{ api: key.protocol, baseURL: key.endpoint ?? baseURL }]\n : [\n { api, baseURL },\n ...Object.entries(key.endpoints ?? {})\n .filter(([family]) => family !== endpointFamilyOf(api))\n .map(([family, url]) => ({ api: FAMILY_PROTOCOL[family as EndpointFamily], baseURL: url ?? '' })),\n ]\n const sendListing = (url: string, init: RequestInit): Promise<Response> => {\n const requestHeaders = new Headers(headers)\n requestHeaders.delete('authorization')\n requestHeaders.delete('x-api-key')\n requestHeaders.delete('x-goog-api-key')\n new Headers(init.headers).forEach((value, name) => requestHeaders.set(name, value))\n const requestSignal = signal == null\n ? init.signal\n : init.signal == null\n ? signal\n : AbortSignal.any([signal, init.signal])\n return send(url, { ...init, headers: requestHeaders, signal: requestSignal })\n }\n const asked = new Set<string>()\n const records: ListedModel[] = []\n for (const target of targets) {\n if (!LISTABLE_PROTOCOLS.has(target.api) || target.baseURL.length === 0) continue\n const url = probeListingUrl(target.baseURL, target.api)\n // A gateway that spells one listing under two protocols is asked once.\n if (asked.has(url)) continue\n asked.add(url)\n const listing = await probeListing({\n baseURL: target.baseURL,\n api: target.api,\n apiKey: key.value,\n headers: profile?.['headers'],\n timeoutMs: resolved.probeTimeoutMs,\n send: sendListing,\n })\n if (listing === undefined) continue\n for (const model of listing) {\n if (records.some(existing => existing.id === model.id)) continue\n records.push(model)\n }\n }\n if (records.length === 0) return { ref: key.ref, models: undefined, targets: [] }\n recordsByRef.set(key.ref, records)\n return {\n ref: key.ref,\n models: records.map(model => model.id),\n targets: [],\n }\n },\n })\n const records = new Map<string, ListedModel>()\n for (const result of results) {\n for (const model of recordsByRef.get(result.ref) ?? []) {\n if (!records.has(model.id)) records.set(model.id, model)\n }\n }\n const models = mergeKeyListings(results).ids\n .map(id => records.get(id))\n .filter((model): model is ListedModel => model !== undefined)\n if (models.length === 0) return undefined\n return new Response(JSON.stringify({ data: models }), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n }\n const overlay = installHeaderOverlay(overlaySource)\n ctx.effect(() => () => { overlay.dispose() }, 'dsh-model-think-level: fetch header overlay')\n\n // `?diag=1` on the probe route reports this without touching the wire, so\n // the request-header takeover is observable from the running host.\n let headerBridgeState: () => unknown = () => ({ stage: 'not-installed' })\n const installPiAiBridge = (llm: unknown): void => {\n const transforms = installPiAiHeaderTransforms(llm, overlaySource)\n transforms.refresh()\n headerBridgeState = () => describePiAiHeaderState(llm, overlaySource)\n ctx.on('llm/adapters-updated', () => transforms.refresh())\n ctx.effect(() => () => transforms.dispose(), 'dsh-model-think-level: pi-ai request headers')\n }\n const availableLlm = (ctx as unknown as { llm?: unknown }).llm\n if (availableLlm === undefined) {\n // Direct callers and older hosts may omit llm from the module-level inject;\n // keep the deferred path as a compatibility fallback for those contexts.\n ctx.inject(['llm'], (llmCtx) => {\n const llm = (llmCtx as unknown as { llm?: unknown }).llm\n if (llm !== undefined) installPiAiBridge(llm)\n })\n } else {\n installPiAiBridge(availableLlm)\n }\n\n // Read once: what sits on disk changes only when the user installs or patches\n // something, and a restart is the honest moment to re-read it.\n const environmentConflicts: HeaderConflictReport = detectHeaderConflicts()\n\n // Same-origin probe route: the browser half's Auto-adapt asks the endpoint's\n // RAW /models listing through here, because the sanctioned llm wire call\n // strips reasoning signals host-side. The credential resolves server-side\n // and never echoes back; only routes the user's own settings name are\n // reachable, and the trust fence rejects cross-site callers.\n ctx.inject(['webServer'], (webServerCtx) => {\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: PROBE_PATH,\n handler: async (req, res) => {\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const url = new URL(req.url ?? '/', 'http://x')\n // Read-only diagnostics: makes the request-header takeover\n // observable in the running host (which adapter is patched).\n if (url.searchParams.get('diag') === '1') {\n sendJson(res, 200, {\n ok: true,\n bridge: headerBridgeState(),\n overlay: {\n routes: overlaySource.current.routes.length,\n overrides: overlaySource.current.overrides.length,\n },\n })\n return\n }\n const route = url.searchParams.get('route') ?? ''\n let section: unknown\n try {\n section = piSection(true)\n } catch {\n sendJson(res, 502, { ok: false, error: 'the llm-pi-ai settings could not be read' })\n return\n }\n const profile = isRecord(section) && isRecord(section['providers'])\n ? section['providers'][route]\n : undefined\n if (!isRecord(profile)) {\n sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route \"${route}\"` })\n return\n }\n const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'] : ''\n if (baseURL.length === 0) {\n sendJson(res, 400, { ok: false, error: `provider route \"${route}\" has no baseURL` })\n return\n }\n // The profile's wire protocol selects the listing route and the\n // credential arm, exactly as the official discovery decides them:\n // only the protocols whose listing this mirror can read are\n // interrogated; everything else reports that it cannot.\n const api = typeof profile['api'] === 'string' ? profile['api'] : ''\n if (api.length === 0) {\n sendJson(res, 400, {\n ok: false,\n error: `provider route \"${route}\" names no API protocol to interrogate`,\n })\n return\n }\n if (!LISTABLE_PROTOCOLS.has(api)) {\n sendJson(res, 400, {\n ok: false,\n error: `protocol \"${api}\" cannot be interrogated; enter this provider's models by hand`,\n })\n return\n }\n const apiKeyEnv = typeof profile['apiKeyEnv'] === 'string' ? profile['apiKeyEnv'] : undefined\n const listingURL = probeListingUrl(baseURL, api)\n let apiKey: string | undefined\n if (apiKeyEnv !== undefined) {\n try {\n apiKey = await resolveCredential(ctx.get('credentials') as CredentialsService | undefined, apiKeyEnv)\n } catch {\n sendJson(res, 502, { ok: false, error: 'the credential store could not read the reference' })\n return\n }\n }\n try {\n // This probe composes its own auth from the profile's reference, so\n // it must bypass the key-routing wrapper: that wrapper would re-sign\n // the request with the route's first key, probing the wrong credential.\n const upstream = await headerOverlayBypass()(listingURL, {\n method: 'GET',\n // Header composition mirrors the harness's own model discovery:\n // the profile's configured request headers ride\n // along, so a deployment that authenticates through a custom\n // header probes here exactly as it lists officially \u2014 and an\n // Anthropic endpoint answers through x-api-key + a fixed\n // anthropic-version instead of a Bearer.\n headers: composeProbeHeaders(profile['headers'], apiKey, api),\n // A probe carries the user's stored credential, so it must\n // reach exactly the authority the profile names: Fetch's\n // default would FOLLOW a cross-origin redirect, and the\n // headers composed here (`x-api-key`, a profile's own auth\n // header) are not stripped on that hop the way `authorization`\n // is. Official discovery keeps the default; this route is\n // stricter on purpose, and the cost is bounded \u2014 a gateway\n // that lists only behind a redirect yields no endpoint\n // evidence, so Auto-adapt falls back to the knowledge base /\n // protocol inference, the path every unanswerable endpoint\n // takes.\n redirect: 'error',\n signal: AbortSignal.timeout(resolved.probeTimeoutMs),\n })\n if (!upstream.ok) {\n const hint = upstream.status === 401 || upstream.status === 403 ? '; check the API key' : ''\n sendJson(res, 502, { ok: false, error: `${displayUrl(listingURL)} answered ${upstream.status}${hint}` })\n return\n }\n const text = await readBounded(upstream, listingURL)\n let body: unknown\n try {\n body = JSON.parse(text) as unknown\n } catch {\n sendJson(res, 502, { ok: false, error: `${displayUrl(listingURL)} answered with a malformed JSON body` })\n return\n }\n // The official parser accepts the standard `data` array and the\n // enriched `models` map; entries are passed through verbatim so\n // the browser half sees the raw capability signals the sanctioned\n // wire call strips.\n const entries = listingEntries(body)\n if (entries === undefined) {\n sendJson(res, 502, {\n ok: false,\n error: `${displayUrl(listingURL)} model listing has neither a \"data\" array nor a \"models\" object`,\n })\n return\n }\n sendJson(res, 200, { ok: true, url: displayUrl(listingURL), data: entries })\n } catch (error) {\n sendJson(res, 502, {\n ok: false,\n error: `could not reach ${displayUrl(listingURL)}: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n },\n }),\n 'dsh-model-think-level: raw-models probe route',\n )\n\n // Read-only diagnostics for the request-header takeover. A path of its own\n // (rather than a flag on the probe route) so a reloaded plugin can answer\n // even while an older instance still owns the probe path.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: DIAG_PATH,\n handler: (req, res) => {\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n sendJson(res, 200, {\n ok: true,\n uaOverride: resolved.uaOverride,\n bridge: headerBridgeState(),\n overlay: {\n routes: overlaySource.current.routes.length,\n overrides: overlaySource.current.overrides.length,\n },\n })\n },\n }),\n 'dsh-model-think-level: header diagnostics route',\n )\n\n // Stored-credential route: the API-key field's eye calls it when the user\n // asks to see a key that is already saved. Every other route here keeps the\n // value host-side; this one hands it to the page on purpose, because the\n // official field is write-only by design \u2014 the settings document carries\n // only the profile's `apiKeyEnv` reference \u2014 so the affordance would\n // otherwise be a mask toggle with nothing behind it. The same trust fence\n // as the probe gates it, the value is never logged, and every answer is\n // `no-store` so neither the key nor the refusals (which name the route's\n // reference) can sit in a cache. The browser half asks only on a click, and\n // only for a card that names a route.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: PROVIDER_KEY_PATH,\n handler: async (req, res) => {\n // Nothing this route answers may sit in a cache: not the key, and\n // not the refusals that name the route's credential reference.\n res.setHeader('cache-control', 'no-store')\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const url = new URL(req.url ?? '/', 'http://x')\n const route = url.searchParams.get('route') ?? ''\n let section: unknown\n try {\n section = piSection(true)\n } catch {\n sendJson(res, 502, { ok: false, error: 'the llm-pi-ai settings could not be read' })\n return\n }\n const profile = isRecord(section) && isRecord(section['providers'])\n ? section['providers'][route]\n : undefined\n if (!isRecord(profile)) {\n sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route \"${route}\"` })\n return\n }\n const apiKeyEnv = typeof profile['apiKeyEnv'] === 'string' ? profile['apiKeyEnv'] : undefined\n // A key-manager row names its own reference; the field's own eye\n // names none and means \"the key this provider is using\". A named\n // one is served only when the route's index lists it, so this route\n // can never become a resolver for arbitrary reference names.\n const named = url.searchParams.get('ref') ?? ''\n let ref: string | undefined\n try {\n ref = named.length > 0\n ? (named === apiKeyEnv || hasKeyEntry(readKeyIndex(keyIndexFilePath()), route, named) ? named : undefined)\n : apiKeyEnv\n } catch {\n sendJson(res, 500, { ok: false, error: 'the key index could not be read' })\n return\n }\n if (ref === undefined) {\n sendJson(res, 404, {\n ok: false,\n error: named.length > 0\n ? `provider route \"${route}\" lists no key \"${named}\"`\n : `provider route \"${route}\" stores no credential reference`,\n })\n return\n }\n let value: string | undefined\n try {\n value = await resolveCredential(ctx.get('credentials') as CredentialsService | undefined, ref)\n } catch {\n sendJson(res, 502, { ok: false, error: 'the credential store could not read the reference' })\n return\n }\n if (value === undefined) {\n sendJson(res, 404, { ok: false, error: `no credential is configured for ${ref}` })\n return\n }\n sendJson(res, 200, { ok: true, key: value })\n },\n }),\n 'dsh-model-think-level: provider-key route',\n )\n\n // The API-key manager: one provider's list of keys, and which one is in use.\n //\n // Both halves of that list are host-side already \u2014 the values belong to the\n // harness credential store, and the reference the adapter actually resolves\n // is a field of the pi-ai profile \u2014 so this route owns the reads AND the\n // writes and the browser half only ever handles references, labels and\n // booleans. That is the same surface the official page works with, and it\n // needs no new Remote face to get it.\n let keyMutationTail = Promise.resolve()\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: KEY_INDEX_PATH,\n handler: async (req, res) => {\n res.setHeader('cache-control', 'no-store')\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET' && req.method !== 'POST') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const url = new URL(req.url ?? '/', 'http://x')\n const route = url.searchParams.get('route') ?? ''\n let releaseMutation: (() => void) | undefined\n try {\n if (req.method === 'POST') {\n // Routes can share credential refs, including normalized names.\n // Keep each write/rollback sequence together; reads never queue.\n const previous = keyMutationTail\n keyMutationTail = new Promise<void>(resolve => { releaseMutation = resolve })\n await previous\n }\n // Read the entry fresh rather than through the cached section: this\n // route writes to it, and an answer built from a pre-write snapshot\n // would show the user the state they just changed away from.\n const entryOf = (): { value: unknown; revision: number } | undefined => {\n try {\n const found = settings.describe().find(candidate => candidate.ns === PI_NS)\n if (found === undefined) throw new HostReadError('the llm-pi-ai settings entry is unavailable')\n return { value: found.value, revision: found.revision }\n } catch {\n throw new HostReadError('the llm-pi-ai settings could not be read')\n }\n }\n if (route.length === 0 || providerProfileOf(entryOf()?.value, route) === undefined) {\n sendJson(res, 400, { ok: false, error: `no llm-pi-ai provider route \"${route}\"` })\n return\n }\n const credentials = ctx.get('credentials') as CredentialsService | undefined\n const indexFile = keyIndexFilePath()\n\n /** The reference the profile names right now, read fresh. */\n const enabledNow = (): string | undefined => enabledRefOf(providerProfileOf(entryOf()?.value, route))\n\n /**\n * Hand the \"in use\" seat to one reference; undefined clears it. The\n * seat IS the profile's `apiKeyEnv`, so nothing else has to know\n * which key is active \u2014 every consumer of the profile, in the GUI or\n * not, resolves exactly the key the user enabled.\n * @param ref - reference to enable, or undefined to name none.\n * @returns The refusal text, or undefined when the write landed.\n */\n const setEnabledKey = async (ref: string | undefined): Promise<string | undefined> => {\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const entry = entryOf()\n if (entry === undefined) return 'the llm-pi-ai settings entry is unavailable'\n try {\n await settings.mutate(\n PI_NS,\n ref === undefined\n ? [{ op: 'unset', path: ['providers', route, 'apiKeyEnv'] }]\n : [{ op: 'set', path: ['providers', route, 'apiKeyEnv'], value: ref }],\n entry.revision,\n )\n return undefined\n } catch (error) {\n // Another writer (the official card's Save, another tab, the\n // autofill pass) moved the document between this read and\n // this write: re-read once and fence on the new revision.\n if (attempt === 0 && isConflictError(error)) continue\n return error instanceof Error ? error.message : String(error)\n }\n }\n return 'the settings document kept changing; try again'\n }\n\n /** The whole list, as the browser half renders it. */\n const payload = async (): Promise<unknown> => {\n // One disk read answers the entries, the endpoints and (with the\n // section) the seat context below; re-reading the file per field\n // would triple the I/O of every list request.\n const document = readKeyIndex(indexFile)\n const seat = enabledNow()\n const listed = keyEntriesOf(document, route)\n const refs = listed.map(entry => entry.ref)\n // The seat (the reference the adapter itself resolves) is always\n // on the list, even when the official page wrote it and this\n // plugin has never listed it \u2014 the adapter still needs it.\n if (seat !== undefined && !refs.includes(seat)) refs.push(seat)\n const facts = await credentialFacts(credentials, refs)\n const now = Date.now()\n const entries: KeyEntryView[] = refs.map(ref => {\n const fact = facts[ref]\n const stored = listed.find(candidate => candidate.ref === ref)\n const view: KeyEntryView = {\n ref,\n // Being switched on is the default: a key the index has\n // never described (the seat) reads as in use.\n enabled: stored?.disabled !== true,\n configured: fact?.configured ?? null,\n }\n if (fact?.masked !== undefined) view.masked = fact.masked\n if (stored?.alias !== undefined) view.alias = stored.alias\n if (stored?.models !== undefined) (view as { models?: readonly string[] }).models = stored.models\n if (stored?.protocol !== undefined) (view as { protocol?: RouteProtocol }).protocol = stored.protocol\n // The cooldown memory is the one source of the \u51B7\u5374 state the\n // row paints: a resting key reads \"cooling for Ns\" instead of\n // healthy, so the panel says why a key is not signing.\n const rest = keyRest.stateOf(restKeyOf(route, ref), now)\n if (rest !== undefined) {\n ;(view as { rest?: KeyEntryView['rest'] }).rest = {\n kind: rest.kind,\n remainingMs: Math.max(0, rest.until - now),\n failures: rest.failures,\n }\n }\n return view\n })\n const endpoints = document.endpoints?.[route]\n // The models this route actually offers \u2014 the universe a key's\n // scope is chosen from (user rule: pick from the models already\n // added, never the provider's whole catalog).\n const routeModels = modelsOf(providersOf(), route)\n .map(model => (typeof model['id'] === 'string' ? model['id'] : ''))\n .filter(id => id.length > 0)\n // What the provider serves ACROSS its keys: one catalogue, each\n // model naming the keys that advertise it. The picker only knows\n // the route's own `models`, so `unmergedModels` is the part of\n // that catalogue it cannot see yet \u2014 the panel offers to add it,\n // and no write happens without that click.\n const merged = mergeKeyListings(\n listed.map(entry => ({\n ref: entry.ref,\n targets: [],\n models: entry.models === undefined ? undefined : [...entry.models],\n })),\n )\n const declaredModels = new Set(routeModels)\n const unmergedModels = merged.ids.filter(id => !declaredModels.has(id))\n return {\n ok: true,\n route,\n entries,\n models: routeModels,\n ...merged.ids.length === 0 ? {} : { mergedModels: merged.ids },\n ...unmergedModels.length === 0 ? {} : { unmergedModels },\n endpoints: {\n openai: endpoints?.openai ?? null,\n anthropic: endpoints?.anthropic ?? null,\n gemini: endpoints?.gemini ?? null,\n },\n }\n }\n\n if (req.method === 'GET') {\n sendJson(res, 200, await payload())\n return\n }\n\n const body = await readJsonBody(req)\n const op = isRecord(body) && typeof body['op'] === 'string' ? body['op'] : ''\n const ref = isRecord(body) && typeof body['ref'] === 'string' ? body['ref'] : undefined\n const alias = isRecord(body) ? normalizeKeyAlias(body['alias']) : undefined\n const value = isRecord(body) && typeof body['value'] === 'string' ? body['value'] : undefined\n // Validate each operation before its first write and compensate\n // later failures across the independent settings and key stores.\n const refuse = (error: string): void => sendJson(res, 400, { ok: false, error })\n // The per-key outcome of a `discover` op, echoed beside the payload\n // so the panel can say which protocol each key was asked on.\n let probeReport: KeyProbeResult[] | undefined\n\n if (op === 'add') {\n if (!isLegalKeyValue(value)) {\n refuse('a key must be printable ASCII without spaces')\n return\n }\n const taken = keyEntriesOf(readKeyIndex(indexFile), route).map(candidate => candidate.ref)\n // The reference in use need not be listed \u2014 the official card\n // and a hand-edited profile both write one this plugin has never\n // seen \u2014 and minting it again would overwrite the very key the\n // provider is running on.\n const active = enabledNow()\n if (active !== undefined && !taken.includes(active)) taken.push(active)\n let created = nextKeyRef(route, taken)\n // Metadata cannot enumerate the credential store. Check each\n // candidate against both read faces before writing a new value.\n for (;;) {\n const facts = await credentialFacts(credentials, [created])\n const configured = facts[created]?.configured\n if (configured === undefined) throw new HostReadError('the credential store could not confirm a free reference')\n if (!configured && await resolveCredential(credentials, created) === undefined) break\n taken.push(created)\n created = nextKeyRef(route, taken)\n }\n // The value goes into the store first: a reference the index\n // lists but the store cannot hold would render as a key the\n // user can never reveal, enable or remove.\n const refused = await storeCredential(credentials, created, value)\n if (refused !== undefined) {\n refuse(refused)\n return\n }\n let indexed = false\n try {\n updateKeyIndex(document => withKeyEntry(document, route, created, alias), indexFile)\n indexed = true\n // Adding the first key also configures the route.\n if (enabledNow() === undefined) {\n const failed = await setEnabledKey(created)\n if (failed !== undefined) throw new Error(failed)\n }\n } catch (error) {\n const rollback = await forgetCredential(credentials, created)\n // Keep metadata if cleanup failed, so the retained secret can\n // still be found and removed by a later manager request.\n if (rollback === undefined && indexed) {\n updateKeyIndex(document => withoutKeyEntry(document, route, created), indexFile)\n }\n if (rollback !== undefined) {\n throw new Error(`${error instanceof Error ? error.message : String(error)}; credential rollback failed for ${created}: ${rollback}`)\n }\n throw error\n }\n } else if (op === 'scope') {\n // Record which models one key serves (the manual override; the\n // `discover` op fills it automatically). Absent/empty models\n // clears the scope, making the key an unscoped catch-all again.\n const document = readKeyIndex(indexFile)\n const known = ref !== undefined && (hasKeyEntry(document, route, ref) || ref === enabledNow())\n if (ref === undefined || !known) {\n refuse('that key is not listed for this provider')\n return\n }\n const scope = isRecord(body) ? normalizeKeyModels(body['models']) : undefined\n const target = ref\n updateKeyIndex(\n document2 =>\n hasKeyEntry(document2, route, target)\n ? withKeyModels(document2, route, target, scope)\n : withKeyEntry(document2, route, target, undefined),\n indexFile,\n )\n } else if (op === 'protocol') {\n // Pin which wire protocol one key speaks (the per-key protocol\n // picker). Absent/blank clears the pin, returning the key to the\n // AUTOMATIC wire: each request speaks the protocol the model's\n // own family names where the provider addressed it, and the\n // route's own protocol otherwise.\n const document = readKeyIndex(indexFile)\n const known = ref !== undefined && (hasKeyEntry(document, route, ref) || ref === enabledNow())\n if (ref === undefined || !known) {\n refuse('that key is not listed for this provider')\n return\n }\n const protocol = isRecord(body) ? normalizeKeyProtocol(body['protocol']) : undefined\n if (isRecord(body) && body['protocol'] !== undefined && body['protocol'] !== null && protocol === undefined) {\n refuse('that protocol is not supported')\n return\n }\n // A pinned protocol rides its own family's base URL when the\n // provider configured one (readRouteKeyScopes), and otherwise\n // falls back to the provider's own address with that wire \u2014 which\n // is how a key switches between Responses and Chat Completions on\n // ONE URL. Refusing the pin without that address (the old rule)\n // made the picker look dead (user item 3), so the pin is stored as\n // stated and the request path decides which URL it goes to.\n const target = ref\n updateKeyIndex(\n document2 =>\n hasKeyEntry(document2, route, target)\n ? withKeyProtocol(document2, route, target, protocol)\n : withKeyEntry(document2, route, target, undefined),\n indexFile,\n )\n } else if (op === 'enable') {\n // Switch one key into or out of the routing pool (the circular\n // check on each row). Everything else about the key \u2014 label,\n // scope, protocol pin \u2014 stays, so switching it back on restores\n // exactly what it served. The last enabled key cannot be\n // switched off: an empty pool would send the request down the\n // adapter's own single-key path, which signs with the very key\n // the user just switched off.\n const document = readKeyIndex(indexFile)\n const known = ref !== undefined && (hasKeyEntry(document, route, ref) || ref === enabledNow())\n if (ref === undefined || !known) {\n refuse('that key is not listed for this provider')\n return\n }\n const enabling = !(isRecord(body) && body['enabled'] === false)\n if (!enabling) {\n const listed = keyEntriesOf(document, route)\n const seat = enabledNow()\n const others = listed.filter(entry => entry.ref !== ref && entry.disabled !== true)\n // The unlisted seat (the profile's own reference) stays a\n // fallback key \u2014 unless it is the one being switched off.\n const seatRemains =\n seat !== undefined && seat !== ref && !listed.some(entry => entry.ref === seat)\n if (others.length === 0 && !seatRemains) {\n refuse('the last enabled key cannot be switched off')\n return\n }\n }\n const target = ref\n updateKeyIndex(\n document2 => {\n const indexed = hasKeyEntry(document2, route, target)\n // Switching ON a reference the index has never listed (the\n // unlisted seat) is already the state of the world.\n if (!indexed && enabling) return document2\n return withKeyDisabled(\n indexed ? document2 : withKeyEntry(document2, route, target, undefined),\n route,\n target,\n !enabling,\n )\n },\n indexFile,\n )\n } else if (op === 'endpoints') {\n // The provider's base URLs, one per protocol family: the\n // ChatGPT/OpenAI wire, the Anthropic wire and the Gemini one.\n // A key that pins a protocol uses the matching URL; each is\n // optional and an empty value clears that side.\n const endpoints = isRecord(body)\n ? normalizeRouteEndpoints({\n openai: body['openai'],\n anthropic: body['anthropic'],\n gemini: body['gemini'],\n })\n : undefined\n updateKeyIndex(document => withRouteEndpoints(document, route, endpoints), indexFile)\n } else if (op === 'discover') {\n // Probe EACH listed key for the models it actually serves. A key\n // is only asked on the protocols and addresses it would be used\n // with (see key-probe.ts): its own pin when it has one, and both\n // families when the provider configured both. A key whose\n // listing cannot be read keeps its previous scope rather than\n // being wiped.\n const document = readKeyIndex(indexFile)\n const profile = providerProfileOf(entryOf()?.value, route)\n const baseURL = typeof profile?.['baseURL'] === 'string' ? profile['baseURL'] : ''\n const api = typeof profile?.['api'] === 'string' ? profile['api'] : ''\n if (baseURL.length === 0) {\n refuse('this provider has no address to interrogate; set each key\\'s models by hand')\n return\n }\n const seat = enabledNow()\n const listedEntries = keyEntriesOf(document, route)\n const listedRefs = listedEntries.map(candidate => candidate.ref)\n if (seat !== undefined && !listedRefs.includes(seat)) listedRefs.push(seat)\n if (listedRefs.length === 0) {\n refuse('add a key before detecting its models')\n return\n }\n const endpoints = document.endpoints?.[route]\n // Resolve every credential BEFORE probing: a key whose value\n // cannot be read is not asked at all, and the pass still runs\n // for the rest instead of stopping at the first unreadable one.\n const asks: { ref: string; apiKey: string; pinned?: RouteProtocol }[] = []\n for (const listed of listedRefs) {\n let apiKey: string | undefined\n try {\n apiKey = await resolveCredential(credentials, listed)\n } catch {\n continue\n }\n if (apiKey === undefined) continue\n const pinned = listedEntries.find(candidate => candidate.ref === listed)?.protocol\n asks.push({\n ref: listed,\n apiKey,\n ...pinned === undefined ? {} : { pinned },\n })\n }\n // The scopes the keys were last seen serving. A key whose listing\n // cannot be read this pass keeps these models: a provider-wide\n // catalogue must not shrink because one key was rate-limited\n // (the rule magpie's per-key fetch applies too).\n const lastKnown = new Map<string, readonly string[]>(\n listedEntries\n .filter(candidate => candidate.models !== undefined)\n .map(candidate => [candidate.ref, candidate.models as readonly string[]]),\n )\n // Bounded concurrency: asking every key at once can trip a\n // provider's per-account rate limit with its own catalogue read.\n const { results } = await collectKeyListings({\n keys: asks,\n lastKnown,\n refOf: ask => ask.ref,\n probe: async ask => probeKeyModels({\n ref: ask.ref,\n intent: {\n api,\n baseURL,\n ...ask.pinned === undefined ? {} : { pinned: ask.pinned },\n ...endpoints === undefined ? {} : { endpoints },\n },\n apiKey: ask.apiKey,\n profileHeaders: profile?.['headers'],\n timeoutMs: resolved.probeTimeoutMs,\n // Each key probes its OWN credential, so bypass the key-routing\n // wrapper (which would otherwise sign every probe with the first key).\n send: headerOverlayBypass(),\n headersFor: composeProbeHeaders,\n read: readBounded,\n entries: listingEntries,\n }),\n })\n for (const result of results) {\n if (result.models === undefined) continue\n updateKeyIndex(\n document2 =>\n hasKeyEntry(document2, route, result.ref)\n ? withKeyModels(document2, route, result.ref, result.models as readonly string[])\n : withKeyEntry(document2, route, result.ref, undefined),\n indexFile,\n )\n }\n if (results.every(result => result.targets.length === 0)) {\n refuse(\n results.find(result => result.skipped !== undefined)?.skipped ??\n 'this provider cannot be interrogated; set each key\\'s models by hand',\n )\n return\n }\n probeReport = results\n } else if (op === 'rename') {\n // The key the provider is RUNNING on takes a label too: that\n // reference is usually the one the official card wrote, which\n // this plugin has never listed. Writing it here is what puts it\n // on the list, so every later write matches an entry.\n const known =\n ref !== undefined &&\n (hasKeyEntry(readKeyIndex(indexFile), route, ref) || ref === enabledNow())\n if (ref === undefined || !known) {\n refuse('that key is not listed for this provider')\n return\n }\n const target = ref\n updateKeyIndex(\n document =>\n hasKeyEntry(document, route, target)\n ? withKeyAlias(document, route, target, alias)\n : withKeyEntry(document, route, target, alias),\n indexFile,\n )\n } else if (op === 'value') {\n const known =\n ref !== undefined &&\n (hasKeyEntry(readKeyIndex(indexFile), route, ref) || ref === enabledNow())\n if (ref === undefined || !known) {\n refuse('that key is not listed for this provider')\n return\n }\n if (!isLegalKeyValue(value)) {\n refuse('a key must be printable ASCII without spaces')\n return\n }\n // Only the secret moves: the reference keeps its name, its alias\n // and its seat. Removing and re-adding would mint a new ref, so\n // the profile would name a key the store no longer holds and the\n // row would lose everything but its value.\n const refused = await storeCredential(credentials, ref, value)\n if (refused !== undefined) {\n refuse(refused)\n return\n }\n } else if (op === 'remove') {\n const document = readKeyIndex(indexFile)\n if (ref === undefined || (!hasKeyEntry(document, route, ref) && ref !== enabledNow())) {\n refuse('that key is not listed for this provider')\n return\n }\n const configured = (await credentialConfigured(credentials, [ref]))[ref]\n if (configured === undefined) throw new HostReadError('the credential store could not read the reference')\n const wasEnabled = ref === enabledNow()\n const remaining = keyEntriesOf(document, route)\n .map(candidate => candidate.ref)\n .filter(candidate => candidate !== ref)\n const replacement = remaining[0]\n if (wasEnabled) {\n // Move the profile before forgetting its credential.\n const failed = await setEnabledKey(replacement)\n if (failed !== undefined) {\n refuse(failed)\n return\n }\n }\n try {\n // Commit metadata before deleting the secret: a disk failure\n // must leave the original credential available for rollback.\n updateKeyIndex(document2 => withoutKeyEntry(document2, route, ref), indexFile)\n if (configured) {\n const refused = await forgetCredential(credentials, ref)\n if (refused !== undefined) throw new Error(refused)\n }\n } catch (error) {\n const failures: string[] = []\n try {\n updateKeyIndex(current => {\n const providers = { ...current.providers }\n const original = document.providers[route]\n if (original === undefined) delete providers[route]\n else providers[route] = original\n return { ...current, providers }\n }, indexFile)\n } catch {\n failures.push('key index rollback failed')\n }\n // Do not undo a later profile change by another writer.\n if (wasEnabled && enabledNow() === replacement) {\n const failed = await setEnabledKey(ref)\n if (failed !== undefined) failures.push(`profile rollback failed: ${failed}`)\n }\n throw new Error([error instanceof Error ? error.message : String(error), ...failures].join('; '))\n }\n } else if (op === 'applyMerged') {\n // Offer the provider-wide catalogue to the picker. Only models the\n // keys advertise that the route does NOT declare yet are appended:\n // nothing already declared is renamed, reordered or removed, so a\n // hand-written entry (a display name, a context window) is never\n // rewritten by a scope probe. The panel asks first, and this op is\n // the only path that writes a provider's models on a probe's\n // behalf; nothing here runs on its own.\n const merged = mergeKeyListings(\n keyEntriesOf(readKeyIndex(indexFile), route).map(candidate => ({\n ref: candidate.ref,\n targets: [],\n models: candidate.models === undefined ? undefined : [...candidate.models],\n })),\n )\n if (merged.ids.length === 0) {\n refuse('no key models have been detected yet; detect them first')\n return\n }\n /**\n * Append the undeclared ids to the RAW user models array (never the\n * resolved view: materializing schema defaults into the user layer\n * is what the autofill pass works hard to avoid).\n * @returns undefined when the write landed or nothing was missing,\n * otherwise the refusal and whether it was a revision conflict.\n */\n const appendMerged = async (): Promise<{ conflict: boolean; error: string } | undefined> => {\n const descriptor = settings.describe().find(candidate => candidate.ns === PI_NS)\n const user = isRecord(descriptor?.['user']) ? descriptor['user'] : undefined\n const userProviders = isRecord(user) && isRecord(user['providers']) ? user['providers'] : undefined\n const profile = isRecord(userProviders) ? userProviders[route] : undefined\n const rawModels: unknown[] = isRecord(profile) && Array.isArray(profile['models'])\n ? profile['models']\n : []\n const declared = new Set(\n rawModels\n .filter(isRecord)\n .map(model => (typeof model['id'] === 'string' ? model['id'].trim() : ''))\n .filter(id => id.length > 0),\n )\n const additions = merged.ids.filter(id => !declared.has(id))\n if (additions.length === 0) return undefined\n try {\n await settings.mutate(\n PI_NS,\n [{\n op: 'set',\n path: ['providers', route, 'models'],\n value: [...rawModels, ...additions.map(id => ({ id }))],\n }],\n descriptor?.revision,\n )\n return undefined\n } catch (error) {\n return {\n conflict: isConflictError(error),\n error: error instanceof Error ? error.message : String(error),\n }\n }\n }\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const failed = await appendMerged()\n if (failed === undefined) break\n // The document moved between the read and the write (the official\n // card, another tab, the autofill pass): re-read once and retry.\n if (attempt === 0 && failed.conflict) continue\n refuse(failed.error)\n return\n }\n // The answer below re-reads the namespace, and our own write is the\n // freshest thing in it: drop the cached section instead of waiting\n // for a document-updated event this handler cannot observe.\n piSectionCached = false\n } else {\n refuse(`unknown key operation \"${op}\"`)\n return\n }\n // The key index is this plugin's own file, so a write to it fires no\n // settings event. Refresh the live routing snapshot here or a key\n // added/scoped/detected just now would not sign a request until some\n // unrelated settings change happened to refresh it.\n refreshKeyScopes()\n const answer = await payload()\n // `payload()` is `unknown` by contract (the browser narrows it), so\n // the probe report is attached without spreading that type.\n sendJson(\n res,\n 200,\n probeReport === undefined || !isRecord(answer) ? answer : { ...answer, probe: probeReport },\n )\n } catch (error) {\n sendJson(res, error instanceof HostReadError ? 502 : 500, {\n ok: false, error: error instanceof Error ? error.message : String(error),\n })\n } finally {\n releaseMutation?.()\n }\n },\n }),\n 'dsh-model-think-level: key index route',\n )\n\n // The autofill switches, for the browser half that runs the running\n // complement. Read-only and same-origin only, like the probe above: a\n // `dsh.client` declaration carries no plugin config, so without this route\n // a deployment configured `autofill: false` would still be written to from\n // the settings page.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: AUTOFILL_CONFIG_PATH,\n handler: async (req, res) => {\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n sendJson(res, 200, {\n ok: true,\n data: { autofill: resolved.autofill, modalityAutofill: resolved.modalityAutofill },\n })\n },\n }),\n 'dsh-model-think-level: autofill config route',\n )\n\n // The request-header overlay's status, for the browser half. Same-origin\n // and read-only, like the other two routes: the takeover lives host-side, so\n // the page needs this to say which routes it is changing and to warn about\n // another plugin rewriting the same surface.\n ctx.effect(\n () =>\n webServerCtx.webServer.register({\n kind: 'exact',\n path: HEADERS_CONFIG_PATH,\n handler: async (req, res) => {\n if (!isTrustedRequest(req)) {\n sendJson(res, 403, { ok: false, error: 'forbidden' })\n return\n }\n if (req.method !== 'GET') {\n sendJson(res, 405, { ok: false, error: 'method not allowed' })\n return\n }\n const index = overlaySource.current\n sendJson(res, 200, {\n ok: true,\n data: {\n /** Whether the fetch-layer takeover is enabled in this deployment. */\n enabled: resolved.uaOverride,\n /** Whether this plugin's wrapper currently owns the global fetch. */\n installed: headerOverlayInstalled(),\n /** Routes whose configured request headers are sent, by origin. */\n overrides: index.overrides.map(entry => ({\n origin: entry.origin,\n route: entry.route,\n headers: entry.headers,\n ...(entry.userAgent === undefined ? {} : { userAgent: entry.userAgent }),\n })),\n /** Same-origin routes with different User-Agent values. */\n conflicts: index.conflicts,\n /** Same-origin differences for any configured request header. */\n headerConflicts: index.headerConflicts,\n /** What was found of the plugins that rewrite the same surface. */\n environment: environmentConflicts,\n },\n })\n },\n }),\n 'dsh-model-think-level: headers config route',\n )\n })\n}\n", "/**\n * Plugin-wide constants shared by the host and browser halves.\n *\n * @module dsh-model-think-level/constants\n */\n\n/** Stable plugin id, matching the cordis.patch.yml row and the bundle id. */\nexport const PLUGIN_ID = 'dsh-model-think-level'\n\n/** Same-origin host route that proxies a provider's RAW /models listing. */\nexport const PROBE_PATH = '/dsh-model-think-level/raw-models'\n/** Read-only diagnostics for the request-header takeover. */\nexport const DIAG_PATH = '/dsh-model-think-level/header-bridge'\n\n/**\n * Same-origin host route that resolves one provider profile's stored\n * credential, so the API-key field's eye can show a SAVED key.\n *\n * The harness keeps provider keys write-only on purpose: the settings document\n * carries only the profile's `apiKeyEnv` reference, and the credential service\n * reports `{ configured, source, writable }` through `describe()` \u2014 never the\n * value. Only the host can read it (`credentials.resolve()`), and it does so\n * for the request adapters; the browser normally never sees a stored key at\n * all. This route is the plugin's deliberate exception: an explicit,\n * user-initiated, same-fence read that answers with the value and is never\n * cached, so the eye can put it back into the official field.\n */\nexport const PROVIDER_KEY_PATH = '/dsh-model-think-level/provider-key'\n\n/**\n * Same-origin host route that owns a provider's list of API keys: their\n * references, their labels, and which one is in use.\n *\n * The harness has no notion of \"several keys for one provider\": a profile names\n * exactly one reference (`apiKeyEnv`) and a credential store holds exactly one\n * value per reference, with no enumeration and no label. Both facts are\n * deliberate \u2014 a configuration surface learns which references exist from its\n * settings schema \u2014 so a list of keys can only be plugin-owned state. It lives\n * in the harness home (`<DSH_HOME>/dsh-model-think-level/key-index.json`) rather\n * than in the pi-ai profile, so the official add-provider card, which writes the\n * WHOLE profile at `providers.<route>`, cannot drop it.\n *\n * The route both reads and writes: the values themselves still go to the\n * credential store through the host's own `credentials` service, so the browser\n * never needs a new Remote face.\n */\nexport const KEY_INDEX_PATH = '/dsh-model-think-level/key-index'\n\n/**\n * Same-origin host route that reports this plugin's autofill switches. The\n * browser half runs the running auto-fill complement, and a `dsh.client`\n * declaration carries no plugin config, so the two switches have to be read\n * from the host that owns the cordis row; without it a deployment that turned\n * `autofill: false` would still be written to from the page.\n */\nexport const AUTOFILL_CONFIG_PATH = '/dsh-model-think-level/autofill-config'\n\n/**\n * Same-origin host route reporting the request-header overlay (issue #12): the\n * routes whose `user-agent` the plugin is overriding, and what it found of the\n * plugins that rewrite the same surface. The browser half renders the\n * coexistence warning from here \u2014 the takeover lives host-side, so the page\n * cannot observe it on its own.\n */\nexport const HEADERS_CONFIG_PATH = '/dsh-model-think-level/headers-config'\n\n/** The settings namespace this plugin edits: pi-ai custom provider routes. */\nexport const PI_AI_NS = 'llm-pi-ai'\n\n/**\n * Model-level marker written when the user deliberately unsets the\n * declaration (\"back to inheritance\"). Schemastery passes unknown model keys\n * through, so the marker survives official-page saves and restarts \u2014 which is\n * the point: auto-fill must respect the absence as a decision, not as a gap\n * to fill.\n */\nexport const UNSET_MARKER = 'reasoningEffortsUnset'\n\n/**\n * Model-level marker for a deliberately unset input-modality declaration,\n * mirroring {@link UNSET_MARKER}: auto-fill must respect the absence of\n * `input` as a decision (the route default applies), not as a gap to fill.\n */\nexport const INPUT_UNSET_MARKER = 'inputUnset'\n\n/**\n * Model-level provenance marker written beside every ladder the HOST autofill\n * fills from the knowledge base, carrying the settings revision the fill read.\n *\n * It exists because the plugin's auto-fill and the user's staged declaration\n * race on the SAME row: whichever half runs the fill writes the knowledge base\n * suggestion, while the staged-declaration flush compares the document against\n * its own suggestion. By the time the flush looks, the suggestion may already\n * be stored -- and byte equality alone cannot tell \"the plugin wrote this\" from\n * \"the user declared this\", so a staged ladder differing from the knowledge\n * base in even one spelling (the editor's `off: null` against the knowledge\n * base's `off: 'none'`) was dropped as a document takeover: the reported\n * \"configured it on the add-provider card, saved, and it is gone\".\n *\n * With the marker the flush knows the stored ladder is a suggestion, so a\n * staged user intent overrides it. Either way the user's bytes win; the marker\n * only decides whether the flush is allowed to write at all. Schemastery passes\n * unknown model keys through, so the marker survives official-page saves and\n * restarts like the other two markers. Any ladder written through the plugin\n * clears it, which is what makes a later hand edit outrank a fresh staging.\n */\nexport const AUTOFILL_MARKER = 'reasoningEffortsAutofilled'\n\n/**\n * Model-level default-effort pick (issue #4): the level a brand-new session\n * starts this model at, outranking the remembered levels. The value is one of\n * the model's own declared ladder keys, or the field is absent when the user\n * has not picked one (memory chain applies). Deliberately NOT a harness\n * concept: pi-ai's runtime never sees it (unknown model keys ride the settings\n * document the way the other markers do), and the browser half is its only\n * consumer. The name matches the catalog's `reasoning.defaultEffort` spelling\n * so a future first-class field can adopt the stored values as-is.\n */\nexport const DEFAULT_EFFORT_FIELD = 'defaultEffort'\n\n/** Locale dictionary namespace for the browser half's copy (not a settings namespace). */\nexport const STORE_NS = PLUGIN_ID\n", "/**\n * The credential-reference vocabulary the API-key manager shares between both\n * halves.\n *\n * A provider's key list is a list of NAMES: every value lives in the harness\n * credential store under its own reference, and the profile records exactly one\n * of those names (`providers.<route>.apiKeyEnv`) as the reference the adapter\n * resolves when it calls the provider. This module owns the naming rules the\n * two halves must agree on \u2014 the browser half picks the next free name for a\n * new key, the host half re-validates whatever arrives \u2014 so one name can never\n * mean two different things on the two sides of the wire.\n *\n * Deliberately free of `node:` imports: the client bundle imports this module\n * too (the same way `constants.ts` is shared), and a single `node:` import\n * would drag the host into the browser build.\n *\n * @module dsh-model-think-level/key-refs\n */\n\n/** One key the manager lists for a provider route. */\nexport interface KeyEntry {\n /** Credential reference holding the value. */\n readonly ref: string\n /** User-facing label; absent means \"show the reference itself\". */\n readonly alias?: string\n /**\n * The model ids this key is known to serve, discovered from the provider's\n * model listing. Absent means \"unscoped\": the key has not been probed yet, so\n * it acts as a catch-all and serves any model no other key claims. An empty\n * array means the key was probed and reached no models at all.\n *\n * Presence, not order, is what matters here: a model reachable through\n * several keys is served by the first key (in list order) that lists it, so\n * list order doubles as the preference order the user asked for.\n */\n readonly models?: readonly string[]\n /**\n * The wire protocol this key must speak, when it is pinned to one.\n * Absent means AUTOMATIC: each request speaks the wire the model's own family\n * names \u2014 an Anthropic-family endpoint for claude models, the Gemini one for\n * gemini models, the route's default for everything else \u2014 as far as the\n * provider configured that family's endpoint. A concrete value re-dispatches\n * every request through that protocol's API implementation AND that key's\n * endpoint, so one provider route can hold a Chat-Completions key and an\n * Anthropic key side by side (a true protocol switch, not just an endpoint\n * swap).\n */\n readonly protocol?: RouteProtocol\n /**\n * Whether the key is switched OUT of the routing pool. Absent \u2014 the stored\n * default \u2014 means the key is in use; a literal `true` lists it but lets no\n * request sign with it. The label, model scope and protocol pin all stay, so\n * switching the key back on restores exactly what it served.\n */\n readonly disabled?: boolean\n}\n\n/**\n * The pi-ai API ids the manager can pin a key to. These are the exact ids\n * `providers.<route>.api` carries, so a key pinned to one speaks the same wire\n * format the official card would have produced for that protocol \u2014 with one\n * addition: `google-generative-ai` names a protocol the harness's own adapter\n * registry does not offer at route level, so it can only ever appear as a\n * per-key pin riding the gemini family's endpoint.\n */\nexport type RouteProtocol =\n | 'openai-completions'\n | 'anthropic-messages'\n | 'openai-responses'\n | 'google-generative-ai'\n\n/** Every protocol a key can be pinned to, in the order the picker shows them. */\nexport const ROUTE_PROTOCOLS: readonly RouteProtocol[] = [\n 'anthropic-messages',\n 'openai-completions',\n 'openai-responses',\n 'google-generative-ai',\n]\n\n/** The endpoint families a protocol can draw its base URL from. */\nexport type EndpointFamily = 'openai' | 'anthropic' | 'gemini'\n\n/** Every endpoint family, in the order address rows and pickers show them. */\nexport const ENDPOINT_FAMILIES: readonly EndpointFamily[] = ['openai', 'anthropic', 'gemini']\n\n/** Which endpoint family a protocol draws its base URL from. */\nexport function endpointFamilyOf(protocol: RouteProtocol): EndpointFamily {\n if (protocol === 'anthropic-messages') return 'anthropic'\n if (protocol === 'google-generative-ai') return 'gemini'\n return 'openai'\n}\n\n/** Whether a value is one of the protocol ids this manager understands. */\nexport function isRouteProtocol(value: unknown): value is RouteProtocol {\n return value === 'openai-completions'\n || value === 'anthropic-messages'\n || value === 'openai-responses'\n || value === 'google-generative-ai'\n}\n\n/**\n * A stored per-key protocol, or undefined when the value means AUTOMATIC.\n *\n * `any`/`''`/unknown values collapse to undefined so a hand-edited index file\n * cannot pin a key to a protocol the runtime has no implementation for; the\n * request is then resolved per model (the model family's own wire where the\n * provider addressed it, the route's own protocol otherwise), which is always\n * valid.\n * @param value - whatever arrived (a picker choice, or a hand-edited index file).\n * @returns the protocol id, or undefined for \"automatic\".\n */\nexport function normalizeKeyProtocol(value: unknown): RouteProtocol | undefined {\n return isRouteProtocol(value) ? value : undefined\n}\n\n/**\n * A stored switch-off mark, or undefined when the key is in use.\n *\n * Being enabled is the default and is never stored, so only a literal `true`\n * means anything; a hand-edited index file cannot switch a key off by typo,\n * and an entry never carries a redundant `disabled: false`.\n * @param value - whatever arrived (a toggle answer, or a hand-edited file).\n * @returns `true` when the key is switched off, else undefined.\n */\nexport function normalizeKeyDisabled(value: unknown): boolean | undefined {\n return value === true ? true : undefined\n}\n\n/**\n * The base URLs one provider route can hold, one per endpoint family: an\n * OpenAI-family endpoint, an Anthropic-family endpoint and a Gemini-family one.\n * A key pinned to a protocol uses the matching one; an automatic key (no pin)\n * dispatches a model to the entry of the family the model's id names, and to\n * the route's own `providers.<route>.baseURL` otherwise.\n */\nexport interface RouteEndpoints {\n /** Base URL for openai-completions / openai-responses keys. */\n readonly openai?: string\n /** Base URL for anthropic-messages keys. */\n readonly anthropic?: string\n /** Base URL for google-generative-ai keys (version path included, `\u2026/v1beta`). */\n readonly gemini?: string\n}\n\n/** Whether a value looks like an http(s) URL worth storing as an endpoint. */\nfunction isEndpointUrl(value: unknown): value is string {\n if (typeof value !== 'string') return false\n const trimmed = value.trim()\n if (trimmed.length === 0) return false\n return /^https?:\\/\\/\\S+$/i.test(trimmed)\n}\n\n/**\n * A stored set of endpoints, or undefined when none carries a usable URL.\n *\n * Each URL is trimmed and must look like http(s); a blank or unusable side is\n * dropped rather than stored, so \"no Anthropic endpoint configured\" stays\n * distinguishable from \"an empty string was saved here\".\n * @param value - whatever arrived (the endpoints editor, or a hand-edited file).\n * @returns the cleaned set, or undefined when it holds no endpoint.\n */\nexport function normalizeRouteEndpoints(value: unknown): RouteEndpoints | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const record = value as Record<string, unknown>\n const out: { openai?: string; anthropic?: string; gemini?: string } = {}\n if (isEndpointUrl(record['openai'])) out.openai = (record['openai'] as string).trim()\n if (isEndpointUrl(record['anthropic'])) out.anthropic = (record['anthropic'] as string).trim()\n if (isEndpointUrl(record['gemini'])) out.gemini = (record['gemini'] as string).trim()\n return out.openai === undefined && out.anthropic === undefined && out.gemini === undefined\n ? undefined\n : out\n}\n\n/**\n * A stored model-scope list, or undefined when the value carries nothing usable.\n *\n * Model ids are opaque tokens (they may contain `/`, `.`, `:` \u2014 `deepseek-ai/DeepSeek-V3`),\n * so they are trimmed but not otherwise rewritten; blank and duplicate ids are\n * dropped, and a value that is not an array collapses to undefined (unscoped).\n * @param value - whatever arrived (a probe result, or a hand-edited index file).\n * @returns the deduplicated id list, or undefined.\n */\nexport function normalizeKeyModels(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined\n const seen = new Set<string>()\n const out: string[] = []\n for (const item of value) {\n if (typeof item !== 'string') continue\n const id = item.trim()\n if (id.length === 0 || seen.has(id)) continue\n seen.add(id)\n out.push(id)\n }\n return out\n}\n\n/** Longest reference the manager will mint or accept. */\nexport const KEY_REF_MAX_LENGTH = 80\n\n/** Longest alias the manager stores. A label, never a secret. */\nexport const KEY_ALIAS_MAX_LENGTH = 40\n\n/**\n * The shape of a reference the manager accepts. Looser than the credential\n * store's own POSIX-ish rule on purpose: a route may legitimately start with a\n * digit (`9router` \u2192 `9ROUTER_API_KEY`), and the store stays the authority on\n * what it will hold. This is the plugin's sanity bound, not the validation.\n */\nexport const KEY_REF_PATTERN = /^[A-Za-z0-9_]{1,80}$/\n\n/**\n * The reference the official Models page derives for a provider route: the\n * route upper-cased with every non-alphanumeric run folded to `_`, plus\n * `_API_KEY`. Mirrors the official page exactly so the first key the manager\n * adds for a provider is the very reference that page would have written.\n * @param route - the provider route key (`ofox`, `aliyun-cn`).\n * @returns the derived reference name.\n */\nexport function deriveKeyRef(route: string): string {\n return `${route.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`\n}\n\n/** Whether a value is a reference name this manager will pass to the store. */\nexport function isKeyRefName(value: unknown): value is string {\n return typeof value === 'string' && KEY_REF_PATTERN.test(value)\n}\n\n/**\n * The first free name in the sequence `<DERIVED>`, `<DERIVED>_2`, `<DERIVED>_3`\u2026\n * @param route - the provider route key.\n * @param taken - every reference already listed for that route.\n * @returns a reference not in `taken`.\n */\nexport function nextKeyRef(route: string, taken: readonly string[]): string {\n const used = new Set(taken)\n const base = deriveKeyRef(route)\n if (!used.has(base)) return base\n for (let suffix = 2; suffix <= 999; suffix += 1) {\n const candidate = `${base}_${suffix}`\n if (!used.has(candidate)) return candidate\n }\n // A thousand keys on one route is not a real deployment; stay unique anyway.\n return `${base}_${Date.now()}`\n}\n\n/**\n * A stored alias, or undefined when the label carries nothing.\n *\n * Control characters are dropped rather than escaped: an alias is rendered as\n * text on the official page, and a stray newline there is a rendering bug, not\n * data worth keeping.\n * @param value - whatever arrived (user input, or a hand-edited index file).\n * @returns the trimmed label, capped at {@link KEY_ALIAS_MAX_LENGTH}.\n */\nexport function normalizeKeyAlias(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n let cleaned = ''\n for (const char of value) {\n const code = char.codePointAt(0) ?? 0\n if (code < 32 || code === 127) continue\n cleaned += char\n }\n cleaned = cleaned.trim()\n if (cleaned.length === 0) return undefined\n return cleaned.slice(0, KEY_ALIAS_MAX_LENGTH)\n}\n\n/**\n * Whether a value is a key the official page would itself accept: printable\n * ASCII with no spaces (its own `LEGAL_API_KEY`). The manager applies the same\n * rule so a key it stores can never be one the official card would refuse.\n */\nexport function isLegalKeyValue(value: unknown): value is string {\n return typeof value === 'string' && /^[\\x21-\\x7E]+$/.test(value)\n}\n\n/** Shortest value that still gets a head and a tail; below it, a flat mask. */\nconst KEY_MASK_MIN_LENGTH = 12\n\n/**\n * A stored key's display form: a head, an ellipsis and a tail \u2014 enough to tell\n * two look-alike keys apart, never the whole secret.\n *\n * The manager shows every row this way, so a list can say which key a row holds\n * without putting anything usable on the page; the eye beside the field stays\n * the one gesture that reveals a value. A value too short to survive trimming\n * gets a fixed-width mask instead: at that length a head and a tail would be\n * most of the key.\n */\nexport function maskKeyValue(value: string): string {\n if (value.length === 0) return ''\n if (value.length < KEY_MASK_MIN_LENGTH) return '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022'\n return `${value.slice(0, 4)}...${value.slice(-4)}`\n}\n", "/**\n * The provider key index: plugin-owned metadata about the keys configured for\n * one provider route.\n *\n * The harness stores VALUES only: `<DSH_HOME>/.credentials.yaml` holds one value\n * per reference, the service reports `{configured, source, writable}` and never\n * the value, and there is no enumeration API at all. A list of \"the keys this\n * provider has\", each with a human label, therefore cannot live in the harness\n * \u2014 it is plugin state. It is kept here, beside the harness home rather than\n * inside the pi-ai profile, because the official add-provider card writes the\n * WHOLE profile at `providers.<route>` and an unknown sibling key there would\n * be at the mercy of schema validation.\n *\n * The file holds no secrets: references and labels only, which is what makes it\n * safe to keep in plain text and easy for a user to inspect or repair by hand.\n * Existing unreadable or malformed files fail closed, so a mutation cannot\n * replace lost metadata with a fresh index. Every write is atomic (`write` to a\n * sibling temp file, then `rename`), so a\n * crash mid-write cannot leave a half-parsed index behind.\n *\n * All of it is synchronous on purpose: the host is single-threaded, so a\n * read-modify-write inside one request handler cannot interleave with another\n * request's, which is the whole concurrency story this file needs.\n *\n * @module dsh-model-think-level/key-index\n */\n\nimport { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport {\n normalizeKeyAlias,\n normalizeKeyDisabled,\n normalizeKeyModels,\n normalizeKeyProtocol,\n normalizeRouteEndpoints,\n type KeyEntry,\n type RouteEndpoints,\n type RouteProtocol,\n} from './key-refs.js'\n\n/** One route's entry, re-exported so the host half has a single import site. */\nexport type KeyIndexEntry = KeyEntry\n\n/**\n * Build one entry, writing only the fields that carry a value. Keeping absent\n * fields absent (rather than `undefined`) keeps hand-edited index files diff-\n * clean and lets `parseKeyIndex`/`writeKeyIndex` round-trip an unscoped key\n * without inventing an empty `models` list that would read as \"reached nothing\".\n * Being enabled is the default, so only a switched-off key carries the flag.\n */\nfunction makeEntry(\n ref: string,\n alias: string | undefined,\n models: readonly string[] | undefined,\n protocol: RouteProtocol | undefined,\n disabled: boolean | undefined,\n): KeyIndexEntry {\n const entry: {\n ref: string\n alias?: string\n models?: readonly string[]\n protocol?: RouteProtocol\n disabled?: boolean\n } = { ref }\n if (alias !== undefined) entry.alias = alias\n if (models !== undefined) entry.models = models\n if (protocol !== undefined) entry.protocol = protocol\n if (disabled === true) entry.disabled = true\n return entry\n}\n\n/** The whole index document, exactly as it sits on disk. */\nexport interface KeyIndexDocument {\n /** Schema version; a future shape can migrate by reading this. */\n readonly version: 1\n /** Route \u2192 keys, in the order the manager lists them. */\n readonly providers: Record<string, readonly KeyIndexEntry[]>\n /**\n * Route \u2192 the extra base URLs that provider holds beyond its own `baseURL`.\n * A key pinned to a concrete protocol draws its endpoint from here, which is\n * how one route serves both an OpenAI and an Anthropic endpoint. Absent means\n * \"no extra endpoints\" (every key falls back to the route's own `baseURL`).\n */\n readonly endpoints?: Record<string, RouteEndpoints>\n}\n\n/** A fresh, empty index. */\nexport function emptyKeyIndex(): KeyIndexDocument {\n return { version: 1, providers: {} }\n}\n\n/**\n * The harness home: `$DSH_HOME` when the host exports it, else the `~/.dsh`\n * the harness would have defaulted to. Never throws.\n */\nexport function harnessHome(): string {\n const configured = process.env['DSH_HOME']\n if (typeof configured === 'string' && configured.length > 0) return configured\n try {\n return join(homedir(), '.dsh')\n } catch {\n return '.dsh'\n }\n}\n\n/** Absolute path of the plugin's key index. */\nexport function keyIndexFilePath(home: string = harnessHome()): string {\n return join(home, 'dsh-model-think-level', 'key-index.json')\n}\n\n/**\n * Parse an already-decoded index document. Never throws and never trusts the\n * input: anything unrecognisable is dropped entry by entry, so a hand-edited or\n * truncated file costs at most the lines it got wrong.\n * @param raw - the decoded JSON value (or anything else).\n * @returns a well-formed document.\n */\nexport function parseKeyIndex(raw: unknown): KeyIndexDocument {\n if (typeof raw !== 'object' || raw === null) return emptyKeyIndex()\n const root = raw as Record<string, unknown>\n const providers = root['providers']\n if (typeof providers !== 'object' || providers === null) return emptyKeyIndex()\n const out: Record<string, KeyIndexEntry[]> = {}\n for (const [route, entries] of Object.entries(providers as Record<string, unknown>)) {\n if (route.length === 0 || !Array.isArray(entries)) continue\n const list: KeyIndexEntry[] = []\n for (const entry of entries) {\n if (typeof entry !== 'object' || entry === null) continue\n const record = entry as Record<string, unknown>\n const ref = record['ref']\n if (typeof ref !== 'string' || ref.length === 0) continue\n if (list.some(existing => existing.ref === ref)) continue\n const alias = normalizeKeyAlias(record['alias'])\n const models = normalizeKeyModels(record['models'])\n const protocol = normalizeKeyProtocol(record['protocol'])\n const disabled = normalizeKeyDisabled(record['disabled'])\n list.push(makeEntry(ref, alias, models, protocol, disabled))\n }\n if (list.length > 0) out[route] = list\n }\n const endpoints = parseEndpoints(root['endpoints'])\n const document: KeyIndexDocument = { version: 1, providers: out }\n return endpoints === undefined ? document : { ...document, endpoints }\n}\n\n/**\n * Read the provider-level endpoint map, dropping unusable entries. Kept separate\n * so a hand-edited or older file that never carried endpoints still parses.\n * @param raw - the decoded `endpoints` member (or anything else).\n * @returns the cleaned map, or undefined when it holds nothing usable.\n */\nfunction parseEndpoints(raw: unknown): Record<string, RouteEndpoints> | undefined {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined\n const out: Record<string, RouteEndpoints> = {}\n for (const [route, value] of Object.entries(raw as Record<string, unknown>)) {\n if (route.length === 0) continue\n const pair = normalizeRouteEndpoints(value)\n if (pair !== undefined) out[route] = pair\n }\n return Object.keys(out).length === 0 ? undefined : out\n}\n\n/** Read the index; only an absent file means a fresh, empty document. */\nexport function readKeyIndex(file: string = keyIndexFilePath()): KeyIndexDocument {\n let text: string\n try {\n text = readFileSync(file, 'utf8')\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') {\n return emptyKeyIndex()\n }\n throw error\n }\n const raw: unknown = JSON.parse(text)\n const record = typeof raw === 'object' && raw !== null && !Array.isArray(raw)\n ? raw as Record<string, unknown> : undefined\n const providers = record?.['providers']\n if (record === undefined || (record['version'] !== undefined && record['version'] !== 1) ||\n typeof providers !== 'object' || providers === null || Array.isArray(providers)) {\n throw new Error('the key index is malformed; repair it before changing keys')\n }\n for (const [route, entries] of Object.entries(providers)) {\n if (route.length === 0 || !Array.isArray(entries) || entries.some((entry: unknown) => {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return true\n const ref = (entry as Record<string, unknown>)['ref']\n return typeof ref !== 'string' || ref.length === 0\n })) {\n throw new Error('the key index is malformed; repair it before changing keys')\n }\n }\n // Keep the existing normalization, including unversioned documents, aliases\n // and duplicate references, for valid indexes written by older versions.\n return parseKeyIndex(raw)\n}\n\n/** Write the index at one path, atomically. */\nexport function writeKeyIndex(document: KeyIndexDocument, file: string = keyIndexFilePath()): void {\n mkdirSync(dirname(file), { recursive: true })\n const temporary = `${file}.${process.pid}.tmp`\n writeFileSync(temporary, `${JSON.stringify(document, null, 2)}\\n`, 'utf8')\n try {\n renameSync(temporary, file)\n } catch (error) {\n try {\n unlinkSync(temporary)\n } catch {\n // The temp file is best-effort cleanup; the rename failure is the news.\n }\n throw error\n }\n}\n\n/**\n * One synchronous read-modify-write. The returned document is what was stored.\n * @param mutate - pure document transform.\n * @param file - index path (tests pass a temp file).\n */\nexport function updateKeyIndex(\n mutate: (document: KeyIndexDocument) => KeyIndexDocument,\n file: string = keyIndexFilePath(),\n): KeyIndexDocument {\n const next = mutate(readKeyIndex(file))\n writeKeyIndex(next, file)\n return next\n}\n\n/** One route's keys, or an empty list. */\nexport function keyEntriesOf(document: KeyIndexDocument, route: string): readonly KeyIndexEntry[] {\n const entries = document.providers[route]\n return Array.isArray(entries) ? entries : []\n}\n\n/** Whether one route's list names this reference. */\nexport function hasKeyEntry(document: KeyIndexDocument, route: string, ref: string): boolean {\n return keyEntriesOf(document, route).some(entry => entry.ref === ref)\n}\n\n/**\n * Add a key, or relabel the one already there. Order is preserved: the list is\n * what the panel renders, and a key that moves on every rename is a worse list.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param alias - a label, or undefined to keep whatever is stored.\n */\nexport function withKeyEntry(\n document: KeyIndexDocument,\n route: string,\n ref: string,\n alias?: string | undefined,\n): KeyIndexDocument {\n const list = [...keyEntriesOf(document, route)]\n const index = list.findIndex(entry => entry.ref === ref)\n const label = normalizeKeyAlias(alias)\n if (index === -1) {\n list.push(makeEntry(ref, label, undefined, undefined, undefined))\n } else {\n const existing = list[index]\n // A relabel with no alias keeps the stored one; the model scope, the\n // pinned protocol and the switch state always ride along untouched \u2014\n // adding or renaming a key never re-probes it, nor silently re-pins its\n // protocol, nor switches it back on.\n const keptLabel = label === undefined ? existing?.alias : label\n list[index] = makeEntry(ref, keptLabel, existing?.models, existing?.protocol, existing?.disabled)\n }\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document) }\n}\n\n/**\n * Set (or clear) one key's label.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference; a no-op when it is not listed.\n * @param alias - the new label, or undefined to fall back to the reference.\n */\nexport function withKeyAlias(\n document: KeyIndexDocument,\n route: string,\n ref: string,\n alias: string | undefined,\n): KeyIndexDocument {\n const list = [...keyEntriesOf(document, route)]\n const index = list.findIndex(entry => entry.ref === ref)\n if (index === -1) return document\n const label = normalizeKeyAlias(alias)\n list[index] = makeEntry(ref, label, list[index]?.models, list[index]?.protocol, list[index]?.disabled)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document) }\n}\n\n/**\n * Set (or clear) one key's discovered model scope.\n *\n * This is the automatic-binding side of Scheme A: the host probes each key's\n * model listing and records what it reached here, so a later request for model\n * M can be routed to the first key that lists M. Passing `undefined` clears the\n * scope back to \"unscoped catch-all\"; an empty array records \"probed, reached\n * no models\". A no-op when the reference is not listed.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param models - the ids this key serves, or undefined to unscope it.\n */\nexport function withKeyModels(\n document: KeyIndexDocument,\n route: string,\n ref: string,\n models: readonly string[] | undefined,\n): KeyIndexDocument {\n const list = [...keyEntriesOf(document, route)]\n const index = list.findIndex(entry => entry.ref === ref)\n if (index === -1) return document\n const scope = models === undefined ? undefined : normalizeKeyModels(models)\n list[index] = makeEntry(ref, list[index]?.alias, scope, list[index]?.protocol, list[index]?.disabled)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document) }\n}\n\n/**\n * Set (or clear) one key's pinned wire protocol.\n *\n * This is the per-key protocol switch: a key pinned to `anthropic-messages`\n * signs requests routed through the Anthropic API and that key's endpoint, even\n * when the route's own `api` is an OpenAI one. Passing `undefined` restores the\n * AUTOMATIC wire: each request speaks the protocol the model's own family names\n * where the provider addressed that family, and the route's default otherwise.\n * A no-op when the reference is not listed.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param protocol - the protocol to pin, or undefined for \"automatic\".\n */\nexport function withKeyProtocol(\n document: KeyIndexDocument,\n route: string,\n ref: string,\n protocol: RouteProtocol | undefined,\n): KeyIndexDocument {\n const list = [...keyEntriesOf(document, route)]\n const index = list.findIndex(entry => entry.ref === ref)\n if (index === -1) return document\n const pinned = normalizeKeyProtocol(protocol)\n list[index] = makeEntry(ref, list[index]?.alias, list[index]?.models, pinned, list[index]?.disabled)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document) }\n}\n\n/**\n * Switch one key into or out of the routing pool.\n *\n * Switching a key off keeps everything else about it \u2014 its label, its model\n * scope, its pinned protocol \u2014 so switching it back on restores exactly what it\n * served. Passing `false` clears the mark; the entry then reads as an ordinary\n * in-use key again. A no-op when the reference is not listed.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n * @param disabled - whether no request may sign with this key.\n */\nexport function withKeyDisabled(\n document: KeyIndexDocument,\n route: string,\n ref: string,\n disabled: boolean,\n): KeyIndexDocument {\n const list = [...keyEntriesOf(document, route)]\n const index = list.findIndex(entry => entry.ref === ref)\n if (index === -1) return document\n const existing = list[index]\n list[index] = makeEntry(ref, existing?.alias, existing?.models, existing?.protocol, disabled ? true : undefined)\n return { version: 1, providers: { ...document.providers, [route]: list }, ...endpointsOf(document) }\n}\n\n/**\n * Set (or clear) one route's pair of extra base URLs.\n *\n * @param document - the current document.\n * @param route - the provider route key.\n * @param endpoints - the OpenAI/Anthropic base URLs, or undefined to clear both.\n */\nexport function withRouteEndpoints(\n document: KeyIndexDocument,\n route: string,\n endpoints: RouteEndpoints | undefined,\n): KeyIndexDocument {\n const map: Record<string, RouteEndpoints> = { ...(document.endpoints ?? {}) }\n const cleaned = normalizeRouteEndpoints(endpoints)\n if (cleaned === undefined) delete map[route]\n else map[route] = cleaned\n const next: KeyIndexDocument = { version: 1, providers: document.providers }\n return Object.keys(map).length === 0 ? next : { ...next, endpoints: map }\n}\n\n/**\n * Carry a document's existing endpoint map forward on a providers-only rewrite.\n * Spread as `{ version: 1, providers, ...endpointsOf(document) }` so the writers\n * above never silently drop a route's endpoints when they only touch key lists.\n * @param document - the source document.\n * @returns `{ endpoints }` when one exists, else `{}` (spreads to nothing).\n */\nfunction endpointsOf(document: KeyIndexDocument): { endpoints?: Record<string, RouteEndpoints> } {\n return document.endpoints === undefined ? {} : { endpoints: document.endpoints }\n}\n\n/**\n * Drop one key. The route key itself is removed once its list empties, so a\n * provider the user cleaned up leaves no residue in the file.\n * @param document - the current document.\n * @param route - the provider route key.\n * @param ref - the credential reference to forget.\n */\nexport function withoutKeyEntry(document: KeyIndexDocument, route: string, ref: string): KeyIndexDocument {\n const list = keyEntriesOf(document, route).filter(entry => entry.ref !== ref)\n const providers: Record<string, readonly KeyIndexEntry[]> = { ...document.providers }\n if (list.length === 0) delete providers[route]\n else providers[route] = list\n return { version: 1, providers, ...endpointsOf(document) }\n}\n", "/**\n * The pure half of multi-key routing: given the ordered keys a provider route\n * may authenticate with and the model a request names, decide WHICH key signs\n * the request first, and \u2014 when that request fails \u2014 WHICH key to try next.\n *\n * The rule the user asked for (Scheme A):\n * - Keys are listed in preference order; index 0 is the default.\n * - A model reachable through several keys goes to the FIRST key that can\n * serve it.\n * - A model only one key can serve sticks to that key.\n * - When a request errors, the next capable key is tried.\n *\n * \"Can serve\" is read from each key's discovered `models` scope:\n * - a scope that lists the model -> can serve it (an exact claim);\n * - an UNSCOPED key (no `models`) -> treated as a catch-all, so it can serve\n * anything (this is the state before a key has been probed, and the way a\n * user deliberately says \"this key takes whatever is left\");\n * - a scope that does NOT list the model -> cannot serve it (an exact denial).\n *\n * Eligible keys keep their list order, so the \"both can serve -> first key\"\n * and \"only one can -> that key\" rules both fall out of a single filter. If NO\n * key is eligible (a stale or empty scope across the board), every key is\n * returned as a last resort so a wrong scope can never strand a model the\n * first key could in fact reach.\n *\n * This module performs no I/O and knows nothing about credentials: the host\n * fills in each candidate's `value`, and the wire seam consumes the answer.\n *\n * On top of the model scope, three further signals decide the attempt order \u2014\n * the same three a gateway such as magpie mixes into its dispatch:\n *\n * - WIRE FIT: a key is ranked by how much translation the model needs (its own\n * family first, the route's default second, a different vendor's family\n * last), so a claude model on an OpenAI-speaking route reaches a key that\n * can speak the Anthropic wire before paying for a translated round trip.\n * A key PINNED to a protocol always speaks it; an UNPINNED key is automatic\n * ({@link autoWireOf}) \u2014 it speaks the model family's own wire against that\n * family's address when the key carries one, and the route's default\n * otherwise;\n * - HONOUR: a pin that crosses wire families without that family's endpoint\n * cannot re-dispatch, so it trails the keys that can (it is never dropped: a\n * lone key must still sign the request);\n * - COOLDOWN: a key that just failed with a retryable status rests for a while\n * instead of being charged the same failure again on the next request.\n *\n * The wire seam alone ranks by wire, because only it can act on a pin; the fetch\n * seam only consults the cooldown memory, since it can neither switch a protocol\n * nor pick the URL.\n *\n * @module dsh-model-think-level/key-route-core\n */\n\nimport { endpointFamilyOf, type EndpointFamily, type RouteProtocol } from './key-refs.js'\n\n/** One key a route may use, with the secret already resolved. */\nexport interface KeyCandidate {\n /** Stable credential reference (for diagnostics and de-duplication). */\n readonly ref: string\n /** The secret to put on the wire. */\n readonly value: string\n /**\n * Model ids this key is known to serve. `undefined` means \"unscoped\": not\n * probed yet, or deliberately left as a catch-all. An array (possibly empty)\n * is a concrete scope.\n */\n readonly models?: readonly string[]\n /**\n * The wire protocol this key must speak, when it is pinned to one.\n * `undefined` means AUTOMATIC: the request speaks whichever wire the model's\n * own family names \u2014 an Anthropic-family endpoint for claude models, the\n * Gemini one for gemini models, the route's default for everything else \u2014\n * as far as the key carries that family's address in {@link endpoints}.\n * A concrete value makes the wire seam re-dispatch the request through that\n * protocol's API implementation (a true protocol switch), using {@link endpoint}.\n */\n readonly protocol?: RouteProtocol\n /**\n * The base URL to send this key's request to, already resolved for the key's\n * protocol family. `undefined` means \"use the model's own baseUrl\" (the route\n * default). A pinned-protocol key carries its family's endpoint here.\n */\n readonly endpoint?: string\n /**\n * The addresses an AUTOMATIC key (no {@link protocol}) may dispatch on, one\n * per endpoint family beyond the route's own. `wireOf` picks the model\n * family's entry and the wire seam sends the request there; families absent\n * from the map fall back to the route's default wire.\n */\n readonly endpoints?: Readonly<Partial<Record<EndpointFamily, string>>>\n}\n\n/** Whether `key` can serve `model`, per the scope rules above. */\nexport function canServe(key: KeyCandidate, model: string | undefined): boolean {\n // An unknown model (the body was unreadable) cannot be used to exclude any\n // key, so every key stays eligible and list order alone decides.\n if (model === undefined) return true\n const models = key.models\n // Unscoped is a catch-all: it has no claim that excludes this model.\n if (models === undefined) return true\n return models.includes(model)\n}\n\n/**\n * Order the keys that may sign a request for `model`, most-preferred first.\n *\n * The result is the eligible keys in their original list order. When the\n * filter leaves nothing, all keys are returned unchanged (last resort) \u2014 the\n * caller's failover loop still bounds the attempts, so an over-eager scope is\n * corrected on the wire rather than failing the request outright.\n * @param keys - the route's keys in preference order (may be empty).\n * @param model - the model id the request names, or undefined when unknown.\n * @returns the ordered candidates to try.\n */\nexport function keysForModel(\n keys: readonly KeyCandidate[],\n model: string | undefined,\n): KeyCandidate[] {\n if (model === undefined) return [...keys]\n const eligible = keys.filter(key => canServe(key, model))\n if (eligible.length === 0) return [...keys]\n // A key that names this model is an explicit assignment and outranks a\n // catch-all key that merely *may* serve anything: honouring the assignment\n // first is what makes \"this model belongs to that key\" true on the wire.\n const named = eligible.filter(key => key.models !== undefined)\n const catchAll = eligible.filter(key => key.models === undefined)\n return [...named, ...catchAll]\n}\n\n/** The wire families: one body format and one endpoint shape each. */\nexport type WireFamily = 'anthropic' | 'openai' | 'gemini'\n\n/** The family a protocol draws its body format and endpoint from. */\nexport function wireFamilyOf(protocol: RouteProtocol): WireFamily {\n if (protocol === 'anthropic-messages') return 'anthropic'\n if (protocol === 'google-generative-ai') return 'gemini'\n return 'openai'\n}\n\n/**\n * A model id that names its own family. Vendor-prefixed ids (`anthropic/claude-\u2026`)\n * and bare names (`claude-sonnet-5`, `gpt-6.1`, `o3-mini`, `codex-1`, `gemini-2.5-flash`)\n * both count; an id that names no family (a relay's `tierflow_pro`) is left unknown\n * so the route's own protocol stays the reference.\n */\nconst ANTHROPIC_MODEL_ID = /(?:^|[/:._-])(?:claude|anthropic)(?:$|[/:._-])/i\nconst OPENAI_MODEL_ID = /(?:^|[/:._-])(?:gpt|chatgpt|codex)(?:$|[/:._-])|(?:^|[/:._-])o[1-9](?:$|[/:._-])/i\nconst GEMINI_MODEL_ID = /(?:^|[/:._-])(?:gemini|gemma)(?:$|[/:._-])/i\n\n/** The family a model id announces, or undefined when it announces none. */\nexport function modelWireFamily(modelId: string | undefined): WireFamily | undefined {\n if (modelId === undefined) return undefined\n if (ANTHROPIC_MODEL_ID.test(modelId)) return 'anthropic'\n if (GEMINI_MODEL_ID.test(modelId)) return 'gemini'\n if (OPENAI_MODEL_ID.test(modelId)) return 'openai'\n return undefined\n}\n\n/**\n * The single wire a model id points at, when its family has only one.\n *\n * The OpenAI family has two wires (Chat Completions and Responses), so no id can\n * single one of them out \u2014 the route's own protocol stays the tie-breaker there.\n * The Anthropic and Gemini families have exactly one each, so a key pinned to\n * one of them needs no translation for a model of that family and deserves the\n * first attempt.\n * @param modelId - the model id the request names, or undefined.\n * @returns the concrete protocol, or undefined when the id does not settle one.\n */\nexport function modelWireHint(modelId: string | undefined): RouteProtocol | undefined {\n const family = modelWireFamily(modelId)\n if (family === 'anthropic') return 'anthropic-messages'\n if (family === 'gemini') return 'google-generative-ai'\n return undefined\n}\n\n/**\n * The wire an AUTOMATIC key (no pin) dispatches for `model`.\n *\n * The model's own family decides: a claude id speaks the Anthropic wire against\n * the Anthropic address, a gemini id speaks the Gemini wire against the Gemini\n * address \u2014 but only when the key actually carries that family's address; any\n * other model (or a family the route itself serves) keeps the route's default\n * wire, which is the one dispatch that always works. A wire that just failed\n * this model before any content (`avoid`) is skipped as the automatic choice \u2014\n * the route's wire is the fallback that answers when the family's gateway does\n * not \u2014 while an explicit pin is never second-guessed this way.\n * @param candidate - the key (only its `endpoints` map is read).\n * @param api - the protocol the route speaks.\n * @param model - the model id the request names, or undefined when unknown.\n * @param avoid - a wire not to pick automatically for this model, when one\n * recently failed.\n * @returns the protocol this attempt speaks.\n */\nexport function autoWireOf(\n candidate: Pick<KeyCandidate, 'endpoints'>,\n api: RouteProtocol,\n model: string | undefined,\n avoid?: RouteProtocol | undefined,\n): RouteProtocol {\n if (model === undefined) return api\n const family = modelWireFamily(model)\n // The route's own family has no separate address to switch to; the OpenAI\n // family has two wires and no id can single one out, so both stay on `api`.\n if (family === undefined || family === endpointFamilyOf(api)) return api\n if (candidate.endpoints?.[family] === undefined) return api\n const hinted: RouteProtocol =\n family === 'anthropic' ? 'anthropic-messages'\n : family === 'gemini' ? 'google-generative-ai'\n : 'openai-completions'\n return hinted === avoid ? api : hinted\n}\n\n/**\n * The protocol a key actually dispatches on a route speaking `api`.\n *\n * An unpinned key resolves automatically per model ({@link autoWireOf}). A pin\n * is honoured when it names the route's own family (a same-family switch needs\n * no other address) or when it carries the endpoint of its family, which is\n * what lets a true protocol switch happen. A cross-family pin with no endpoint\n * cannot be honoured \u2014 the route's base URL carries the route family's paths \u2014\n * so the key still signs on the route's own wire rather than being sent to an\n * address it does not own.\n * @param candidate - the key.\n * @param api - the protocol the route speaks.\n * @param model - the model id the request names, or undefined when unknown.\n * @param avoid - a wire the automatic resolution should skip, when one\n * recently failed for this model.\n * @returns the protocol the attempt will speak.\n */\nexport function wireOf(\n candidate: KeyCandidate,\n api: RouteProtocol,\n model?: string | undefined,\n avoid?: RouteProtocol | undefined,\n): RouteProtocol {\n const pinned = candidate.protocol\n if (pinned === undefined) return autoWireOf(candidate, api, model, avoid)\n const crossesFamilies = endpointFamilyOf(pinned) !== endpointFamilyOf(api)\n return crossesFamilies && candidate.endpoint === undefined ? api : pinned\n}\n\n/** Whether {@link wireOf} can honour the candidate's pin on this route. */\nexport function isHonoured(candidate: KeyCandidate, api: RouteProtocol): boolean {\n const pinned = candidate.protocol\n if (pinned === undefined) return true\n return endpointFamilyOf(pinned) === endpointFamilyOf(api) || candidate.endpoint !== undefined\n}\n\n/**\n * How much translation a key costs for a model: 0 needs none, 1 keeps the wire\n * family but changes the protocol (Chat Completions vs Responses), 2 speaks a\n * different vendor's family and would pay for a translated round trip.\n */\nexport type WireFit = 0 | 1 | 2\n\n/**\n * Rank one key against one model, following magpie's three-way fit: the model's\n * own family first, the request's own wire next, another family last.\n * @param candidate - the key.\n * @param api - the protocol the route speaks.\n * @param modelId - the model id, or undefined when the body was unreadable.\n * @param avoid - a wire the automatic resolution should skip, when one\n * recently failed for this model.\n * @returns 0 (native), 1 (translated within the family) or 2 (another family).\n */\nexport function protocolFit(\n candidate: KeyCandidate,\n api: RouteProtocol,\n modelId: string | undefined,\n avoid?: RouteProtocol | undefined,\n): WireFit {\n const wire = wireOf(candidate, api, modelId, avoid)\n const keyFamily = wireFamilyOf(wire)\n const targetFamily = modelWireFamily(modelId) ?? wireFamilyOf(api)\n if (keyFamily !== targetFamily) return 2\n // The route's own wire is the request the caller already made: nothing moves.\n if (wire === api) return 0\n return wire === modelWireHint(modelId) ? 0 : 1\n}\n\n/**\n * Stable partition: the items `keep` accepts first, in their original order,\n * then the rest, also in their original order.\n */\nfunction partition<T>(items: readonly T[], keep: (item: T) => boolean): T[] {\n const first: T[] = []\n const rest: T[] = []\n for (const item of items) (keep(item) ? first : rest).push(item)\n return [...first, ...rest]\n}\n\n/**\n * Order keys by wire fit alone, keeping list order inside each rank.\n *\n * A model whose family no key shares leaves every key at the same rank, so the\n * caller's order survives untouched: ranking can reorder, never drop.\n * @param candidates - the route's keys in preference order.\n * @param api - the protocol the route speaks.\n * @param modelId - the model id the request names, or undefined.\n * @param avoid - a wire the automatic resolution should skip, when one\n * recently failed for this model.\n * @returns a new array, stable within each rank.\n */\nexport function sortByFit(\n candidates: readonly KeyCandidate[],\n api: RouteProtocol,\n modelId: string | undefined,\n avoid?: RouteProtocol | undefined,\n): KeyCandidate[] {\n return candidates\n .map(candidate => ({ candidate, fit: protocolFit(candidate, api, modelId, avoid) }))\n .sort((a, b) => a.fit - b.fit)\n .map(entry => entry.candidate)\n}\n\n/** Move keys the caller reports as resting behind every key that is ready. */\nexport function restLast<T extends KeyCandidate>(\n candidates: readonly T[],\n isResting: (candidate: KeyCandidate) => boolean,\n): T[] {\n return partition(candidates, candidate => !isResting(candidate))\n}\n\n/** One key as the wire seam will attempt it, with the reasons recorded. */\nexport interface PlannedKey {\n readonly candidate: KeyCandidate\n /** The protocol this attempt will speak ({@link wireOf}). */\n readonly wire: RouteProtocol\n /** How much translation the model costs on this wire ({@link protocolFit}). */\n readonly fit: WireFit\n /** Whether a protocol pin can be honoured ({@link isHonoured}). */\n readonly honoured: boolean\n /** Whether this key is cooling down after a failure. */\n readonly resting: boolean\n}\n\n/** What the wire seam should attempt, in order, and why. */\nexport interface KeyPlan {\n /** The keys to try, most-preferred first (pool, then aside, then resting). */\n readonly ordered: readonly KeyCandidate[]\n /** The same order, annotated for diagnostics. */\n readonly entries: readonly PlannedKey[]\n /**\n * The keys that speak the starting wire. A failure inside the pool is most\n * likely environmental, so the pool is drained before any other wire is tried \u2014\n * a mixed-protocol route then costs at most one translated attempt.\n */\n readonly pool: readonly KeyCandidate[]\n /** Keys that would change the wire (or that a missing endpoint demotes). */\n readonly aside: readonly KeyCandidate[]\n /** The protocol the first attempt speaks, when there is any key at all. */\n readonly wire: RouteProtocol | undefined\n}\n\n/** What the wire seam knows about the request it is about to place. */\nexport interface PlanOptions {\n /** The protocol the route speaks. */\n readonly api: RouteProtocol\n /** The model id the request names, when it could be read. */\n readonly model?: string\n /** The wire that served this model last time, learned from a committed stream. */\n readonly preferredWire?: RouteProtocol\n /**\n * The wire that failed this model last time before any content, learned from\n * a pre-content failure. An automatic key does not pick it again for this\n * model ({@link autoWireOf}); explicit pins are never second-guessed.\n */\n readonly avoidWire?: RouteProtocol\n /** Whether a key is cooling down after a failure. */\n readonly isResting?: (candidate: KeyCandidate) => boolean\n}\n\n/**\n * Decide what the wire seam attempts, in which order, and on which wire.\n *\n * The order is the composition of four signals, strongest last, so a learned\n * fact always beats a heuristic and a hard constraint always beats both:\n *\n * 1. wire fit \u2014 least translation first ({@link protocolFit}; the automatic\n * resolution inside it also skips {@link PlanOptions.avoidWire});\n * 2. the wire that served this model last time ({@link PlanOptions.preferredWire});\n * 3. honour \u2014 keys whose pin can be dispatched before keys that cannot;\n * 4. pooling \u2014 the starting wire's keys first, other wires appended after them;\n * 5. cooldown \u2014 resting keys last, never dropped.\n *\n * Pooling splits the list without dropping anything: the aside keys are still\n * tried when the pool fails, which is what keeps a single misconfigured key from\n * stranding a model that a different wire could serve.\n * @param candidates - the keys the resolver returned, in preference order.\n * @param options - the route's wire, the model, and the runtime's memories.\n * @returns the plan the caller iterates.\n */\nexport function planKeys(candidates: readonly KeyCandidate[], options: PlanOptions): KeyPlan {\n const api = options.api\n const model = options.model\n const avoid = options.avoidWire\n const entries = candidates.map((candidate): PlannedKey => ({\n candidate,\n wire: wireOf(candidate, api, model, avoid),\n fit: protocolFit(candidate, api, model, avoid),\n honoured: isHonoured(candidate, api),\n resting: options.isResting?.(candidate) === true,\n }))\n const preferredWire = options.preferredWire\n const byFit = [...entries].sort((a, b) => a.fit - b.fit)\n const byPreferred = partition(byFit, entry => preferredWire === undefined || entry.wire === preferredWire)\n const byHonour = partition(byPreferred, entry => entry.honoured)\n // The starting wire is the best-ranked key that can actually be dispatched;\n // every key sharing it is drained before any other wire is attempted.\n const poolWire = byHonour.find(entry => entry.honoured)?.wire\n const pool = byHonour.filter(entry => entry.honoured && entry.wire === poolWire)\n const aside = byHonour.filter(entry => !(entry.honoured && entry.wire === poolWire))\n const ordered = partition([...pool, ...aside], entry => !entry.resting)\n return {\n ordered: ordered.map(entry => entry.candidate),\n entries: ordered,\n pool: pool.map(entry => entry.candidate),\n aside: aside.map(entry => entry.candidate),\n wire: ordered[0]?.wire,\n }\n}\n\n/**\n * Whether an HTTP status is worth retrying on the next key. Authentication and\n * authorization failures (the wrong key for this endpoint), rate limits, timeouts\n * and server faults are all \"this key did not work, try the next\"; a 400/404/422\n * is a request-shape problem that every key would answer identically, so it is\n * returned to the caller unchanged rather than multiplied across keys.\n * @param status - the response status code.\n */\nexport function shouldFailover(status: number): boolean {\n return status === 401 || status === 403 || status === 408 || status === 429 || status >= 500\n}\n\n/**\n * Why a key failed, as far as the next request is concerned. The distinction is\n * only between \"this key is the problem\" and \"every key would repeat it\", which\n * is why a 400 has no kind at all.\n */\nexport type FailureKind = 'auth' | 'rate' | 'quota' | 'server' | 'timeout' | 'refused'\n\n/**\n * Bodies that say \"the account is out of budget\" rather than \"you are going too\n * fast\". A 429 in this shape must not be retried next minute the way a rate\n * limit is: the key is done for the window, whatever the status implies.\n */\nconst QUOTA_FAILURE = /quota|insufficient|exhausted|balance|billing|credit|payment required|\u989D\u5EA6|\u4F59\u989D|\u6B20\u8D39|\u7528\u5C3D|\u914D\u989D|\u5145\u503C/i\n\n/**\n * What a failed attempt says about the key, or undefined when it says nothing \u2014\n * a request-shape failure (400/404/422) that every key would answer identically.\n * @param status - the response status, or undefined when the stream failed without one.\n * @param bodyText - the response body (bounded by the caller) or the stream's error text.\n * @returns the failure kind, or undefined for a failure the key did not cause.\n */\nexport function classifyFailure(status: number | undefined, bodyText = ''): FailureKind | undefined {\n if (status === undefined) return QUOTA_FAILURE.test(bodyText) ? 'quota' : 'refused'\n if (status === 401 || status === 403) return 'auth'\n if (status === 402) return 'quota'\n if (status === 408) return 'timeout'\n if (status === 429) return QUOTA_FAILURE.test(bodyText) ? 'quota' : 'rate'\n if (status >= 500) return 'server'\n return undefined\n}\n\n/** The first cooling period per kind: a wrong key is retired, a timeout is not. */\nconst COOLDOWN_MS: Record<FailureKind, number> = {\n auth: 5 * 60_000,\n rate: 60_000,\n quota: 30 * 60_000,\n server: 30_000,\n timeout: 30_000,\n refused: 60_000,\n}\n\n/** Longest a key is ever benched, whatever keeps failing. */\nexport const REST_COOLDOWN_CAP_MS = 30 * 60_000\n\n/**\n * How long a key should rest after its `failures`-th consecutive failure.\n *\n * The provider's own `Retry-After` is the floor when it is longer than the\n * kind's baseline (a server that says \"come back in an hour\" means it), and\n * repeated failures double the wait up to the cap so a dead key is not retried\n * on every request forever.\n * @param kind - why it failed.\n * @param failures - how many consecutive failures, 1 for the first.\n * @param retryAfterMs - the provider's `Retry-After`, already parsed.\n * @returns the resting period in milliseconds.\n */\nexport function cooldownFor(kind: FailureKind, failures = 1, retryAfterMs?: number): number {\n const asked = retryAfterMs !== undefined && retryAfterMs > 0 ? retryAfterMs : 0\n const base = Math.min(REST_COOLDOWN_CAP_MS, Math.max(COOLDOWN_MS[kind], asked))\n const escalated = base * 2 ** Math.max(0, failures - 1)\n return Math.round(Math.min(REST_COOLDOWN_CAP_MS, escalated))\n}\n\n/**\n * Parse a `Retry-After` header (delay-seconds or an HTTP date) into milliseconds.\n * @param value - the header value, when the response carried one.\n * @param now - the current time, for the date form.\n * @returns milliseconds to wait, or undefined when the value says nothing usable.\n */\nexport function parseRetryAfter(value: string | null | undefined, now: number): number | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n if (trimmed.length === 0) return undefined\n if (/^\\d+(?:\\.\\d+)?$/.test(trimmed)) return Math.round(Number(trimmed) * 1000)\n const at = Date.parse(trimmed)\n if (Number.isNaN(at)) return undefined\n return Math.max(0, at - now)\n}\n\n/** One key's cooling state: who benched it, until when, and how often it failed. */\nexport interface RestState {\n readonly kind: FailureKind\n /** Epoch milliseconds after which the key is a normal candidate again. */\n readonly until: number\n /** Consecutive failures that produced this period. */\n readonly failures: number\n}\n\n/** How a failure was observed, so the period can honour the provider's word. */\nexport interface RestNote {\n /** The observation time; defaults to now. Injected so tests are deterministic. */\n readonly now?: number\n /** The provider's `Retry-After`, already parsed. */\n readonly retryAfterMs?: number\n}\n\n/** Bounded memory of which keys are benched and for how long. */\nexport interface RestStore {\n /** How many keys it remembers (expired entries included until pruned). */\n readonly size: number\n /** The live state of a key, or undefined when it is a normal candidate again. */\n stateOf(key: string, now: number): RestState | undefined\n /** Whether the key should be deferred right now. */\n isResting(key: string, now: number): boolean\n /** Record one failure of a key and return the state it is now in. */\n note(key: string, kind: FailureKind, options?: RestNote): RestState\n /** The key answered: forget its failures. */\n clear(key: string): void\n /** Forget every key. */\n reset(): void\n}\n\n/** Enough for a host that churns through routes without growing without bound. */\nexport const REST_STORE_LIMIT = 256\n\n/**\n * Create a cooldown store.\n *\n * Holding the clock outside makes the store a pure function of its call history,\n * which is what lets both seams share one memory while the tests drive it.\n * @param limit - how many keys it may remember before pruning expired entries.\n * @returns a store with no keys resting.\n */\nexport function createRestStore(limit = REST_STORE_LIMIT): RestStore {\n const resting = new Map<string, RestState>()\n const live = (key: string, now: number): RestState | undefined => {\n const state = resting.get(key)\n if (state === undefined) return undefined\n if (state.until > now) return state\n resting.delete(key)\n return undefined\n }\n return {\n get size(): number { return resting.size },\n stateOf: live,\n isResting(key, now) { return live(key, now) !== undefined },\n note(key, kind, options) {\n const now = options?.now ?? Date.now()\n const previous = live(key, now)\n const failures = previous === undefined ? 1 : previous.failures + 1\n const until = now + cooldownFor(kind, failures, options?.retryAfterMs)\n if (resting.size >= limit) {\n for (const [staleKey, state] of resting) {\n if (state.until <= now) resting.delete(staleKey)\n }\n // Still full of live entries: a bounded memory matters more than history.\n if (resting.size >= limit) resting.clear()\n }\n const state: RestState = { kind, until, failures }\n resting.set(key, state)\n return state\n },\n clear(key) { resting.delete(key) },\n reset() { resting.clear() },\n }\n}\n\n/**\n * The key a cooldown belongs to: the route and the credential reference.\n *\n * Deliberately not per model: a 401 or a 429 describes the credential and its\n * account, and charging the same key a known failure on every model of the route\n * is what a cooldown exists to prevent.\n * @param route - the provider route key.\n * @param ref - the credential reference.\n */\nexport function restKeyOf(route: string, ref: string): string {\n return `${route}\\u0000${ref}`\n}\n\n/** The cooldown memory both seams share for this process. */\nexport const keyRest: RestStore = createRestStore()\n\n/** One key as it took part in a plan, without its secret. */\nexport interface PlannedKeyTrace {\n readonly ref: string\n readonly wire: RouteProtocol\n readonly fit: WireFit\n readonly honoured: boolean\n readonly resting: boolean\n}\n\n/** The last plan the wire seam built for a request, for `?diag=1`. */\nexport interface RoutePlanTrace {\n /** When the plan was built. */\n readonly at: number\n readonly route: string\n readonly model: string | undefined\n readonly wire: RouteProtocol | undefined\n readonly keys: readonly PlannedKeyTrace[]\n}\n\nconst PLAN_TRACE_LIMIT = 16\nconst planTraces: RoutePlanTrace[] = []\n\n/**\n * Remember a plan for diagnostics. Only references and ranks are kept \u2014 never a\n * key value \u2014 because the probe route prints these entries to the browser.\n * @param route - the provider route the plan was built for.\n * @param plan - the plan.\n * @param options - the model the plan was built for, and the time.\n */\nexport function recordRoutePlan(\n route: string,\n plan: KeyPlan,\n options?: { readonly model?: string; readonly now?: number },\n): void {\n planTraces.push({\n at: options?.now ?? Date.now(),\n route,\n model: options?.model,\n wire: plan.wire,\n keys: plan.entries.map(entry => ({\n ref: entry.candidate.ref,\n wire: entry.wire,\n fit: entry.fit,\n honoured: entry.honoured,\n resting: entry.resting,\n })),\n })\n if (planTraces.length > PLAN_TRACE_LIMIT) planTraces.splice(0, planTraces.length - PLAN_TRACE_LIMIT)\n}\n\n/** The most recent plans, newest last. */\nexport function readRoutePlans(limit = PLAN_TRACE_LIMIT): readonly RoutePlanTrace[] {\n return planTraces.slice(Math.max(0, planTraces.length - limit))\n}\n\n/** Forget the recorded plans. */\nexport function resetRoutePlans(): void {\n planTraces.length = 0\n}\n\n\n\n/**\n * Re-sign `headers` with `value` in place, preserving whichever credential\n * scheme the request already used.\n *\n * pi-ai's provider has ALREADY set the auth header from the route's configured\n * key by the time a request reaches the fetch seam; this only swaps the value so\n * the chosen key takes effect without re-deriving the scheme. If neither header\n * is present (a transport that auths elsewhere), a Bearer `authorization` is\n * added. The opposite scheme's header is cleared so two credentials can never\n * ride along together.\n * @param headers - the mutable request headers.\n * @param value - the secret to sign with.\n */\nexport function applyKeyToHeaders(headers: Headers, value: string): void {\n const usesGoogle = headers.has('x-goog-api-key')\n const usesApiKey = headers.has('x-api-key')\n const usesBearer = headers.has('authorization')\n if (usesGoogle) headers.set('x-goog-api-key', value)\n if (usesApiKey) headers.set('x-api-key', value)\n if (usesBearer) headers.set('authorization', `Bearer ${value}`)\n // A request that carried no credential header at all: default to Bearer.\n if (!usesGoogle && !usesApiKey && !usesBearer) headers.set('authorization', `Bearer ${value}`)\n // Never let another scheme's (stale) credential linger. A request that named\n // the google scheme carries the only credential that scheme understands, so\n // the other two are cleared together; otherwise an api-key outranks a Bearer.\n if (usesGoogle) {\n headers.delete('authorization')\n headers.delete('x-api-key')\n } else if (usesApiKey && usesBearer) {\n headers.delete('authorization')\n }\n}\n\n/**\n * The header names that carry a credential, for the three wire styles the\n * harness and its pinned keys speak: Anthropic Messages uses `x-api-key`,\n * Google Generative AI uses `x-goog-api-key`, everything else a Bearer\n * `authorization`. Used to (a) overwrite whichever one the SDK already set, and\n * (b) know the name to remove when a request is re-signed with a different key.\n */\nconst AUTH_HEADERS = ['authorization', 'x-api-key', 'x-goog-api-key'] as const\n\n/** The credential header names, exported for the wire seam's diagnostics. */\nexport const CREDENTIAL_HEADERS: readonly string[] = AUTH_HEADERS\n\n/**\n * Marker the wire seam (headers-pi-ai) stamps on requests it dispatched: it\n * chose that request's key, wire protocol and endpoint, so the fetch seam\n * (headers-fetch) must apply only its header patch and leave the signature and\n * the failover alone \u2014 the two seams rank keys differently on purpose, and a\n * re-signing fetch layer would put a different key's credential on a body\n * encoded for the wire seam's choice. Carries a constant value only (never a\n * reference or secret) and is stripped before the request leaves the fetch\n * wrapper.\n */\nexport const WIRE_DISPATCH_HEADER = 'x-dsh-model-think-level-wire'\n", "/**\n * The reasoning-effort + input-modality knowledge base + wire-protocol\n * inference engine.\n *\n * Every model a third-party provider route serves must declare its\n * 'reasoningEfforts' (which DSH thinking levels it accepts, and the exact\n * string to send on the wire for each) before the composer's model picker\n * offers any reasoning control for it. This module answers \"what should this\n * model's declaration be?\" from three sources, in order:\n *\n * 1. An endpoint listing signal (when the route was probed): an explicit\n * \"does not reason\", a modality disclosure, or a context length.\n * 2. A curated knowledge base keyed by model id/name patterns, carrying the\n * exact level set, wire spellings, request modalities, and reference\n * capacities known to work against that family of endpoints.\n * 3. Wire-protocol inference from the route's 'api' / 'baseURL', plus a\n * conservative name heuristic for modalities, for families nothing else\n * names.\n *\n * All outputs stay on the adapter's own vocabulary (THINKING_LEVELS,\n * INPUT_MODALITIES, the reasoningEfforts/input dict shapes) so a suggested\n * declaration can be written to llm-pi-ai settings with no translation step.\n * A suggestion is a *preset*: the user can accept it, tune it, or ignore it.\n * The plugin never silently overwrites a declaration the user already made.\n *\n * @module dsh-model-think-level/knowledge\n */\n\n/** The canonical pi-ai escalation order accepted by llm-pi-ai. */\nexport const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const\n\nexport type ThinkingLevel = (typeof THINKING_LEVELS)[number]\n\n/**\n * The request-modality vocabulary llm-pi-ai accepts on a model entry -- a\n * local mirror of pi-ai's MODALITY_GATE (text/image today). The core schema\n * refuses anything else at write time, and its drift gate forces the\n * vocabulary to grow exactly when pi-ai's Model['input'] does; the vocabulary\n * spec pins this mirror against upstream so the UI follows.\n */\nexport const INPUT_MODALITIES = ['text', 'image'] as const\n\nexport type InputModality = (typeof INPUT_MODALITIES)[number]\n\n/** One level's wire spelling; null means \"send nothing for this level\". */\nexport type WireSpelling = string | null\n\n/** A full reasoning-effort declaration value: level -> wire spelling. */\nexport type ReasoningEfforts = Partial<Record<ThinkingLevel, WireSpelling>>\n\n/** A full input-modality declaration value: the modalities a model accepts. */\nexport type InputModalities = readonly InputModality[]\n\n/** Reasoning-budget request-field spellings pi-ai accepts (older kernels reject them). */\nexport const THINKING_TOKEN_BUDGET_FIELDS = ['thinking_token_budget', 'thinking_budget', 'thinking_budget_tokens'] as const\nexport type ThinkingTokenBudgetField = (typeof THINKING_TOKEN_BUDGET_FIELDS)[number]\n\n/** The compat fields this plugin may suggest (a subset of the profile schema). */\nexport interface CompatSuggestion {\n /** Wire format the endpoint speaks; omitted when unknown. */\n thinkingFormat?: string\n /** Whether the endpoint accepts a reasoning-effort-style parameter. */\n supportsReasoningEffort?: boolean\n /**\n * Whether pi-ai may rewrite the system prompt to the developer role for\n * reasoning models. Self-hosted relays get an explicit false (their\n * upstreams reject role:developer); official endpoints keep pi-ai's own\n * detection default by omitting the field.\n */\n supportsDeveloperRole?: boolean\n /**\n * Anthropic-messages protocol only: force adaptive thinking so the\n * declared efforts dispatch as `output_config.effort` instead of falling\n * into the older budget-based thinking path. pi-ai offers this field on\n * exactly the anthropic-messages compat gate, and the oracle models that\n * take an effort ladder all have adaptive thinking.\n */\n forceAdaptiveThinking?: boolean\n thinkingTokenBudgetField?: ThinkingTokenBudgetField\n supportsThinkingTokenBudget?: boolean\n vllmPriority?: number\n}\n\n/**\n * Compat keys a kernel older than their introduction does not know, so an\n * autofill patch carrying one is stripped before the downgrade retry.\n *\n * `supportsMaxOutputTokens` is RETIRED -- the row editor no longer offers the\n * control -- but a profile written by an earlier version still carries the key,\n * and that stored value rides an autofill patch, so it stays on this list.\n */\nexport const NEW_COMPAT_KEYS = ['thinkingTokenBudgetField', 'vllmPriority', 'supportsMaxOutputTokens'] as const\n\n/** One knowledge-base entry: which model families it matches and what to declare. */\nexport interface KnowledgeEntry {\n /** Stable id (also used to de-duplicate user overrides). */\n id: string\n /** Model id/name patterns (lowercase substring match). */\n patterns: readonly string[]\n /**\n * Level set + wire spellings to declare. `false` marks a family the\n * official catalog serves WITHOUT any reasoning control (GPT-4o / GPT-4\n * generations): suggesting a ladder there would have the composer send\n * reasoning_effort and get a 400 from the real endpoint.\n */\n efforts: ReasoningEfforts | false\n /** Optional compat block to declare alongside the efforts. */\n compat?: CompatSuggestion\n /**\n * The model family takes an effort ladder on the anthropic-messages\n * protocol too: pi-ai only routes declared efforts to `output_config.effort`\n * when `forceAdaptiveThinking` is set, so this pin adds that compat block\n * on anthropic-messages routes (and nothing on any other protocol).\n */\n anthropicAdaptive?: boolean\n /**\n * Request modalities to declare, in core vocabulary. Absent = no modality\n * suggestion for this family. Wider support a gateway may serve (pdf,\n * audio, video) is recorded in 'note' until the core vocabulary grows.\n */\n input?: InputModalities\n /**\n * Reference context window in tokens. Rendered as footnote advice, and a\n * mounted row's official capacity input echoes it (fill-only) when a\n * suggestion is applied.\n */\n contextWindow?: number\n /** Reference max output tokens in tokens (same echo rule as the context window). */\n maxTokens?: number\n /**\n * The vendor's own default level for the family, when its docs name one\n * (the same research pass that recorded the ladders). Consumed by the\n * client's effort memory as the model-switch fallback: a switch to a model\n * with no remembered level re-applies the vendor default instead of leaving\n * the session on the host's \"Default\" (no-effort) state. Never guessed --\n * entries whose docs publish no default simply carry none.\n */\n defaultEffort?: ThinkingLevel\n /** Human note shown next to the suggestion (localized by the caller). */\n note?: string\n}\n\n/** What a provider route names about itself that inference can use. */\nexport interface RouteFacts {\n /** Wire protocol as configured ('api'), if any. */\n api?: string\n /** Endpoint URL, if any. */\n baseURL?: string\n /** Display name, if any. */\n displayName?: string\n}\n\n/** The endpoint facts a suggestion fuses, as the probe route reports them. */\nexport interface EndpointFacts {\n /** Tri-state reasoning signal: true / false / 'unknown' (listing silent). */\n reasoning: boolean | 'unknown'\n /** The listing field that produced the reasoning signal, null when none did. */\n source: string | null\n /**\n * The listing's input-modality disclosure, normalized to lowercase strings,\n * when the listing named such a field at all. Present-but-empty means the\n * field existed with no usable members; absent means the listing never\n * spoke about modalities (or the probe never ran) -- the tri-state\n * discipline: silence is not refusal.\n */\n input?: readonly string[]\n /** Context length the listing disclosed, when it carries one. */\n contextLength?: number\n}\n\n/** How a suggestion's input-modality part was derived. */\nexport type InputSource = 'knowledge' | 'endpoint' | 'heuristic'\n\n/** A resolved suggestion for one model on one route. */\nexport interface EffortSuggestion {\n /**\n * The reasoning-effort declaration to write, if one is derivable. False\n * arrives when the endpoint explicitly reports the model does not reason.\n */\n efforts?: ReasoningEfforts | false\n /**\n * The vendor's own default level for the model, when the knowledge base\n * names one and the suggested ladder carries it. The effort memory uses it\n * as the model-switch fallback (see {@link KnowledgeEntry.defaultEffort}).\n */\n defaultEffort?: ThinkingLevel\n /** The compat block to write alongside, if any. */\n compat?: CompatSuggestion\n /** Request modalities to declare, when derivable. */\n input?: InputModalities\n /** Where the modality part came from -- its confidence rides this. */\n inputSource?: InputSource\n /** Reference context window; echoed into the row's official capacity input when one is mounted. */\n contextWindow?: number\n /** Reference max output tokens (same echo rule as the context window). */\n maxTokens?: number\n /** Whether a knowledge-base entry matched (vs protocol inference). */\n matched: boolean\n /** The knowledge entry id when one matched. */\n entryId?: string\n /** Human-readable source of the suggestion. */\n source: string\n /**\n * Overall confidence for the UI: high = knowledge base (wire values) and/or\n * an explicit endpoint signal; medium = endpoint confirmed reasoning but the\n * level ladder is inferred; low = protocol inference alone.\n */\n confidence: 'high' | 'medium' | 'low'\n /** The endpoint signal behind this suggestion, when one was supplied. */\n endpoint?: { reasoning: boolean | 'unknown'; source: string | null }\n}\n\n/**\n * The curated knowledge base. Patterns are lowercase substring matches against\n * the model id (and display name). First match wins, longest pattern wins.\n *\n * Sources of truth (per family; DeepSeek / OpenAI / Anthropic re-checked\n * 2026-09 against their current official docs, the rest 2026-08): official API docs --\n * api-docs.deepseek.com (news/pricing/thinking/vision/API reference),\n * developers.openai.com model pages + guides (platform.openai.com blocked;\n * Azure learn mirror cross-checked), platform.claude.com (effort page,\n * models overview, OpenAI-SDK compatibility page), ai.google.dev (thinking +\n * OpenAI-compat pages), docs.x.ai (model pages + reasoning capability),\n * docs.bigmodel.cn (thinking + model pages), platform.kimi.com (models /\n * use-thinking-models / use-reasoning-effort), platform.stepfun.com (model\n * pages + reasoning), docs.byteplus.com / volcengine ModelArk (deep\n * reasoning), cloud.baidu.com (Qianfan pricing/thinking model list),\n * plus first-party GitHub cards (openai/gpt-oss, mistralai/mistral-common,\n * Tencent-Hunyuan/Hy3, MiniMax-AI/MiniMax-M3) -- cross-checked against the\n * public OpenRouter catalog (input_modalities, supported_parameters) where\n * noted. 2026-10 \u5168\u9762\u6821\u51C6 pass: the whole table was re-checked against\n * pi-ai 1.2.0's official model catalog, whose thinkingLevelMap semantics\n * are adopted here -- a level PRESENT in the map is accepted (a null value\n * means it dispatches via omit/budget/toggle channels, NOT an active\n * disable for the openai/anthropic families), and a level ABSENT is\n * refused and must not be declared. Capacities are REFERENCE values:\n * aggregators disagree, so the note says so where the spread is wide, and\n * families whose numbers stay contested simply carry none.\n */\nexport const KNOWLEDGE_BASE: readonly KnowledgeEntry[] = [\n {\n id: 'deepseek-v4-vision',\n // Must precede deepseek-v4 semantically -- guaranteed anyway by the\n // longest-boundary-hit rule, since these patterns are strictly longer.\n patterns: ['deepseek-v4-flash-vision', 'deepseek-v4-vision'],\n efforts: { off: 'none', low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 384_000,\n note: 'DeepSeek \u89C6\u89C9\u5B9E\u9A8C\u7248 id\uFF08deepseek-v4-flash-vision-exp\uFF09\u3002\u5B98\u65B9\u76EE\u5F55\u5DF2\u6807\u6CE8\u8BE5\u6A21\u578B\u9000\u5F79\uFF0C\u540D\u5B57\u4ECD\u88AB\u63A5\u53D7\u3001\u7531\u73B0\u884C deepseek-flash \u63D0\u4F9B\u670D\u52A1\u2014\u2014\u56FE\u7247\u8F93\u5165\u73B0\u5DF2\u7531 deepseek-flash \u539F\u751F\u63D0\u4F9B\u3002',\n },\n {\n id: 'deepseek-v4-1-flash',\n // V4.1-Flash is DeepSeek's CURRENT flagship and it takes image input, which\n // the shared `deepseek-v4` stem cannot express: that entry carries the text\n // floor its pro/legacy siblings share, and one modal answer cannot be both.\n // This entry keys every V4.1 spelling, and it must stay ahead of the base\n // stem -- the longest-hit rule guarantees that, these patterns are strictly\n // longer -- so an id, or a display name, that says \"V4.1 Flash\" declares\n // images even when the relay invented the id itself.\n // 'deepseek-flash' is the CURRENT official id (2026-09-10) and belongs\n // here, not to the stem: the pricing page serves it as V4.1-Flash, and a\n // third-party reseller exposing DeepSeek's own model under that name means\n // the same model.\n patterns: ['deepseek-v4.1-flash', 'deepseek-flash'],\n efforts: { off: 'none', low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 384_000,\n note: 'DeepSeek-V4.1-Flash\uFF082026-09-10 \u53D1\u5E03\u7684\u73B0\u884C\u5B98\u65B9\u6A21\u578B\uFF0C\u5B98\u65B9 id \u4E3A deepseek-flash\uFF1B25 \u4E07\u5E76\u53D1\u3001**\u539F\u751F\u56FE\u7247\u8F93\u5165**\uFF09\u3002V4.1 \u7684\u5404\u5199\u6CD5\uFF08deepseek-flash\u3001deepseek-v4.1-flash\u3001deepseek-v4-1-flash\uFF0C\u4EE5\u53CA\u5E26\u65E5\u671F\u540E\u7F00\u7684\u7B2C\u4E09\u65B9\u53D8\u4F53\uFF09\u90FD\u5F52\u6B64\u6761\u2014\u2014\u7EAF\u6587\u672C\u7684 deepseek-v4 \u4E3B\u5E72\u4E0D\u518D\u541E\u6389\u5B83\u4EEC\u3002\u5B98\u65B9\u679A\u4E3E\u540C V4 \u7CFB\uFF1AOff\uFF08thinking:\"disabled\"\uFF09/ Low / High / Max\uFF0C\u9ED8\u8BA4 High\uFF1B\u5BB9\u91CF 1,048,576 \u4E0A\u4E0B\u6587 / \u6700\u5927\u8F93\u51FA 384K\u3002',\n },\n {\n id: 'deepseek-v4',\n // One pattern covers the family's TEXT-floor members: every serving\n // suffixes the base id (deepseek-v4-flash, deepseek-v4-pro,\n // deepseek-v4-flash-free ...), so the shared stem keys them all --\n // including free/aggregator spellings the official catalog never lists.\n // Closing thinking is the 'thinking: disabled' object, so the off spelling\n // is a non-null placeholder that arms the deepseek format's disabled\n // branch. The placeholder must stay 'none': pi-ai's deepseek completions\n // branch only checks non-null (any string arms thinking:disabled), while\n // the same map rides the Responses API as reasoning.effort, whose official\n // DeepSeek values are none/low/high/max -- 'off' would be a 400 there.\n // The stem deliberately stops at 'deepseek-v4': the image-capable V4.1\n // generation keys its own strictly longer entry above, while this entry\n // keeps the retired deepseek-v4-flash spelling and the text-only\n // deepseek-v4-pro, whose declarations agree with its text floor.\n patterns: ['deepseek-v4'],\n efforts: { off: 'none', low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 1_048_576,\n maxTokens: 384_000,\n note: 'DeepSeek \u5B98\u65B9\u679A\u4E3E Low / High / Max\uFF08\u9ED8\u8BA4 High\uFF1Bminimal\u3001medium\u3001xhigh \u517C\u5BB9\u6620\u5C04\uFF0Cultra\u2192max\uFF09\uFF0COff \u5373 thinking:\"disabled\"\uFF08Responses API \u4E0B off \u4EE5 reasoning.effort:\"none\" \u8868\u793A\uFF09\u3002\u672C\u6761\u76EE\u662F V4 \u5BB6\u65CF\u7684**\u7EAF\u6587\u672C**\u6210\u5458\uFF1Adeepseek-v4-pro\uFF08= DeepSeek-V4-Pro-0813\uFF0C\u5B98\u65B9\u4E0D\u652F\u6301\u56FE\u7247\uFF09\u4E0E\u5DF2\u9000\u5F79\u6A21\u578B\u7684\u517C\u5BB9\u522B\u540D deepseek-v4-flash\uFF08deepseek-v4-flash-vision-exp \u53E6\u6709\u89C6\u89C9\u6761\u76EE\uFF09\u3002**\u6536\u56FE\u7684 V4.1-Flash\uFF08\u5B98\u65B9 id deepseek-flash\uFF09\u53E6\u6709\u4E13\u95E8\u6761\u76EE**\uFF0C\u5176 input \u542B image\u3002\u5BB9\u91CF\uFF1A1,048,576 \u4E0A\u4E0B\u6587 / \u6700\u5927\u8F93\u51FA 384K\uFF08393,216\uFF1B\u9ED8\u8BA4\u975E\u601D\u8003 8K\u3001\u601D\u8003 64K\u3001effort=max \u65F6 128K\uFF09\u3002',\n },\n {\n id: 'deepseek-v3',\n // deepseek-reasoner belongs to the R1 entry: it is the reasoning model's\n // API name and must not match here. The old alias pair\n // (deepseek-chat / deepseek-reasoner) was retired upstream in 2026-07;\n // the id patterns stay for third-party gateways still serving V3.x.\n patterns: ['deepseek-v3', 'deepseek-chat'],\n efforts: { off: 'none', high: 'high', max: 'max' },\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 163_840,\n maxTokens: 65_536,\n note: 'DeepSeek V3 \u6863\u4F4D\uFF1AOff / High / Max\u3002\u5B98\u65B9\u5DF2\u505C\u552E V3 \u4EE3\uFF08\u5B9A\u4EF7\u9875\u4EC5\u5269 V4 \u4E09\u578B\uFF09\uFF0C\u5BB9\u91CF\u53D6\u76EE\u5F55\u73B0\u5F79\u503C\u3002',\n },\n {\n id: 'deepseek-r1',\n patterns: ['deepseek-r1', 'deepseek-reasoner'],\n // R1's reasoning cannot be switched off at the API level; the harness\n // treats it as a thinking model whose only declared level is the default.\n efforts: { high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 163_840,\n maxTokens: 32_768,\n note: 'DeepSeek-R1 \u4E3A\u63A8\u7406\u6A21\u578B\uFF0C\u4EC5\u63D0\u4F9B High\u3002\u5B98\u65B9\u5DF2\u4E0B\u67B6 R1 \u4EE3\uFF0C\u5BB9\u91CF\u53D6\u76EE\u5F55 r1-0528 \u503C\u3002',\n },\n {\n id: 'openai-gpt-5-2',\n patterns: ['gpt-5.2'],\n // gpt-5.2 (2025-12) took 'none' as the explicit no-thinking value\n // (replacing gpt-5's 'minimal') and added xhigh; its default is none.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.2 \u6863\u4F4D\uFF1ANone / Low / Medium / High / XHigh\uFF08\u9ED8\u8BA4 None\uFF09\u3002\u5B98\u65B9\u53E6\u652F\u6301 PDF \u8F93\u5165\uFF08\u6838\u5FC3\u8BCD\u8868\u6682\u4E0D\u542B\uFF09\u3002gpt-5.2-pro \u5B98\u65B9\u9875\u672A\u5355\u5217\u6863\u4F4D\u884C\uFF0C\u6309\u672C\u6761\u76EE\u540C\u6863\u5904\u7406\uFF1Bgpt-5.2-codex \u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'openai-gpt-5-2-codex',\n // The codex variant's official model page names low/medium/high/xhigh\n // only -- NO none -- so the shared gpt-5.2 entry must not claim an off\n // for it (a 'none' request would 400). Longer pattern wins over 'gpt-5.2'.\n patterns: ['gpt-5.2-codex'],\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n // OpenAI's API default for the codex line is medium (Inspect AI's\n // per-model default table, aligned with developers.openai.com).\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.2-Codex \u6863\u4F4D\uFF1ALow / Medium / High / XHigh\uFF08\u65E0 None \u6863\uFF0C\u52FF\u52FE Off\uFF09\uFF0C\u5E26\u56FE\u8F93\u5165\u3001400K\u3002',\n },\n {\n id: 'openai-gpt-5-6',\n patterns: ['gpt-5.6'],\n // gpt-5.6 spans the full modern ladder including max; the sol/luna/terra\n // variants share it (official reasoning guide: values \"can include none\n // minimal low medium high xhigh, and max\"). pi-ai 1.2.0 catalog\n // confirms the FULL ladder at a 272,000 context.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-5.6\uFF08\u522B\u540D\u5373 sol\uFF09\u6863\u4F4D\uFF1ANone / Low / Medium(\u9ED8\u8BA4) / High / XHigh / Max\uFF1Bsol/luna/terra \u540C\u6863\uFF0C\u5E26\u56FE\u8F93\u5165\u30022026-10 \u6821\u51C6\uFF1A\u4E0A\u4E0B\u6587\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8BB0 272,000\uFF08\u6B64\u524D\u8BEF\u8BB0 1,050,000\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-5',\n patterns: ['gpt-5.5'],\n // gpt-5.5 defaults to medium (official reasoning guide) and tops out at\n // xhigh (max is ABSENT from the pi-ai 1.2.0 catalog); the -pro variant\n // (1.05M context, Responses-only) keeps high/xhigh only.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-5.5 \u6863\u4F4D\uFF1ANone / Low / Medium(\u9ED8\u8BA4) / High / XHigh\uFF08\u65E0 Max \u6863\uFF09\uFF0C\u5E26\u56FE\u8F93\u5165\u3002pro \u53D8\u4F53\u4EC5 High(\u9ED8\u8BA4) / XHigh\u30011.05M \u4E0A\u4E0B\u6587\u4E14\u4EC5 Responses API\u30022026-10 \u6821\u51C6\uFF1A\u4E0A\u4E0B\u6587\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8BB0 272,000\uFF08\u6B64\u524D\u8BEF\u8BB0 1,050,000\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-4',\n patterns: ['gpt-5.4'],\n // Official model page: none (default) / low / medium / high / xhigh;\n // pro drops none+low (medium/high/xhigh, 1.05M, Responses-only);\n // mini/nano sit on 400K. pi-ai 1.2.0 catalog: 272,000 context.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-5.4 \u6863\u4F4D\uFF1ANone(\u9ED8\u8BA4) / Low / Medium / High / XHigh\uFF0C\u5E26\u56FE\u8F93\u5165\u3002pro \u53D8\u4F53\u4EC5 Medium/High/XHigh\uFF081.05M\uFF09\uFF1Bmini/nano \u4E3A 400K \u4E0A\u4E0B\u6587\u30022026-10 \u6821\u51C6\uFF1A\u4E0A\u4E0B\u6587\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8BB0 272,000\uFF08\u6B64\u524D\u8BEF\u8BB0 1,050,000\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-3',\n patterns: ['gpt-5.3'],\n // pi-ai 1.2.0 catalog (gpt-5.3-codex): none IS accepted on the codex\n // line, spelled 'none' -- the older \"no none\" reading is retired.\n // gpt-5.3-chat (non-reasoning) keys its own openai-chat entry.\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.3-Codex \u6863\u4F4D\uFF1ANone / Low / Medium(\u9ED8\u8BA4) / High / XHigh\uFF0C\u5E26\u56FE\u8F93\u5165\u3001400K\uFF1B2026-10 \u6821\u51C6\uFF1ANone \u6863\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8865\u56DE\uFF08\u6B64\u524D\u6309\u65E7\u6A21\u578B\u9875\u8BB0\u4E3A\u65E0 None\uFF09\u3002gpt-5.3-chat \u4E3A\u975E\u63A8\u7406\u804A\u5929\u6A21\u578B\uFF08\u89C1 chat \u6761\u76EE\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-1',\n patterns: ['gpt-5.1'],\n // gpt-5.1 (2025-11): none replaces minimal; no xhigh outside codex-max.\n // The codex variants split into their own entry: their official pages\n // publish no effort line, and the codex line's 5.2/5.3 successors take\n // no none -- so the conservative declaration there drops both none and\n // xhigh (see openai-gpt-5-1-codex).\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.1 \u6863\u4F4D\uFF1ANone / Low / Medium / High\uFF08\u9ED8\u8BA4 None\uFF09\u3002',\n },\n {\n id: 'openai-gpt-5-1-codex',\n // Official model pages for 5.1-codex / -codex-max / -codex-mini publish no\n // reasoning-effort line (unlike gpt-5.1 itself); the codex successors\n // 5.2/5.3 are low/medium/high/xhigh without none, so none is NOT declared\n // here either. xhigh is likewise unproven for 5.1-codex (the 5.1 page's\n // own ladder stops at high) and is withheld.\n patterns: ['gpt-5.1-codex'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.1-Codex \u7CFB\u5217\uFF1A\u5B98\u65B9\u6A21\u578B\u9875\u672A\u5355\u5217 effort \u503C\u57DF\uFF0C\u6309\u540C\u4EE3\u4FDD\u5B88\u6863 Low / Medium / High\uFF08\u65E0 None\uFF1Bxhigh \u672A\u8BC1\u5B9E\uFF09\u3002\u5982\u7AEF\u70B9\u652F\u6301 xhigh/none \u53EF\u624B\u8C03\u3002',\n },\n {\n id: 'openai-gpt-5',\n patterns: ['gpt-5'],\n // The 2025-08 first generation: minimal is the floor, there is no none,\n // and the default (medium) thinks -- so no off level is offered.\n efforts: { minimal: 'minimal', low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5 \u521D\u4EE3\u6863\u4F4D\uFF1AMinimal / Low / Medium / High\uFF0C\u65E0\u5173\u95ED\u6863\u3002',\n },\n {\n id: 'openai-gpt-5-2-chat',\n // pi-ai 1.2.0 catalog: gpt-5.2-chat-latest IS a reasoning model with a\n // tiny ladder (off[omit] / medium / xhigh) at 128K -- it must not fall\n // into the non-reasoning openai-chat entry below, which is why that\n // entry's 'gpt-5.2-chat' pattern moved here.\n patterns: ['gpt-5.2-chat'],\n efforts: { off: null, medium: 'medium', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 16_384,\n note: 'GPT-5.2-Chat\uFF08\u5B98\u65B9 id gpt-5.2-chat-latest\uFF09\uFF1Api-ai 1.2.0 \u76EE\u5F55\u8BB0\u4E3A\u63A8\u7406\u6A21\u578B\uFF0C\u4EC5 Medium / XHigh \u4E24\u6863\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF0C\u975E\u663E\u5F0F\u5173\u95ED\uFF09\uFF0C128K / 16,384 \u8F93\u51FA\u30022026-10 \u65B0\u589E\u6761\u76EE\u3002',\n },\n {\n id: 'openai-chat',\n // Non-reasoning chat lines across generations: they take no\n // reasoning_effort at all (official model pages list no \"Reasoning\").\n // Official ids are the *-chat-latest snapshots; the bare -chat spellings\n // stay for gateways serving them. gpt-5-chat-latest was removed upstream\n // on 2026-07-23 and gpt-chat-latest has no model page anymore -- the\n // patterns persist for compatibility only. ('gpt-5.2-chat' moved to its\n // own reasoning entry above per pi-ai 1.2.0.)\n patterns: [\n 'gpt-5.1-chat-latest', 'gpt-5.3-chat-latest', 'gpt-5-chat-latest',\n 'gpt-chat-latest', 'gpt-5-chat', 'gpt-5.1-chat', 'gpt-5.3-chat',\n ],\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 16_384,\n note: '-chat \u7CFB\u5217\uFF08\u5B98\u65B9 id \u4E3A gpt-5.x-chat-latest\uFF09\u4E3A\u975E\u63A8\u7406\u804A\u5929\u6A21\u578B\uFF0C\u4E0D\u652F\u6301 effort \u53C2\u6570\uFF08\u52FF\u52FE\u601D\u8003\u6863\uFF09\uFF1B\u5B98\u65B9\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF0C128K / 16,384 \u8F93\u51FA\u3002gpt-5-chat-latest \u5DF2\u4E8E 2026-07-23 \u4E0B\u67B6\u3001gpt-chat-latest \u5DF2\u65E0\u5B98\u65B9\u9875\u9762\uFF08\u4FDD\u7559\u6A21\u5F0F\u4F9B\u7F51\u5173\uFF09\u3002gpt-5.2-chat \u53E6\u6709\u63A8\u7406\u6761\u76EE\u3002',\n },\n {\n id: 'openai-o',\n // The o-series scheduled-removal notice (2026-06-11): o1/o1-pro/o3-mini/\n // o4-mini are removed 2026-10-23 and o3/o3-pro on 2026-12-11, with\n // gpt-5.6-sol / gpt-5.6-terra replacing them; the tokens stay for\n // gateways and local deployments still serving them, and match only on\n // word boundaries (see matchKnowledgeBase), so 'o1' hits 'o1-mini' but\n // not 'ko1'.\n patterns: ['o1', 'o3', 'o4'],\n // o-series had no none: not sending the parameter meant medium (think\n // on), so no off level is offered.\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 200_000,\n maxTokens: 100_000,\n note: 'OpenAI o \u7CFB\u6863\u4F4D\uFF1ALow / Medium / High\u3002\u5B98\u65B9\u5DF2\u4E8E 2026-06 \u516C\u544A\u9000\u5F79\uFF08o1/o1-pro/o3-mini/o4-mini 2026-10-23 \u79FB\u9664\u3001o3/o3-pro 2026-12-11\uFF09\uFF0C\u7F51\u5173\u6B8B\u7559\u4ECD\u53EF\u547D\u4E2D\uFF1B\u591A\u6570 o \u7CFB\u7AEF\u70B9\u6536\u56FE\uFF08o3-mini \u4F8B\u5916\uFF09\u3002',\n },\n {\n id: 'openai-gpt-oss',\n // Official README: configurable reasoning effort low / medium / high\n // (CLI default: low); official model page: 131,072 context and exactly\n // the same 131,072 max output tokens, text input only.\n patterns: ['gpt-oss'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'low',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 131_072,\n maxTokens: 131_072,\n note: 'GPT-OSS \u5F00\u6E90\u6743\u91CD\uFF08Ollama/vLLM \u5E38\u89C1\uFF09\uFF1Areasoning effort Low / Medium / High\uFF0C\u7EAF\u6587\u672C\uFF0C131K \u4E0A\u4E0B\u6587 / 131K \u8F93\u51FA\u30022026-09 \u590D\u6838\uFF1A\u5B98\u65B9\u6A21\u578B\u9875\u73B0\u5728\u5199 Chat Completions = Not supported\u3001\u65E0\u56FE\u7247\u8F93\u5165\uFF08\u9ED8\u8BA4 Low \u6765\u81EA\u5B98\u65B9 CLI\uFF0C\u4E0D\u662F API \u9875\uFF09\uFF0C\u56E0\u6B64\u8FD9\u91CC\u4E0D\u518D\u58F0\u660E Off\u3002',\n },\n {\n id: 'openai-gpt-6',\n // GPT-6 luna/sol/terra (2026, after astra): pi-ai 1.2.0 catalog carries\n // the FULL ladder with an explicit 'none' off for luna/sol. astra keys\n // its own entry above (its off is the omit-style null), and 6.1-sol's\n // off is likewise omit-expressed there -- 'none' is not proven manually\n // adjustable on it, so it stays in the astra entry's shape.\n patterns: ['gpt-6-luna', 'gpt-6-sol', 'gpt-6-terra', 'gpt-6.1'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-6 \u7CFB\uFF08luna/sol/terra\uFF0C2026-10 \u6821\u51C6\u65B0\u589E\uFF09\uFF1Api-ai 1.2.0 \u76EE\u5F55\u5168\u6863 None / Low / Medium / High / XHigh / Max\uFF0C\u5E26\u56FE\u8F93\u5165\uFF0C272,000 \u4E0A\u4E0B\u6587 / 128,000 \u8F93\u51FA\u3002gpt-6-astra \u89C1\u5355\u72EC\u6761\u76EE\uFF08\u88F8 \"gpt-6\" \u4E0E 6.1-sol \u7531 astra \u6761\u76EE\u627F\u63A5\uFF0Coff \u4EE5\u7701\u7565\u8868\u8FBE\uFF0C\"none\" \u672A\u8BC1\u5B9E\u53EF\u624B\u8C03\uFF09\u3002',\n },\n {\n id: 'openai-gpt-6-astra',\n // Longest-pattern-wins keeps this ahead of the 5.x entries; 'astra' is the\n // only stable token an aggregator is likely to expose.\n patterns: ['gpt-6-astra', 'gpt-6', 'gpt-6.1-sol'],\n // Official reasoning guide: none returns HTTP 400 on this model, and the\n // model page lists low/medium/high/xhigh/max. pi-ai 1.2.0 catalog adds\n // minimal as present-null (omit-expressed) and keeps astra at 272,000.\n // The bare 'gpt-6' stem lives here (not on the luna/sol/terra sibling)\n // so gateways serving unversioned \"gpt-6\" keep the omit-style off that\n // astra/6.1-sol actually use; 'gpt-6.1' likewise -- only 6.1-sol exists\n // in the 1.2.0 catalog, and its off is omit-expressed like astra's.\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 272_000,\n maxTokens: 128_000,\n note: 'GPT-6 Astra \u6863\u4F4D\uFF1ALow / Medium / High / XHigh / Max\u2014\u2014**\u6CA1\u6709 None \u6863**\uFF08\u5B98\u65B9\u539F\u6587\uFF1A\u8BBE\u4E3A none \u8FD4\u56DE HTTP 400\uFF09\uFF0C\u56E0\u6B64\u672C\u6761\u76EE\u4E0D\u58F0\u660E Off\u3002\u5E26\u56FE\u8F93\u5165\uFF1B2026-10 \u6821\u51C6\uFF1A\u4E0A\u4E0B\u6587\u6309 pi-ai 1.2.0 \u76EE\u5F55\u8BB0 272,000\uFF08\u6B64\u524D\u8BEF\u8BB0 1,050,000\uFF09\u3002\u5DE5\u5177\u8C03\u7528\u9700\u8D70 Responses API\u3002gpt-6 luna/sol/terra \u89C1\u5355\u72EC\u6761\u76EE\uFF1B\u88F8 \"gpt-6\" \u4E0E 6.1-sol\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\u7531\u672C\u6761\u76EE\u627F\u63A5\u3002',\n },\n {\n id: 'openai-gpt-daybreak',\n // pi-ai 1.2.0 catalog: gpt-daybreak-blue-latest (1.05M) and -red-latest\n // (400K) take the FULL modern ladder with an explicit 'none' off.\n patterns: ['gpt-daybreak'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_050_000,\n maxTokens: 128_000,\n note: 'GPT-Daybreak\uFF08blue-latest 1.05M / red-latest 400K\uFF0C2026-10 \u65B0\u589E\uFF09\uFF1Api-ai 1.2.0 \u76EE\u5F55\u5168\u6863 None / Low / Medium / High / XHigh / Max\uFF0C\u5E26\u56FE\u8F93\u5165 / 128,000 \u8F93\u51FA\u3002',\n },\n {\n id: 'openai-gpt-realtime',\n // pi-ai 1.2.0 catalog: gpt-realtime-2.1 -- minimal joins the ladder as a\n // real wire value (off stays omit-style), 128K in / 32K out.\n patterns: ['gpt-realtime'],\n efforts: { minimal: 'minimal', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 32_000,\n note: 'GPT-Realtime 2.1\uFF082026-10 \u65B0\u589E\uFF09\uFF1Api-ai 1.2.0 \u76EE\u5F55\u6863\u4F4D Minimal / Low / Medium / High / XHigh\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF0C128,000 \u4E0A\u4E0B\u6587 / 32,000 \u8F93\u51FA\u3002',\n },\n {\n id: 'openai-gpt-5-6-cyber',\n // Before the family entry: cyber's model page publishes NO effort line and\n // limits Chat Completions, so the family ladder (which includes none/max)\n // must not be offered for it.\n patterns: ['gpt-5.6-cyber'],\n // Conservative: the codex-style successors publish no none, and cyber's\n // page publishes nothing at all -- declare the intersection the other 5.6\n // variants agree on, plus xhigh (every published 5.6 ladder carries it).\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 400_000,\n maxTokens: 128_000,\n note: 'GPT-5.6-Cyber\uFF1A\u5B98\u65B9\u6A21\u578B\u9875\u672A\u5355\u5217 effort \u503C\u57DF\uFF08\u4E0D\u7B49\u4E8E\u4E0D\u652F\u6301\uFF09\uFF0C\u6545\u6309\u540C\u4EE3\u4FDD\u5B88\u6863 Low / Medium / High / XHigh\uFF1B\u8BE5\u578B\u53F7\u4EC5 Responses API\uFF0C\u5E26\u56FE\u8F93\u5165\u3001400K \u4E0A\u4E0B\u6587\u3002\u5B98\u65B9\u652F\u6301\u7684\u5176\u4ED6\u6863\u4F4D\u53EF\u624B\u8C03\u540E\u5E94\u7528\u3002',\n },\n {\n id: 'openai-gpt-4o',\n // Boundary matching keeps 'gpt-4' from hitting 'gpt-4o', so the vision\n // generation needs its own entry. gpt-4.1 keeps its own entry below\n // (1M context, larger output cap).\n patterns: ['gpt-4o'],\n // GPT-4o is not a reasoning model (official catalog lists no reasoning,\n // the API refuses reasoning_effort): suggest `false` so the editor\n // marks the row \"does not reason\" instead of wiring a rejected ladder.\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 16_384,\n note: 'GPT-4o \u4EE3\u9645\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u4E0D\u652F\u6301 effort \u53C2\u6570\uFF08\u52FF\u52FE\u601D\u8003\u6863\uFF09\uFF1B\u56FE\u7247\u8F93\u5165\u5168\u7CFB\u6807\u914D\uFF0C128K / 16,384 \u8F93\u51FA\u3002',\n },\n {\n id: 'openai-gpt-4-1',\n // Official model page: 1,047,576 context / 32,768 max output, text+image\n // on every variant (4.1 / mini / nano alike -- the old \"nano is\n // text-only\" claim was wrong). No reasoning step at all.\n patterns: ['gpt-4.1'],\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 1_047_576,\n maxTokens: 32_768,\n note: 'GPT-4.1 \u5168\u7CFB\uFF08\u542B mini/nano\uFF09\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u4E0D\u652F\u6301 effort \u53C2\u6570\uFF1B\u5B98\u65B9 1,047,576 \u4E0A\u4E0B\u6587 / 32,768 \u8F93\u51FA\uFF0C\u5168\u7CFB\u5E26\u56FE\u8F93\u5165\u3002',\n },\n {\n id: 'openai-gpt-4-turbo-preview',\n // The preview snapshot is text-only (later turbo snapshots take images;\n // the shared preview spelling must not claim them). Longest-boundary-hit\n // keeps it ahead of 'gpt-4-turbo'.\n patterns: ['gpt-4-turbo-preview'],\n efforts: false,\n input: ['text'],\n contextWindow: 128_000,\n maxTokens: 4_096,\n note: 'GPT-4 Turbo Preview\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u7EAF\u6587\u672C\u8F93\u5165\uFF08\u6B63\u5F0F turbo \u5FEB\u7167\u652F\u6301\u56FE\u7247\uFF0C\u89C1\u4E0B\u6761\uFF09\uFF0C128K\u3002',\n },\n {\n id: 'openai-gpt-4-turbo',\n patterns: ['gpt-4-turbo'],\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 128_000,\n maxTokens: 4_096,\n note: 'GPT-4 Turbo\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u5B98\u65B9\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF0C128K / 4,096 \u8F93\u51FA\u3002',\n },\n {\n id: 'openai-gpt',\n patterns: ['gpt-4', 'gpt-3.5'],\n // Same reasoning as gpt-4o above: the GPT-4/3.5 generations take no\n // reasoning_effort -- suggest `false` rather than a rejected ladder.\n // gpt-4 remains text-only (8K window); the vision-bearing 4o/4.1/turbo\n // lines have their own entries.\n efforts: false,\n input: ['text'],\n note: 'GPT-4/3.5 \u4EE3\u9645\uFF1A\u975E\u63A8\u7406\u6A21\u578B\uFF0C\u4E0D\u652F\u6301 effort \u53C2\u6570\uFF08\u52FF\u52FE\u601D\u8003\u6863\uFF09\u3002gpt-4-turbo/4.1 \u8D77\u652F\u6301\u56FE\u7247\uFF0C\u89C1\u5355\u72EC\u6761\u76EE\uFF1B\u65B0\u4EE3\u8BF7\u7528 GPT-5 \u7CFB\uFF08\u89C1 openai-chat/gpt-5.x \u6761\u76EE\uFF09\u3002',\n },\n {\n id: 'anthropic-claude-5-5',\n // Claude 5.5 generation (2026-10): haiku/opus/sonnet-5-5 all take the\n // FULL effort ladder per pi-ai 1.2.0's official catalog (off and\n // minimal are present-null = omit-expressed, the five rungs dispatch as\n // output_config.effort). Absorbs the turn-2 haiku-5.5 entry: pi-ai\n // 1.2.0 names xhigh/max for the whole generation, the catalog size is\n // 1M/128K (not the 200K/64K first read off ofox's aggregator listing),\n // patterns cover the whole generation plus the bare aggregator\n // spelling. ('claude-haiku-5-5' is NOT listed separately: loose\n // normalization folds '-' and '.' identically, so the dotted spelling\n // already keys the dash spelling -- listing both would trip the\n // unique-normalized-pattern hygiene test.)\n patterns: ['claude-haiku-5.5', 'claude-opus-5-5', 'claude-sonnet-5-5', 'haiku-5.5', 'claude-5-5'],\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n defaultEffort: 'high',\n // No thinkingFormat: pi-ai has no 'anthropic' member, and the\n // openai-completions compat gate that takes thinkingFormat is not the\n // protocol an Anthropic endpoint speaks.\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude 5.5 \u4EE3\uFF08Haiku 5.5 / Opus 5.5 / Sonnet 5.5\uFF09\uFF1Api-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u5168\u6863 Low / Medium / High(\u9ED8\u8BA4) / XHigh / Max\uFF0C\u81EA\u9002\u5E94\u601D\u8003\uFF0C1M \u4E0A\u4E0B\u6587 / 128K \u8F93\u51FA\u3002off/minimal \u4EE5\u7701\u7565\u8868\u8FBE\uFF08\u76EE\u5F55\u5C06\u4E24\u952E\u8BB0\u4E3A null\uFF0C\u975E\u663E\u5F0F\u5173\u95ED\uFF09\u3002',\n },\n {\n id: 'anthropic-claude-5',\n // Claude 5th generation (fable/mythos-5/opus-5/sonnet-5, 2026): adaptive\n // thinking. 2026-10 calibration against pi-ai 1.2.0's official catalog:\n // low/medium/high were REMOVED from these models' effort maps (they\n // remain on the 5.5 generation) -- fable-5 and opus-5 keep only\n // xhigh/max (with an omit-expressed off), sonnet-5 keeps xhigh/max with\n // no off at all. Mythos has no pi-ai entry; it stays matched here\n // conservatively on the same-generation shape. Mythos Preview is split\n // into its own entry below.\n patterns: ['claude-fable-5', 'claude-mythos-5', 'claude-opus-5', 'claude-sonnet-5'],\n // Ladder per pi-ai 1.2.0 (claude-fable-5 / claude-opus-5 /\n // claude-sonnet-5). NOTE: Anthropic's own OpenAI-SDK compatibility\n // layer IGNORES reasoning_effort (thinking is driven by its own param,\n // on by default for Claude 5) -- the declaration bites on third-party\n // gateways that map it; on the native anthropic-messages protocol,\n // anthropicAdaptive pins the compat that makes pi-ai dispatch these as\n // output_config.effort.\n efforts: { xhigh: 'xhigh', max: 'max' },\n // pi-ai 1.2.0 publishes no default rung for this generation; the old\n // 'high' default was removed with the low/medium/high rungs themselves.\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude 5 \u4EE3\uFF08Fable 5 / Mythos 5 / Opus 5 / Sonnet 5\uFF09\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u5DF2\u6536\u7D27\u4E3A XHigh / Max\uFF08low/medium/high \u6863\u5DF2\u4ECE\u8BE5\u4EE3 effort \u76EE\u5F55\u79FB\u9664\uFF1BFable 5 \u4E0E Opus 5 \u53E6\u63A5\u53D7\u4EE5\u7701\u7565\u8868\u8FBE\u7684 off\uFF0CSonnet 5 \u65E0 off\uFF09\u30021M \u4E0A\u4E0B\u6587 / 128K \u8F93\u51FA\uFF08Batch 300K\uFF09\u3002\u5B98\u65B9\u652F\u6301 PDF \u8F93\u5165\u3002\u6CE8\u610F\uFF1AAnthropic \u5B98\u65B9 OpenAI \u517C\u5BB9\u5C42\u4F1A\u5FFD\u7565 effort \u53C2\u6570\uFF0C\u58F0\u660E\u5728\u7B2C\u4E09\u65B9\u7F51\u5173\u6620\u5C04\u65F6\u751F\u6548\u3002',\n },\n {\n id: 'anthropic-claude-5-1',\n // Ahead of the claude-5 entry, whose 'claude-fable-5' / 'claude-mythos-5'\n // patterns are prefixes of these ids and would win the equal-length tie.\n // 2026-10 calibration: pi-ai 1.2.0 keeps fable-5-1 on the same tight\n // xhigh/max map as fable-5 (plus mid-conversation effort support,\n // which this plugin does not declare per model).\n patterns: ['claude-fable-5-1', 'claude-mythos-5-1'],\n efforts: { xhigh: 'xhigh', max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude Fable 5.1 / Mythos 5.1\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u76EE\u5F55\u6863\u4F4D XHigh / Max\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF0C\u81EA\u9002\u5E94\u601D\u8003\u5E38\u5F00\uFF08\u4E0D\u63A5\u53D7 enabled/disabled\uFF09\u30021M \u4E0A\u4E0B\u6587 / 128K \u8F93\u51FA\uFF1BFable 5.1 \u652F\u6301\u4F1A\u8BDD\u4E2D\u9014\u6539\u6863\uFF08\u9700 beta header\uFF0C\u672C\u63D2\u4EF6\u4E0D\u6D89\u53CA\uFF09\u3002',\n },\n {\n id: 'anthropic-claude-mythos-preview',\n // Official effort matrix: max is available, xhigh is NOT (the matrix's\n // xhigh list covers Fable 5 / Mythos 5 / Opus 5 / Opus 4.8 / Opus 4.7 /\n // Sonnet 5 only). pi-ai 1.2.0 has no mythos entry at all; this entry\n // keeps its doc-derived ladder unchanged.\n patterns: ['claude-mythos-preview'],\n efforts: { low: 'low', medium: 'medium', high: 'high', max: 'max' },\n // Anthropic's effort page: the API default is HIGH across the whole\n // supported list (omitting effort behaves exactly as high).\n defaultEffort: 'high',\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude Mythos Preview\uFF1A\u5B98\u65B9\u6863\u4F4D Low / Medium / High / Max\uFF08\u65E0 XHigh\uFF09\uFF0C1M \u4E0A\u4E0B\u6587\u3002pi-ai 1.2.0 \u76EE\u5F55\u65E0 mythos \u6761\u76EE\uFF0C\u672C\u6863\u4F4D\u6CBF\u7528\u5B98\u65B9 effort \u77E9\u9635\u3002',\n },\n {\n id: 'anthropic-claude-opus-4-high',\n patterns: ['claude-opus-4-8', 'claude-opus-4-7'],\n // 2026-10 calibration: pi-ai 1.2.0's catalog lists ONLY xhigh/max for\n // opus-4-7/4-8 -- the low/medium/high rungs are gone from the official\n // effort maps (xhigh remains the recommended coding start on 4.7).\n efforts: { xhigh: 'xhigh', max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude Opus 4.7/4.8\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u6863\u4F4D\u4EC5 XHigh / Max\uFF08low/medium/high \u5DF2\u4ECE\u8BE5\u4EE3\u76EE\u5F55\u79FB\u9664\uFF1Bxhigh \u4E3A\u5B98\u65B9\u63A8\u8350\u7684\u7F16\u7801\u8D77\u6B65\u6863\uFF09\u30021M \u4E0A\u4E0B\u6587\u3002',\n },\n {\n id: 'anthropic-claude-4-6',\n patterns: ['claude-opus-4-6', 'claude-sonnet-4-6'],\n // 2026-10 calibration: pi-ai 1.2.0 narrows the 4.6 generation to a\n // single rung -- max only (the official effort page's \"some models that\n // support max don't support xhigh\" reading tightens further).\n efforts: { max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 128_000,\n note: 'Claude 4.6 \u4EE3\uFF08Opus 4.6 / Sonnet 4.6\uFF09\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u4EC5\u5269 Max \u4E00\u6863\uFF08low/medium/high/xhigh \u5747\u5DF2\u4ECE\u76EE\u5F55\u79FB\u9664\uFF09\u30021M \u4E0A\u4E0B\u6587\u3002',\n },\n {\n id: 'anthropic-claude-opus-4-5',\n // The only extended-thinking-only model in Anthropic's official effort\n // support list (claude-opus-4-5-20251101): effort works alongside\n // budget_tokens, and the max/xhigh columns of the official matrix do not\n // name it -- so the ladder tops out at high.\n patterns: ['claude-opus-4-5'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'high',\n compat: { supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 200_000,\n maxTokens: 64_000,\n note: 'Claude Opus 4.5\uFF1A\u5B98\u65B9 effort \u652F\u6301\u5217\u8868\uFF0820251101 \u5FEB\u7167\uFF09\uFF0C\u6863\u4F4D Low / Medium / High\uFF08\u65E0 XHigh/Max\uFF09\uFF0C\u53EF\u4E0E budget_tokens \u5E76\u7528\uFF1B200K / 64K\u3002',\n },\n {\n id: 'anthropic-claude',\n // Everything else in the Claude line: 3.x and the 4.5-generation\n // Sonnet/Haiku. Anthropic's official effort support list names exactly\n // the 5.5/5/5.1 generations plus opus-4-5/4-6/4-7/4-8/sonnet-4-6 -- none\n // of the models matching this entry take the effort parameter (their\n // thinking rides thinking.type), so a ladder here would be refused.\n // `false` is the honest \"no effort control\" declaration, matching the\n // openai-chat convention. (The 5.5 generation -- haiku/opus/sonnet-5-5,\n // including aggregator spellings like 'haiku-5.5' -- keys its own\n // strictly longer entry above.)\n patterns: ['claude'],\n efforts: false,\n input: ['text', 'image'],\n contextWindow: 200_000,\n maxTokens: 64_000,\n note: 'Claude 3.x \u4E0E Sonnet 4.5 / Haiku 4.5\uFF1A\u5B98\u65B9 effort \u53C2\u6570\u4E0D\u652F\u6301\uFF08\u4EC5 5.5/5/5.1 \u4EE3\u3001Opus 4.5/4.6/4.7/4.8\u3001Sonnet 4.6 \u652F\u6301\uFF09\uFF0C\u601D\u8003\u7531 thinking.type \u63A7\u5236\u2014\u2014\u52FF\u52FE\u601D\u8003\u6863\u3002\u53C2\u8003\u5BB9\u91CF 200K / 64K\uFF08Haiku 3.5 \u4E3A\u7EAF\u6587\u672C\uFF0C\u6309\u9700\u53D6\u6D88\u56FE\u7247\uFF09\u3002Haiku 5.5 \u53CA\u6574\u4E2A 5.5 \u4EE3\u89C1\u4E0A\u65B9 anthropic-claude-5-5 \u6761\u76EE\u3002',\n },\n {\n id: 'google-gemini',\n patterns: ['gemini'],\n // Gemini over the OpenAI-compat layer maps reasoning_effort per family\n // (3.1+/3.x -> thinking_level, 2.5 -> thinking_budget). The official\n // compatibility sheet is a full grid (minimal / low / medium / high x\n // family), but the declared ladder stays low/medium/high: the safest\n // universal set, since minimal lands on a non-native value on Gemini\n // 3.1 Pro and none is reserved for 2.5 non-Pro. Users wanting the finer\n // grid tune by hand.\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 65_536,\n note: 'Gemini \u901A\u7528\u5B89\u5168\u6863\uFF1ALow / Medium / High\uFF08\u5B98\u65B9 OpenAI \u517C\u5BB9\u6620\u5C04\u8868\u53E6\u6536 minimal\uFF1A2.5 \u7CFB\u6620\u5C04\u4E3A 1,024 \u9884\u7B97\u30013.1 Flash-Lite/3 Flash \u539F\u751F minimal\u30013.1 Pro \u843D low\uFF09\u3002none \u4EC5\u80FD\u5173 2.5 \u975E Pro\uFF1B2.5 Pro \u4E0E 3 \u4EE3\u4E0D\u53EF\u5173\uFF1B\u5404\u578B\u9ED8\u8BA4\u4E0D\u4E00\uFF08flash-lite \u9ED8\u8BA4\u5173\uFF09\u3002\u5B98\u65B9\u53E6\u6536\u97F3\u9891/\u89C6\u9891/PDF\u3002Gemma-4 \u89C1\u4E0B\u6761\u3002',\n },\n {\n id: 'google-gemma-4',\n // 2026-10 calibration NEW entry: pi-ai 1.2.0 keys gemma-4-26b-a4b-it /\n // gemma-4-31b-it with a THREE-slot map {off:null, minimal:'MINIMAL',\n // high:'HIGH'} -- the Google native spelling for this open model goes\n // upper-case enum style, and the medium/low rungs are ABSENT (they are\n // not accepted). Vision per catalog; 262,144 in / 32,768 out.\n patterns: ['gemma-4'],\n efforts: { off: null, minimal: 'MINIMAL', high: 'HIGH' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n maxTokens: 32_768,\n note: 'Gemma 4\uFF0826b/31b-it\uFF09\uFF1A\u4E09\u6863 Minimal / High\uFF08\u6863\u4F4D\u7EBF\u4E3A\u5B98\u65B9\u5927\u5199\u679A\u4E3E\u62FC\u5199\uFF09\uFF0Coff \u4EE5\u7701\u7565\u8868\u8FBE\uFF1BLow/Medium \u4E0D\u88AB\u63A5\u53D7\u3002\u5E26\u56FE\u8F93\u5165\uFF0C262,144 / 32,768\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF09\u3002',\n },\n {\n id: 'xai-grok-4-7',\n // grok-4.7 shipped after the 2026-08 pass that read it as 404 upstream;\n // that reading is retired here. 2026-10 calibration: pi-ai 1.2.0 is\n // now a first-party catalog entry -- the ladder\n // off[omit]/low/medium/high/xhigh is confirmed (max stays ABSENT), and\n // the earlier \"xhigh unverified\" hedge is retired. Capacity: 500K in /\n // 500K out per the catalog, so the \"max output disagrees across\n // catalogs\" note is resolved as 500,000.\n patterns: ['grok-4.7'],\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 500_000,\n maxTokens: 500_000,\n note: 'Grok 4.7\uFF1A\u6863\u4F4D Low / Medium / High / XHigh\uFF0C\u601D\u8003\u4E0D\u53EF\u5173\u95ED\uFF08off \u4EC5\u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF1B\u5E26\u56FE\u8F93\u5165\uFF0C500K \u4E0A\u4E0B\u6587 / 500K \u8F93\u51FA\uFF082026-10 \u6821\u51C6\uFF1Api-ai 1.2.0 \u5B98\u65B9\u76EE\u5F55\u786E\u8BA4\u6863\u4F4D\u4E0E\u5BB9\u91CF\uFF0C\"\u4E0A\u6E38 404\"\u4E0E\"\u6863\u4F4D\u672A\u8BC1\u5B9E\"\u4E24\u6761\u65E7\u8BB0\u5F55\u4F5C\u5E9F\uFF09\u3002grok-4.5 \u4F20 xhigh \u88AB\u9759\u9ED8\u6309 High \u5904\u7406\u7684\u8BF4\u660E\u89C1\u5176\u6761\u76EE\u3002',\n },\n {\n id: 'xai-grok-high',\n patterns: ['grok-4.6'],\n // grok-4.6 adds xhigh on top of low/medium/high (default) and cannot\n // close thinking (docs.x.ai model page + reasoning capability page).\n // (An earlier pass read grok-4.7 as 404 upstream; it shipped later --\n // see the entry above.)\n efforts: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 500_000,\n note: 'Grok 4.6 \u6863\u4F4D\uFF1ALow / Medium / High(\u9ED8\u8BA4) / XHigh\uFF0C\u601D\u8003\u4E0D\u53EF\u5173\u95ED\uFF1B\u5E26\u56FE\u8F93\u5165\u3001500K \u4E0A\u4E0B\u6587\u3002Grok 4.7 \u89C1\u4E0A\u4E00\u6761\uFF08\u6B64\u524D\u8BB0\u4E3A\"\u4E0D\u5B58\u5728\"\uFF0C\u5DF2\u968F\u53D1\u5E03\u4F5C\u5E9F\uFF09\u3002',\n },\n {\n id: 'xai-grok-4-5',\n // grok-4.5 keeps the three-step ladder (default high) with image input\n // and a 500K context window; an xhigh request is silently treated as\n // high (official reasoning page), so it is not declared here.\n patterns: ['grok-4.5'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 500_000,\n note: 'Grok 4.5 \u6863\u4F4D\uFF1ALow / Medium / High(\u9ED8\u8BA4)\uFF0C\u601D\u8003\u4E0D\u53EF\u5173\u95ED\uFF1B\u5E26\u56FE\u8F93\u5165\u3002\u4F20\u5165 xhigh \u4F1A\u88AB\u5B98\u65B9\u9759\u9ED8\u6309 High \u5904\u7406\u3002',\n },\n {\n id: 'xai-grok-4-3',\n // Official reasoning-capability pages: grok-4.3 documents FOUR effort\n // levels (none / low / medium / high) with a 1M context window; the\n // deprecated grok-4-fast/grok-4-1-fast/grok-4-0709 slugs redirect to\n // grok-4.3 at low/none. The old \"no none for 4.3\" reading of the docs\n // was wrong and is fixed here. 2026-10 calibration: pi-ai 1.2.0's\n // catalog has NO xhigh for 4.3 (it joins at 4.6/4.7) and puts the\n // output cap at 30,000 -- the xhigh rung from the earlier pass is\n // retired.\n patterns: ['grok-4.3'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'low',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 30_000,\n note: 'Grok 4.3\uFF1A\u5B98\u65B9\u56DB\u7EA7 reasoning effort\uFF08None / Low(\u9ED8\u8BA4) / Medium / High\uFF09\uFF0C1M \u4E0A\u4E0B\u6587 / 30,000 \u8F93\u51FA\uFF082026-10 \u6821\u51C6\uFF1AXHigh \u6863\u6309 pi-ai 1.2.0 \u76EE\u5F55\u79FB\u9664\u2014\u2014\u5B83\u81EA 4.6 \u8D77\u624D\u52A0\u5165\uFF1B\u5E26\u56FE\u8F93\u5165\uFF09\u3002grok-4-fast \u7B49\u65E7 slug 2026-05-15 \u8D77\u81EA\u52A8\u91CD\u5B9A\u5411\u5230\u672C\u578B\u53F7\u3002',\n },\n {\n id: 'xai-grok',\n // grok-4.5 (and 4.1-fast etc.) take the standard three-step ladder;\n // grok-4 and older reject reasoning_effort outright -- gateways serving\n // them will refuse the value and the user can clear it by hand. Grok\n // 4/4.1 and grok-3 retired 2026-05-15 (redirected to grok-4.3), and\n // grok-build-0.1 (early-access coding model) publishes no effort\n // contract.\n patterns: ['grok'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n note: 'Grok \u901A\u7528\u6863\u4F4D\uFF1ALow / Medium / High\u3002\u521D\u4EE3 grok-4\u3001grok-4.20 \u4E0E grok-build-0.1 \u4E0D\u63A5\u53D7\u8BE5\u53C2\u6570\uFF08grok-4 \u7CFB\u4E0E grok-3 \u5DF2\u4E8E 2026-05-15 \u9000\u5F79\u5E76\u91CD\u5B9A\u5411\u81F3 4.3\uFF09\uFF1Bgrok-4.20-multi-agent \u7684\u56DB\u6863\u63A7\u5236\u7684\u662F agent \u6570\u91CF\u800C\u975E\u601D\u8003\u6DF1\u5EA6\u3002\u65B0\u65E7\u4EE3\u9645\u8BF7\u4F18\u5148\u9009 4.5/4.6/4.3\uFF1B\u591A\u6A21\u6001\u53D8\u4F53\u6309\u9700\u52FE\u9009\u56FE\u7247\u3002',\n },\n {\n id: 'mistral-magistral',\n // 2026-10 calibration REVERSAL: pi-ai 1.2.0's official catalog keys\n // magistral-medium-latest on the new mistral-conversations protocol\n // WITH a two-state effort map (none/high, off spelled 'none') -- the\n // earlier \"no effort parameter / deprecated\" reading is retired. The\n // ladder is the same two-state shape the modern mistral-medium/small\n // line takes; vision per the catalog; capacity 262,144 in / 16,384 out.\n patterns: ['magistral'],\n efforts: { off: 'none', high: 'high' },\n // The catalog's no-parameter behaviour maps to the 'none' wire value.\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n maxTokens: 16_384,\n note: 'Magistral\uFF08magistral-medium-latest\uFF09\uFF1A2026-10 \u6821\u51C6\u2014\u2014pi-ai 1.2.0 \u76EE\u5F55\u663E\u793A\u73B0\u5F79 magistral \u8D70 mistral-conversations \u534F\u8BAE\u5E76\u63A5\u53D7 effort\uFF08None / High \u4E24\u6863\uFF0C\u9ED8\u8BA4 None\uFF09\uFF0C\u5E26\u56FE\u8F93\u5165\uFF0C262,144 / 16,384\u3002\u65E9\u524D\"\u8BE5\u7EBF\u65E0 effort \u53C2\u6570\u4E14\u5DF2\u5F03\u7528\"\u7684\u8BB0\u5F55\u4F5C\u5E9F\u3002',\n },\n {\n id: 'mistral-medium-3',\n // Official reasoning page + mistral-common request.py (the first-party\n // protocol enum) name the reasoning_effort models: values are exactly\n // none/high. 2026-10 calibration adds pi-ai 1.2.0's catalog ids: the\n // reasoning line now spans mistral-large-4 (1M/262K, vision),\n // mistral-medium-2604 / mistral-medium-latest (262K/262K, vision) plus\n // the earlier small-2603/small-latest pair -- all on the same\n // two-state none/high map on the mistral-conversations protocol.\n // Normalization folds '.' and '-' to the same space, so the one dotted\n // spelling also keys the API id (mistral-medium-3-5).\n patterns: [\n 'mistral-medium-3.5', 'mistral-large-4', 'mistral-medium-2604',\n 'mistral-medium-latest', 'mistral-small-latest', 'mistral-small-2603',\n ],\n efforts: { off: 'none', high: 'high' },\n // mistral-common's ModelSettings defaults reasoning_effort to None --\n // the endpoint's no-parameter behaviour IS the none/off level.\n defaultEffort: 'off',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n note: 'Mistral \u73B0\u5F79\u63A8\u7406\u6863\uFF082026-10 \u6269\u5145\uFF09\uFF1ANone / High \u4E24\u6863\uFF0C\u5B98\u65B9 reasoning_effort \u679A\u4E3E\u5373 none/high\uFF1B\u73B0\u5F79\u578B\u53F7 mistral-large-4\uFF081M\uFF09\u3001mistral-medium-3.5\uFF082604/latest\uFF09\u3001mistral-small-2603\uFF08Small 4\uFF09\u7ECF\u5B83\u63A7\u5236\uFF0C\u5747\u5E26\u89C6\u89C9\u3002\u5BB9\u91CF\uFF1Alarge-4 262,144 \u8F93\u51FA\u3001medium 262,144 \u8F93\u51FA\u3001small 256,000 \u8F93\u51FA\uFF08\u4E0A\u4E0B\u6587\u5747 262,144\uFF09\u3002\u975E\u63A8\u7406\u65E7\u6B3E\u89C1\u4E0B\u6761\u3002',\n },\n {\n id: 'mistral-legacy',\n // 2026-10 calibration: pi-ai 1.2.0 keys the NON-reasoning mistral line\n // (r=false, no tlm) separately from the two-state reasoning line above.\n // These slugs take no effort parameter at all; matching them here keeps\n // auto-adapt from handing them the reasoning ladder via the generic\n // 'mistral' stem. devstral/ministral/codestral/pixtral/voxtral carry\n // the stem too and are covered by the same false declaration.\n patterns: [\n 'mistral-large-2411', 'mistral-large-latest', 'mistral-large-2512',\n 'mistral-medium-2505', 'mistral-medium-2508', 'mistral-small-2506',\n 'mistral-nemo', 'devstral', 'ministral', 'codestral', 'pixtral', 'voxtral',\n ],\n efforts: false,\n input: ['text', 'image'],\n note: 'Mistral \u975E\u63A8\u7406\u7EBF\uFF082026-10 \u65B0\u589E\u6761\u76EE\uFF09\uFF1Alarge-2411/2512/latest\u3001medium-2505/2508\u3001small-2506\u3001nemo \u53CA devstral/ministral/codestral/pixtral/voxtral \u7B49\u4E13\u7528\u7EBF\u5747\u4E0D\u63A5\u53D7 effort \u53C2\u6570\uFF08\u52FF\u52FE\u601D\u8003\u6863\uFF09\u3002\u591A\u6570\u73B0\u5F79\u6B3E\u5E26\u89C6\u89C9\uFF08large-2411 \u4E3A\u7EAF\u6587\u672C\uFF09\u3002',\n },\n {\n id: 'qwen-vision',\n // The DashScope vision lines: -vl suffixes and QvQ. Normalization folds\n // 'qwen2.5-vl' to 'qwen2 5 vl', hence the spelled-out middle pattern.\n // Note the modern generations (3.8-max / 3.7-plus / 3.7-flash and the\n // 3.5-omni line) are multimodal too -- see the qwen-3-8 entry and the\n // plain qwen entry note.\n patterns: ['qwen-vl', 'qwen2-vl', 'qwen2-5-vl', 'qwen3-vl', 'qvq'],\n // DashScope takes NO reasoning_effort: thinking is the enable_thinking\n // boolean -- pi-ai's 'qwen' format dispatches exactly that switch.\n // Commercial Model Studio deployments default enable_thinking to TRUE\n // (help.aliyun.com) -- the on state, which is High here.\n efforts: { off: null, high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'qwen' },\n input: ['text', 'image'],\n contextWindow: 131_072,\n maxTokens: 8_192,\n note: '\u901A\u4E49\u89C6\u89C9\u7EBF\uFF08Qwen-VL/QvQ\uFF09\uFF1Aenable_thinking \u5F00\u5173\uFF08\u5F00=High\uFF09\uFF0C\u6536\u56FE\u3002qwen3-vl \u5BB9\u91CF\u66F4\u5927\uFF0C\u6309\u9700\u4E0A\u8C03\u3002',\n },\n {\n id: 'qwen-3-8',\n // The 3.8 generation moved from the bare enable_thinking switch to an\n // official reasoning_effort ladder: the Qwen3.8 README (\"Flexible\n // Thinking Control\"), the Qwen3.8-27B model card, the Qwen3.8-Flash-Next\n // card and the qwen.ai Flash-Next blog all document reasoning_effort\n // with xhigh as the DEFAULT (xhigh/medium/low), alongside the\n // per-request enable_thinking toggle (chat_template_kwargs on\n // open-weight serving). qwen3.8-max stays the current flagship (1M\n // context; Model Studio lists it under image/video understanding), so\n // the plain qwen entry's text-only declaration must not claim it.\n patterns: ['qwen3.8'],\n efforts: { off: null, low: 'low', medium: 'medium', xhigh: 'xhigh' },\n defaultEffort: 'xhigh',\n compat: { thinkingFormat: 'qwen', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n note: 'Qwen 3.8 \u7CFB\uFF1A\u5B98\u65B9 reasoning_effort \u6863\u4F4D XHigh(\u9ED8\u8BA4) / Medium / Low\uFF0Cthinking \u9ED8\u8BA4\u5F00\u3001\u53EF\u6309\u8BF7\u6C42\u5173\u95ED\uFF1B\u539F\u751F\u591A\u6A21\u6001\uFF08qwen3.8-max \u56FE\u50CF/\u89C6\u9891\u7406\u89E3\uFF0C\u89C6\u9891\u672A\u5165\u6838\u5FC3\u8BCD\u8868\uFF09\u30021M \u6863\u4E0A\u4E0B\u6587\u300227B \u4E0E Flash-Next \u5F00\u6E90\u6B3E\u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'qwen-3-8-27b',\n // Open-weight dense release (2026-08-14, HF Qwen/Qwen3.8-27B model\n // card): \"native vision-language model\", 262,144 context natively\n // \"extensible up to 1,000,000 tokens\", reasoning_effort xhigh (default)\n // / medium / low with per-request thinking disable. Longer than the\n // bare 'qwen3.8' pattern, so it wins for -27B ids.\n patterns: ['qwen3.8-27b'],\n efforts: { off: null, low: 'low', medium: 'medium', xhigh: 'xhigh' },\n defaultEffort: 'xhigh',\n compat: { thinkingFormat: 'qwen', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: 'Qwen3.8-27B\uFF08dense\uFF0C2026-08-14 \u5F00\u6E90\uFF09\uFF1A\u5B98\u65B9 reasoning_effort \u6863\u4F4D XHigh(\u9ED8\u8BA4) / Medium / Low\uFF0Cthinking \u9ED8\u8BA4\u5F00\u3001\u53EF\u6309\u8BF7\u6C42\u5173\uFF1B\u539F\u751F\u56FE\u50CF+\u89C6\u9891\u7406\u89E3\uFF08\u89C6\u9891\u672A\u5165\u6838\u5FC3\u8BCD\u8868\uFF09\u3002262,144 \u539F\u751F\u4E0A\u4E0B\u6587\u3001\u5B98\u65B9\u58F0\u660E\u53EF\u6269\u81F3 1M\u3002\u6765\u6E90\uFF1AHF Qwen/Qwen3.8-27B \u6A21\u578B\u5361\u3002',\n },\n {\n id: 'qwen-3-8-flash-next',\n // Open-weight experimental architecture preview (HF\n // Qwen/Qwen3.8-Flash-Next card + the qwen.ai blog): the\n // Qwen4-underpinning hybrid (QSA, n-gram embedding; 125B with 6B\n // activated), native vision encoder, 262,144 context natively\n // extensible to 1M. Thinking control identical to the 3.8 generation:\n // enable_thinking toggle plus reasoning_effort xhigh (default) /\n // medium / low. Longest pattern, so it wins for -flash-next ids.\n patterns: ['qwen3.8-flash-next'],\n efforts: { off: null, low: 'low', medium: 'medium', xhigh: 'xhigh' },\n defaultEffort: 'xhigh',\n compat: { thinkingFormat: 'qwen', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: 'Qwen3.8-Flash-Next\uFF08125B-A6B \u5B9E\u9A8C\u67B6\u6784\uFF0CQwen4 \u524D\u8EAB\uFF09\uFF1A\u5B98\u65B9 reasoning_effort \u6863\u4F4D XHigh(\u9ED8\u8BA4) / Medium / Low + enable_thinking \u5F00\u5173\uFF1B\u539F\u751F\u89C6\u89C9\uFF08Vision Encoder\uFF09\u3002262,144 \u539F\u751F\u4E0A\u4E0B\u6587\u3001\u53EF\u6269\u81F3 1M\u3002\u6765\u6E90\uFF1AHF \u6A21\u578B\u5361\u4E0E qwen.ai \u5B98\u65B9\u535A\u5BA2\u3002',\n },\n {\n id: 'qwen',\n patterns: ['qwen', 'qwq'],\n // DashScope takes NO reasoning_effort: thinking is the enable_thinking\n // boolean (plus thinking_budget) -- pi-ai's 'qwen' format dispatches\n // exactly that switch, so the ladder is honestly open/close with one\n // nominal thinking level. QwQ is think-always; clearing the off level\n // there is one click. Commercial DashScope defaults enable_thinking to\n // TRUE (open-weight serving defaults to false) -- the on state is High.\n efforts: { off: null, high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'qwen' },\n input: ['text'],\n contextWindow: 1_000_000,\n maxTokens: 65_536,\n note: '\u901A\u4E49\u5343\u95EE\uFF1Aenable_thinking \u5F00\u5173\uFF08\u65E0 effort \u6863\uFF09\uFF0C\u5F00=High\uFF1B\u73B0\u5F79\u65D7\u8230\u4E3A qwen3.8 \u7CFB\uFF081M \u6863\u4E0A\u4E0B\u6587\uFF0C\u89C1 qwen-3-8 \u6761\u76EE\uFF09\u30023.6/3.7 \u4EE3\u7684 Plus/Flash \u4EA6\u9ED8\u8BA4\u591A\u6A21\u6001\uFF08\u56FE\u7247/\u89C6\u9891\uFF09\uFF0C\u5982\u63A5\u5165\u8BF7\u6309\u9700\u52FE\u9009\u56FE\u7247\uFF1B\u89C6\u89C9\u7EBF\u89C1 qwen-vision \u6761\u76EE\u3002',\n },\n {\n id: 'glm-vision',\n // Zhipu's vision lines: glm-4v / glm-4.6v / glm-4.5v / glm-5v. Longer\n // than the plain 'glm' patterns, so they win for those ids.\n // 'glm-4-6v' (not 'glm-46v'): normalization folds 'glm-4.6v' to\n // 'glm 4 6v', so the pattern must carry the same inner separator; the\n // same fold gives 'glm-4.5v' -> 'glm 4 5v'.\n patterns: ['glm-4v', 'glm-4-6v', 'glm-4-5v', 'glm-5v'],\n efforts: { off: null, high: 'high' },\n // GLM-4.5V is forced-thinking and the 4.x line defaults to enabled\n // (docs.bigmodel.cn thinking page) -- the on state is High.\n defaultEffort: 'high',\n compat: { thinkingFormat: 'zai' },\n input: ['text', 'image'],\n contextWindow: 131_072,\n maxTokens: 32_768,\n note: '\u667A\u8C31\u89C6\u89C9\u7EBF\uFF08GLM-4V/4.5V/4.6V/5V\uFF09\uFF1Athinking \u5F00\u5173\uFF08\u5F00=High\uFF09\uFF0C\u6536\u56FE\u3002GLM-4.5V \u4E3A\u5F3A\u5236\u601D\u8003\uFF08\u4F20 disabled \u62A5\u9519\uFF0C\u8BF7\u624B\u52A8\u5220 Off \u6863\uFF09\u3002',\n },\n {\n id: 'glm-5-3-flash',\n // Official model page (docs.bigmodel.cn/cn/guide/models/vlm/glm-5.3-flash,\n // page dated 2026-08-28): input modalities \"\u89C6\u9891\u3001\u56FE\u50CF\u3001\u6587\u672C\u3001\u6587\u4EF6\", 1M\n // context / 128K max output, and \"thinking.type \u4EC5\u652F\u6301 enabled\" \u2014 forced\n // thinking, no off switch. \"\u6587\u672C\u53C2\u6570\u4E0E GLM-5.3 \u4FDD\u6301\u4E00\u81F4\" gives the flash\n // variant the 5.3 ladder (low/high/max). Native multimodal (320B), which\n // the text-only glm-5.3 entry must NOT claim \u2014 hence this separate entry;\n // the longer pattern wins over plain 'glm-5.3'.\n // 'glm-5.3-flashx' is the same model under a relay spelling (ofox lists\n // 'z-ai/glm-5.3-flashx' named 'GLM-5.3-FlashX'). It must be listed\n // explicitly: boundary matching rejects the bare 'glm 5 3 flash' needle\n // there because the next character is the alnum 'x', and the shorter\n // 'glm-5.3' would then claim the id as the text-only model.\n patterns: ['glm-5.3-flash', 'glm-5.3-flashx'],\n efforts: { low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'max',\n compat: { thinkingFormat: 'zai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: 'GLM-5.3-Flash\uFF08320B\uFF0C\u5B98\u65B9\u6587\u6863 vlm \u5206\u7C7B\uFF09\uFF1A\u5F3A\u5236\u601D\u8003\uFF08thinking.type \u4EC5 enabled\uFF0C\u4E0D\u652F\u6301\u5173\u95ED\uFF09\uFF0C\u6587\u672C\u53C2\u6570\u4E0E GLM-5.3 \u4E00\u81F4\u2014\u2014\u6863\u4F4D Low / High / Max\u3002\u8F93\u5165\u6A21\u6001\uFF1A\u89C6\u9891\u3001\u56FE\u50CF\u3001\u6587\u672C\u3001\u6587\u4EF6\uFF08\u89C6\u9891/\u6587\u4EF6\u672A\u5165\u6838\u5FC3\u8BCD\u8868\uFF0C\u56FE\u7247\u53EF\u52FE\uFF09\u3002\u5B98\u65B9 1M \u4E0A\u4E0B\u6587 / 128K \u6700\u5927\u8F93\u51FA\u3002\u6765\u6E90\uFF1Adocs.bigmodel.cn \u6A21\u578B\u9875\u3002',\n },\n {\n id: 'glm-5-3',\n patterns: ['glm-5.3'],\n // glm-5.3 accepts exactly max/high/low; anything else (including the\n // 5.2 ladder's minimal/none) errors, and thinking cannot be disabled.\n // The API reference names reasoning_effort's default as max.\n efforts: { low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'max',\n compat: { thinkingFormat: 'zai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: 'GLM-5.3 \u6863\u4F4D\uFF1ALow / High / Max\uFF08\u5F3A\u5236\u601D\u8003\uFF0C\u5176\u4F59\u503C\u62A5\u9519\uFF09\u3002\u5B98\u65B9\u5BB9\u91CF 1M / 128K\u3002',\n },\n {\n id: 'glm-5-2',\n patterns: ['glm-5.2'],\n // glm-5.2 takes the widest ladder in the wild: none/minimal/low/medium/\n // high/xhigh/max (default max). The zai format arms thinking:disabled\n // for off and sends the effort for the rest.\n efforts: { off: 'none', minimal: 'minimal', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' },\n defaultEffort: 'max',\n compat: { thinkingFormat: 'zai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n // Official capability page: none/minimal stop thinking, low/medium map\n // to high, xhigh maps to max -- all seven spellings are accepted.\n note: 'GLM-5.2 \u6863\u4F4D\uFF1ANone / Minimal / Low / Medium / High / XHigh / Max\uFF08\u5B98\u65B9\u6620\u5C04\uFF1ALow\u00B7Medium\u2192High\u3001XHigh\u2192Max\u3001None\u00B7Minimal=\u505C\u6B62\u601D\u8003\uFF09\u3002\u89C6\u89C9\u7EBF\u89C1 glm-vision \u6761\u76EE\u3002',\n },\n {\n id: 'glm',\n patterns: ['glm', 'zhipu', 'chatglm'],\n // GLM 4.x: thinking.type enabled/disabled only, no effort ladder --\n // the zai format sends exactly that switch (and no effort value,\n // because supportsReasoningEffort is not declared). GLM-4.5/4.6\n // default to enabled (hybrid reasoning: the model decides per\n // request) -- the on state is High.\n efforts: { off: null, high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'zai' },\n input: ['text'],\n note: 'GLM \u901A\u7528\uFF1Athinking \u5F00\u5173\uFF08\u65E0 effort \u6863\uFF09\uFF0C\u5F00=High\uFF1Beffort \u9636\u68AF\u4EC5 GLM-5.2+ \u652F\u6301\uFF08\u89C1\u4E0A\u4E24\u6761\u76EE\uFF09\u3002\u6CE8\u610F GLM-4.7/GLM-4.5V \u4E3A\u5F3A\u5236\u601D\u8003\uFF0C\u4F20 disabled \u4F1A\u62A5\u9519\uFF08\u8BF7\u624B\u52A8\u5220 Off \u6863\uFF09\u3002\u89C6\u89C9\u7EBF\u89C1 glm-vision \u6761\u76EE\u3002',\n },\n {\n id: 'kimi-k3',\n patterns: ['kimi-k3'],\n // kimi-k3: top-level reasoning_effort low/high/max (default max),\n // always thinking -- the thinking object must not be sent at all.\n efforts: { low: 'low', high: 'high', max: 'max' },\n defaultEffort: 'max',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n note: 'Kimi K3 \u6863\u4F4D\uFF1ALow / High / Max(\u9ED8\u8BA4 Max)\uFF0C\u8D70\u9876\u5C42 reasoning_effort\uFF1B\u59CB\u7EC8\u63A8\u7406\u3001\u52FF\u4F20 thinking \u5BF9\u8C61\u3002\u539F\u751F\u89C6\u89C9\u7406\u89E3\uFF0C1M \u4E0A\u4E0B\u6587\uFF08\u6700\u5927\u8F93\u51FA\u5B98\u65B9\u672A\u5355\u72EC\u5217\uFF0C\u4E0D\u63D0\u4F9B\uFF09\u3002',\n },\n {\n id: 'kimi-k2-vision',\n // K2.5/K2.6 are multimodal thinking models with a toggleable\n // thinking.type switch (official use-thinking-models table); K2.5 was\n // re-verified as MULTIMODAL on 2026-08-24 (the old \"text-only\" note was\n // wrong). Longer patterns beat the plain 'kimi' stem below.\n patterns: ['kimi-k2.6', 'kimi-k2.5'],\n efforts: { off: null, high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek' },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: 'Kimi K2.5/K2.6 \u89C6\u89C9\u4EE3\uFF1Athinking.type \u5F00\u5173\uFF08\u9ED8\u8BA4\u5F00\u3001\u53EF\u5173\uFF09\uFF0C\u5F00=High\uFF1B\u5E26\u89C6\u89C9\uFF0C256K\u3002K2.7 Code \u59CB\u7EC8\u601D\u8003\uFF0C\u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'kimi-k27-code',\n // K2.7 Code (and its highspeed twin) ALWAYS think: thinking.type only\n // accepts \"enabled\", sending \"disabled\" errors -- so no Off level.\n patterns: ['kimi-k2.7'],\n efforts: { high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'deepseek' },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: 'Kimi K2.7 Code\uFF08\u542B\u9AD8\u901F\u7248\uFF09\uFF1A\u59CB\u7EC8\u601D\u8003\u2014\u2014thinking.type \u4EC5\u63A5\u53D7 enabled\uFF08\u4F20 disabled \u62A5\u9519\uFF09\uFF0C\u65E0 Off \u6863\uFF1B\u5E26\u89C6\u89C9\uFF0C256K\u3002',\n },\n {\n id: 'kimi-for-coding',\n // 2026-10 calibration NEW entry: pi-ai 1.2.0 keys kimi-for-coding on\n // anthropic-messages with a four-rung map (off omit-expressed, then\n // low/high/max) plus forceAdaptiveThinking -- Moonshot's coding\n // endpoint speaks the Anthropic shape, not the deepseek thinking.type\n // switch the K2 line uses. -highspeed twin has NO tlm (no effort\n // control); 1M in / 32,768 out, vision.\n patterns: ['kimi-for-coding'],\n efforts: { low: 'low', high: 'high', max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 32_768,\n note: 'Kimi for Coding\uFF1AMoonshot \u7F16\u7801\u4E13\u7EBF\u8D70 anthropic-messages \u534F\u8BAE\u3001\u81EA\u9002\u5E94\u601D\u8003\uFF0C\u6863\u4F4D Low / High / Max\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF1B\u5E26\u56FE\u8F93\u5165\uFF0C1M \u4E0A\u4E0B\u6587 / 32,768 \u8F93\u51FA\u3002\u9AD8\u901F\u7248\uFF08-highspeed\uFF09\u65E0 effort \u63A7\u4EF6\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF09\u3002',\n },\n {\n id: 'kimi-moonshot-v1-vision',\n // Legacy Moonshot V1 vision variants (official model list): plain\n // generation models with no thinking control, but they DO accept images\n // -- the generic 'moonshot' pattern must not declare text-only for them.\n patterns: ['moonshot-v1-8k-vision', 'moonshot-v1-32k-vision', 'moonshot-v1-128k-vision'],\n efforts: false,\n input: ['text', 'image'],\n note: 'Moonshot V1 \u89C6\u89C9\u65E7\u4EE3\uFF088k/32k/128k \u5404\u4E00\uFF09\uFF1A\u65E0\u601D\u8003\u63A7\u4EF6\uFF08\u751F\u6210\u6A21\u578B\uFF09\u3001\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF1B\u8BE5\u7EBF\u5DF2\u505C\u6B62\u5BF9\u65B0\u7528\u6237\u5F00\u653E\uFF082026-08-31 \u5168\u91CF\u4E0B\u7EBF\uFF0C\u7F51\u5173\u6B8B\u7559\u4ECD\u53EF\u547D\u4E2D\uFF09\u3002',\n },\n {\n id: 'kimi',\n // k2.5/2.6 use the DeepSeek-shaped thinking.type enabled/disabled\n // switch, which the 'deepseek' format dispatches; the old k2 preview\n // ids and moonshot-v1 names are retired upstream (2026-05/08) but live\n // on gateways. Effort ladders are not part of their contract.\n patterns: ['kimi', 'moonshot'],\n efforts: { off: null, high: 'high' },\n compat: { thinkingFormat: 'deepseek' },\n input: ['text'],\n contextWindow: 262_144,\n note: 'Kimi \u901A\u7528\uFF1Athinking \u5F00\u5173\uFF08\u65E0 effort \u6863\uFF09\uFF0C\u5F00=High\u3002k2 \u7CFB\u5217 2026-05-25 \u4E0B\u7EBF\u3001kimi-latest 2026-01-28 \u4E0B\u7EBF\u3001moonshot-v1 \u7CFB 2026-08-31 \u5168\u91CF\u4E0B\u7EBF\uFF08\u7F51\u5173\u6B8B\u7559\u4ECD\u53EF\u547D\u4E2D\uFF1Bmoonshot-v1 \u672C\u8EAB\u975E\u601D\u8003\u6A21\u578B\uFF09\u3002\u89C6\u89C9\u4EE3\u4E0E K2.7 Code \u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'hunyuan-hy3',\n // Open-weight contract (Tencent-Hunyuan/Hy3 README): reasoning_effort\n // travels inside chat_template_kwargs as \"no_think\" (default) / \"low\" /\n // \"high\"; the same README's spec table states a 256K context length.\n patterns: ['hy3'],\n efforts: { low: 'low', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 262_144,\n note: '\u6DF7\u5143 hy3\uFF1A\u5F00\u6E90\u5951\u7EA6\u7ECF chat_template_kwargs.reasoning_effort = no_think(\u9ED8\u8BA4)/low/high\uFF1B\u5B98\u65B9\u6A21\u578B\u5361 256K \u4E0A\u4E0B\u6587\uFF08295B MoE\uFF0C2026 \u5F00\u6E90\uFF09\u3002',\n },\n {\n id: 'hunyuan-hy4',\n // Open-weight contract (Tencent-Hunyuan/Hy4-preview README): reasoning\n // defaults to \"high\" (deep chain-of-thought) and is disabled with\n // extra_body={\"chat_template_kwargs\": {\"reasoning_effort\": \"no_think\"}}\n // \u2014 the same chat-template channel as hy3, with the default flipped to\n // high. The spec table states a 1M context length; the model is a\n // 770B-A49B MoE with Gated DSA attention. The README documents no levels\n // beyond high/no_think, so a low rung is NOT declared without evidence.\n patterns: ['hy4-preview', 'hy-4-preview'],\n efforts: { off: 'no_think', high: 'high' },\n defaultEffort: 'high',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n contextWindow: 1_000_000,\n note: '\u6DF7\u5143 Hy4 preview\uFF1A\u5B98\u65B9 README\u2014\u2014reasoning \u9ED8\u8BA4 high\uFF08\u6DF1\u5EA6\u601D\u8003\uFF09\uFF0C\u5173\u95ED\u7ECF chat_template_kwargs.reasoning_effort=no_think\uFF1B\u5B98\u65B9\u89C4\u683C\u8868 1M \u4E0A\u4E0B\u6587\uFF08770B-A49B MoE\uFF0CGated DSA\uFF09\u3002low \u6863\u5B98\u65B9\u672A\u5217\uFF0C\u5982\u6709\u8BF7\u624B\u8C03\uFF1B\u89C6\u89C9\u672A\u58F0\u660E\uFF0C\u6309\u9700\u624B\u52FE\u3002\u6765\u6E90\uFF1ATencent-Hunyuan/Hy4-preview \u5B98\u65B9 README\u3002',\n },\n {\n id: 'step-5-preview',\n // StepFun's official model is 'step-5-preview' (there is no bare\n // 'step-5'), carrying the same three-step reasoning_effort ladder as the\n // 3.x line with no way to close thinking -- hence no `off`. The official\n // page calls medium the \"default recommendation\". 1M context, 64K max\n // output, native image + video input.\n patterns: ['step-5'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_000_000,\n maxTokens: 65_536,\n note: '\u9636\u8DC3 Step-5-Preview\uFF08\u5B98\u65B9 id \u5373 step-5-preview\uFF0C\u65E0\u88F8 step-5\uFF1Bpattern \u53D6\u5BB6\u65CF\u4E3B\u5E72\u4EE5\u517C\u5BB9\u7F51\u5173\u5199\u6CD5\uFF09\uFF1A\u6863\u4F4D Low / Medium(\u5B98\u65B9\u6807\"\u9ED8\u8BA4\u63A8\u8350\") / High\uFF0C\u601D\u8003\u4E0D\u53EF\u5173\u95ED\uFF1B\u539F\u751F\u56FE\u7247 + \u89C6\u9891\u8F93\u5165\uFF1B1M \u4E0A\u4E0B\u6587\u300164K \u6700\u5927\u8F93\u51FA\uFF08\u5B98\u65B9\u53E6\u6CE8 max_tokens \u9ED8\u8BA4 INF\u3001\u4E0E 64K \u4E0A\u9650\u5E76\u5B58\uFF0C\u4EE5\u7AEF\u70B9\u5B9E\u6D4B\u4E3A\u51C6\uFF09\u3002',\n },\n {\n id: 'step-3-7',\n // StepFun step-3.7 is the vision-capable generation; 3.5 stayed\n // text-only on the official serving plan.\n patterns: ['step-3.7', 'step-3.6'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 262_144,\n note: '\u9636\u8DC3 Step-3.6/3.7 \u6863\u4F4D\uFF1ALow / Medium(\u9ED8\u8BA4\u63A8\u8350) / High\uFF0C\u539F\u751F\u56FE\u7247+\u89C6\u9891\u7406\u89E3\u3002\u4E0A\u4E0B\u6587\u4E3A\u8F93\u5165+\u8F93\u51FA\u603B\u548C\u4E0A\u9650\u3002',\n },\n {\n id: 'step-3-5',\n // step-3.5-flash (official listing): only low/high, text-only.\n patterns: ['step-3.5'],\n efforts: { low: 'low', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 262_144,\n note: '\u9636\u8DC3 Step-3.5 Flash \u6863\u4F4D\uFF1ALow / High\uFF08\u7EAF\u6587\u672C\u63A8\u7406\u65D7\u8230\uFF09\u3002\u4E0A\u4E0B\u6587\u4E3A\u8F93\u5165+\u8F93\u51FA\u603B\u548C\u4E0A\u9650\u3002',\n },\n {\n id: 'step',\n // StepFun step-3.x: reasoning_effort low/medium/high (default medium);\n // thinking cannot be turned off, only tuned.\n patterns: ['step-3', 'step-2'],\n efforts: { low: 'low', medium: 'medium', high: 'high' },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n note: '\u9636\u8DC3 Step \u6863\u4F4D\uFF1ALow / Medium / High\uFF08\u9ED8\u8BA4 Medium\uFF0C\u4E0D\u53EF\u5173\u95ED\uFF09\u30023.6/3.7 \u89C6\u89C9\u4EE3\u89C1\u5355\u72EC\u6761\u76EE\u3002',\n },\n {\n id: 'doubao',\n // Volcengine Ark: officially documented is the thinking.type\n // enabled/disabled/auto switch; the reasoning_effort ladder on\n // seed-2.x has community evidence (chatbox/compshare) but no first-\n // party doc yet -- kept as the conventional ladder, verify per gateway.\n // 'doubao' already covers every doubao-* spelling; the bare 'seed' token\n // (boundary-checked) catches seed-first ids some gateways serve. The\n // seed generations are vision-capable; doubao-1.5-pro stays text-only.\n patterns: ['doubao', 'seed'],\n efforts: { off: null, low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n note: '\u8C46\u5305\u6863\u4F4D\uFF1AOff / Low / Medium / High\u2014\u2014effort \u9636\u68AF\u4ECD\u662F\u793E\u533A\u8BC1\u636E\u3001\u5B98\u65B9 Ark \u6587\u6863\u660E\u5217\u7684\u4E3A thinking.type \u5F00\u5173\uFF082026-08-24 \u590D\u6838\u4ECD\u672A\u89C1\u5230 effort \u5B98\u65B9\u660E\u6587\uFF09\u3002seed \u4EE3\u6536\u56FE\uFF081.5-pro \u4F8B\u5916\uFF09\u3002',\n },\n {\n id: 'minimax-m2',\n // 2026-10 calibration NEW entry: pi-ai 1.2.0 keys MiniMax-M2.5 (and the\n // M2 line) with NO thinkingLevelMap and supportsReasoningEffort:false\n // on the anthropic-messages protocol -- unlike M3 below, the M2\n // generation predates the thinking parameter entirely. `false` keeps\n // auto-adapt from handing it the M3 declaration. Text-only;\n // 204,800 in / 131,072 out.\n patterns: ['minimax-m2'],\n efforts: false,\n input: ['text'],\n contextWindow: 204_800,\n maxTokens: 131_072,\n note: 'MiniMax-M2 / M2.5\uFF08\u542B -highspeed\uFF09\uFF1A\u65E0\u601D\u8003\u63A7\u4EF6\u3001\u65E0 effort \u53C2\u6570\uFF08M3 \u624D\u5F15\u5165 thinking \u53C2\u6570\uFF09\uFF0C\u7EAF\u6587\u672C\uFF0C204,800 / 131,072\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF1BM3 \u89C1\u4E0B\u6761\uFF09\u3002',\n },\n {\n id: 'minimax-m3',\n // Official M3 README: a thinking parameter with enabled / adaptive /\n // disabled -- NO reasoning_effort ladder. That is exactly the\n // deepseek-shaped toggle, so the kimi-style declaration fits; \"adaptive\"\n // is not expressible in the level vocabulary and defaults apply.\n // 2026-10 calibration adds the catalog's 512,000 output cap.\n patterns: ['minimax-m3'],\n efforts: { off: null, high: 'high' },\n compat: { thinkingFormat: 'deepseek' },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 512_000,\n note: 'MiniMax-M3\uFF1A\u5B98\u65B9 thinking \u53C2\u6570 enabled/adaptive/disabled\uFF08\u65E0 effort \u6863\uFF09\uFF0C\u5F00=High\u3001\u5173=disabled\uFF1B\u539F\u751F\u591A\u6A21\u6001\uFF08\u56FE/\u89C6\u9891\uFF0C\u6838\u5FC3\u8BCD\u8868\u4EC5\u542B\u56FE\uFF09\uFF0C1M \u4E0A\u4E0B\u6587 / 512,000 \u8F93\u51FA\uFF082026-10 \u6821\u51C6\u8865\u5BB9\u91CF\uFF09\u3002',\n },\n {\n id: 'mimo-v2-6',\n // Xiaomi MiMo v2.6 (and the v2.5 generation it supersedes) takes a required\n // thinking.type toggle (enabled/disabled, default enabled) plus a required\n // reasoning.effort. The official page lists the accepted effort values as\n // none/minimal/low/medium/high/xhigh/max/ultra and normalizes minimal to\n // low and xhigh/max/ultra to high -- but says outright that reasoning\n // strength is not differentiated yet, so the ladder below is what the\n // endpoint ACCEPTS, not a set of levels that behave differently today.\n // xhigh/max are deliberately absent: the endpoint folds them into high.\n // One entry covers both generations: the same models are documented under\n // one contract, and the family's only text-only member (v2.5-pro) keys its\n // own entry with a strictly longer pattern.\n patterns: ['mimo-v2.6', 'mimo-v2.5'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: '\u5C0F\u7C73 MiMo v2.6 \u7CFB\u5217\uFF08mimo-v2.6-pro / -flash / -pro-ultraspeed\uFF1B1M \u4E0A\u4E0B\u6587 / 128K \u6700\u5927\u8F93\u51FA\u3001\u539F\u751F\u5168\u6A21\u6001\uFF09\u4E0E\u5176\u524D\u4EE3 mimo-v2.5\u3002\u5B98\u65B9\u6587\u6863\uFF1Athinking.type\uFF08enabled/disabled\uFF0C\u9ED8\u8BA4 enabled\uFF09+ reasoning.effort\uFF08none \u5173\u95ED\uFF1B\u5176\u4F59\u5408\u6CD5\u503C\u5747\u5F00\u542F\uFF0C\u4E14**\u73B0\u9636\u6BB5\u6682\u672A\u533A\u5206\u63A8\u7406\u5F3A\u5EA6**\u2014\u2014minimal \u5F52\u4E00\u4E3A low\u3001xhigh/max/ultra \u5F52\u4E00\u4E3A high\uFF09\uFF0C\u56E0\u6B64\u8FD9\u91CC\u58F0\u660E\u7684\u662F\u7AEF\u70B9**\u63A5\u53D7**\u7684\u6863\u4F4D Off / Low / Medium / High\uFF08xhigh\u3001max \u4E0D\u58F0\u660E\uFF0C\u7AEF\u70B9\u53EA\u4F1A\u6298\u53E0\u4E3A high\uFF09\u3002\u601D\u8003\u6A21\u5F0F\u4E0B temperature / top_p \u4E0D\u53EF\u81EA\u5B9A\u4E49\uFF08\u5F3A\u5236 1.0 / 0.95\uFF09\uFF1B\u5E26\u5DE5\u5177\u8C03\u7528\u7684\u5386\u53F2\u8F6E\u5FC5\u987B\u5B8C\u6574\u56DE\u4F20 reasoning_content\uFF0C\u5426\u5219 400\u3002mimo-v2.5 \u4E0E v2.5-pro \u5B98\u65B9\u5B9A\u4E8E 2026-10-21 \u4E0B\u7EBF\u3002',\n },\n {\n id: 'mimo-v2-5-pro',\n // The v2.5 flagship is the family's only text-only member -- the official\n // capability table lists no multimodal understanding for it (models.dev\n // agrees, attachment=false), while every v2.6 model and mimo-v2.5 do.\n // Strictly longer pattern than the family entry's 'mimo-v2.5', so the\n // longest-hit rule routes it here.\n patterns: ['mimo-v2.5-pro'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: '\u5C0F\u7C73 MiMo v2.5-Pro\uFF1A\u8BE5\u5BB6\u65CF\u552F\u4E00\u7684**\u7EAF\u6587\u672C**\u6210\u5458\uFF08\u5B98\u65B9\u80FD\u529B\u8868\u672A\u5217\u5168\u6A21\u6001\u7406\u89E3\uFF09\uFF0C1M \u4E0A\u4E0B\u6587 / 128K \u6700\u5927\u8F93\u51FA\uFF0C\u63A8\u7406\u5951\u7EA6\u4E0E v2.6 \u7CFB\u5217\u76F8\u540C\uFF08thinking.type + reasoning.effort\uFF0Cnone \u5173\u95ED\u3001\u5176\u4F59\u6863\u4F4D\u6682\u4E0D\u533A\u5206\u5F3A\u5EA6\uFF09\u3002\u5B98\u65B9\u5B9A\u4E8E 2026-10-21 \u4E0B\u7EBF\u3002',\n },\n {\n id: 'baidu-ernie',\n // Baidu Qianfan's OpenAI-compatible surface accepts no reasoning_effort\n // parameter (the v2 API parameter tables carry none); thinking is a\n // per-variant property: the -Thinking / ERNIE 5.0-Thinking-* family is\n // always-on thinking, the plain ERNIE 4.5/5.0/5.1 generations are not\n // thinking models at all. The official pricing page (2026-08) lists\n // ERNIE 5.1 / 5.0 / 5.0-Thinking-Preview|Latest|Exp / 4.5-Turbo(-VL).\n patterns: ['ernie'],\n efforts: false,\n input: ['text'],\n contextWindow: 131_072,\n note: '\u767E\u5EA6\u5343\u5E06 ERNIE \u7CFB\uFF1A\u5B98\u65B9 OpenAI \u517C\u5BB9\u63A5\u53E3\u65E0 reasoning_effort \u53C2\u6570\u2014\u2014\u601D\u8003\u7531\u6A21\u578B\u53D8\u4F53\u51B3\u5B9A\uFF08-Thinking \u7CFB\u5217\u59CB\u7EC8\u601D\u8003\u3001\u666E\u901A\u7CFB\u5217\u4E0D\u601D\u8003\uFF09\uFF0C\u52FF\u52FE\u601D\u8003\u6863\u3002ERNIE 4.5 Turbo VL \u652F\u6301\u56FE\u7247\uFF0C\u6309\u9700\u624B\u52FE\uFF1B\u53C2\u8003\u5BB9\u91CF\u53D6 Turbo 128K \u6863\u3002',\n },\n {\n id: 'fireworks-ember',\n // 2026-10 calibration NEW entry: Fireworks' ember-1 keys on\n // anthropic-messages in pi-ai 1.2.0 with a five-rung map (off spelled\n // 'none') plus forceAdaptiveThinking/allowEmptySignature -- a relay\n // model that genuinely dispatches output_config.effort. Vision;\n // 1,048,576 in / 131,072 out.\n patterns: ['ember-1'],\n efforts: { off: 'none', low: 'low', medium: 'medium', high: 'high', max: 'max' },\n compat: { supportsReasoningEffort: true },\n anthropicAdaptive: true,\n input: ['text', 'image'],\n contextWindow: 1_048_576,\n maxTokens: 131_072,\n note: 'Fireworks ember-1\uFF1Aanthropic-messages \u534F\u8BAE\u81EA\u9002\u5E94\u601D\u8003\uFF0C\u6863\u4F4D None(\u5173) / Low / Medium / High / Max\uFF08off \u663E\u5F0F none \u62FC\u5199\uFF09\uFF1B\u5E26\u56FE\u8F93\u5165\uFF0C1M \u4E0A\u4E0B\u6587 / 131,072 \u8F93\u51FA\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF09\u3002',\n },\n {\n id: 'thinkingmachines-inkling',\n // 2026-10 calibration NEW entry: pi-ai 1.2.0 keys inkling (Thinking\n // Machines) with the FULL seven-rung ladder incl. explicit max, vision,\n // 524,288 in / 131,072 out. On together.ai the relay exposes\n // supportsReasoningEffort:false -- the ladder below still keys the\n // model name first; relays that forward it accept the rungs.\n patterns: ['inkling'],\n efforts: {\n off: 'none', minimal: 'minimal', low: 'low', medium: 'medium',\n high: 'high', xhigh: 'xhigh', max: 'max',\n },\n defaultEffort: 'medium',\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text', 'image'],\n contextWindow: 524_288,\n maxTokens: 131_072,\n note: 'Thinking Machines Inkling\uFF1A\u5168\u6863 Minimal / Low / Medium(\u9ED8\u8BA4) / High / XHigh / Max\uFF0Coff \u663E\u5F0F none\uFF1B\u5E26\u56FE\u8F93\u5165\uFF0C512K \u4E0A\u4E0B\u6587 / 131,072 \u8F93\u51FA\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF1Btogether \u4E2D\u7EE7\u4FA7 effort \u53C2\u6570\u672A\u5F00\u653E\uFF0C\u9700\u652F\u6301\u65B9\u8F6C\u53D1\uFF09\u3002',\n },\n {\n id: 'antling-ring',\n // 2026-10 calibration NEW entry: Ant Ling's Ring-2.6-1T takes a\n // two-rung map (high/xhigh) with off omit-expressed; Ling-2.6(-flash)\n // is r=false (non-reasoning) and keys the second entry. 262,144 in /\n // 65,536 out per pi-ai 1.2.0.\n patterns: ['ring-2.6'],\n efforts: { high: 'high', xhigh: 'xhigh' },\n compat: { thinkingFormat: 'openai', supportsReasoningEffort: true },\n input: ['text'],\n contextWindow: 262_144,\n maxTokens: 65_536,\n note: '\u8682\u8681 Ling Ring-2.6-1T\uFF1A\u6863\u4F4D High / XHigh\uFF08off \u4EE5\u7701\u7565\u8868\u8FBE\uFF09\uFF1B262,144 / 65,536\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF09\u3002',\n },\n {\n id: 'antling-ling',\n // 2026-10 calibration NEW entry: Ling-2.6-1T / Ling-2.6-flash are\n // non-reasoning (r=false, no tlm in pi-ai 1.2.0) -- declared false so\n // auto-adapt does not hand them the Ring ladder.\n patterns: ['ling-2.6'],\n efforts: false,\n input: ['text'],\n note: '\u8682\u8681 Ling-2.6\uFF08\u542B -flash\uFF09\uFF1A\u975E\u601D\u8003\u6A21\u578B\uFF0C\u65E0 effort \u63A7\u4EF6\uFF082026-10 \u6821\u51C6\u65B0\u589E\uFF1BRing-2.6 \u601D\u8003\u7EBF\u89C1\u4E0A\u6761\uFF09\u3002',\n },\n]\n\n/**\n * The generic OpenAI-compatible ladder -- the single source for every\n * OpenAI-shaped protocol row below and the fallback when nothing matches.\n */\nexport const GENERIC_OPENAI_EFFORTS: ReasoningEfforts = {\n off: null,\n low: 'low',\n medium: 'medium',\n high: 'high',\n}\n\n/**\n * Level sets keyed by pi-ai's REAL wire protocols -- the only values a\n * route's 'api' may take are 'openai-completions' | 'openai-responses' |\n * 'anthropic-messages' (llm-pi-ai provider.ts PROTOCOLS) -- plus the\n * 'deepseek' URL dialect for routes that name no api but point at DeepSeek's\n * own endpoint, which takes its native off/high/max ladder.\n *\n * 'off: null' is only offered where a no-thinking mode is plausible; the\n * conservative choice elsewhere is to omit it so the picker never promises an\n * Off the endpoint would reject. Exported for the vocabulary grid tests that\n * pin these ladders against pi-ai's resolution rules.\n */\nexport const PROTOCOL_INFERENCE: Readonly<Record<string, ReasoningEfforts>> = {\n 'openai-completions': GENERIC_OPENAI_EFFORTS,\n 'openai-responses': GENERIC_OPENAI_EFFORTS,\n 'anthropic-messages': GENERIC_OPENAI_EFFORTS,\n // The live V4 contract: low/high/max (+ thinking toggle for off, spelled\n // 'none' so an off selection also maps to the official Responses-API value\n // reasoning.effort: none).\n deepseek: { off: 'none', low: 'low', high: 'high', max: 'max' },\n}\n\n/** A best-effort generic declaration when even the protocol is unknown. */\nconst GENERIC_FALLBACK: ReasoningEfforts = { low: 'low', medium: 'medium', high: 'high' }\n\n/** Normalize one route fact for matching/inference. */\nfunction normalize(value: string | undefined): string {\n return (value ?? '').toLowerCase().trim()\n}\n\n/** Whether a character is a lowercase letter or digit (word-boundary test). */\nfunction isAlnum(ch: string | undefined): boolean {\n return ch !== undefined && /[a-z0-9]/.test(ch)\n}\n\n/**\n * Lowercase and collapse every non-alphanumeric run to one space, so id /\n * display-name / pattern separators ('-', '_', '.', spaces) compare equal:\n * pattern 'deepseek-v3' matches display name \"DeepSeek V3\".\n */\nfunction normalizeLoose(value: string): string {\n return value.toLowerCase().trim().replace(/[^a-z0-9]+/g, ' ')\n}\n\n/**\n * Whether the occurrence of a pattern at index 'at' sits on a word boundary\n * in the haystack: neither neighbor may be a letter/digit. Keeps short family\n * tokens from false-hitting ('o1' must hit 'o1 mini' but not 'ko1 pro';\n * 'seed' hits 'doubao seed 1 6' but not 'seedling').\n */\nfunction onBoundary(haystack: string, at: number, length: number): boolean {\n const before = at === 0 ? undefined : haystack[at - 1]\n const after = haystack[at + length]\n return !isAlnum(before) && !isAlnum(after)\n}\n\n/** Match the knowledge base: first match wins, longest boundary hit wins. */\nexport function matchKnowledgeBase(modelId: string, displayName?: string): KnowledgeEntry | undefined {\n const haystack = normalizeLoose(modelId) + ' ' + normalizeLoose(displayName ?? '')\n let best: { entry: KnowledgeEntry; length: number } | undefined\n for (const entry of KNOWLEDGE_BASE) {\n for (const pattern of entry.patterns) {\n const needle = normalizeLoose(pattern)\n let at = haystack.indexOf(needle)\n while (at >= 0) {\n if (onBoundary(haystack, at, needle.length)) {\n if (best === undefined || needle.length > best.length) {\n best = { entry, length: needle.length }\n }\n break\n }\n at = haystack.indexOf(needle, at + 1)\n }\n }\n }\n return best?.entry\n}\n\n/**\n * Infer which PROTOCOL_INFERENCE key applies to a route. A configured 'api'\n * is already a pi-ai protocol name and wins as-is; otherwise the endpoint's\n * HOST names the dialect -- matched on the registrable domain so an aggregator\n * path like https://gw.example.com/deepseek/v1 stays generic -- and anything\n * unrecognized resolves to the OpenAI-compatible ladder (the overwhelming\n * majority of gateways).\n */\nconst NATIVE_DIALECT_DOMAINS: Readonly<Record<string, string>> = {\n // api.deepseek.com is the official endpoint (api-docs.deepseek.com). The\n // 'deepseek.ai' form was dropped: it resolves to a Vercel-hosted site\n // (76.76.21.21), not DeepSeek infrastructure, so nothing warrants assuming\n // the native dialect for it.\n 'deepseek.com': 'deepseek',\n 'anthropic.com': 'anthropic-messages',\n}\n\nexport function inferProtocol(route: RouteFacts): string {\n const api = normalize(route.api)\n if (api.length > 0) return api\n const baseURL = route.baseURL\n if (baseURL !== undefined && baseURL.length > 0) {\n try {\n const host = new URL(baseURL).hostname.toLowerCase()\n const parts = host.split('.')\n if (parts.length >= 2) {\n const dialect = NATIVE_DIALECT_DOMAINS[parts.slice(-2).join('.')]\n if (dialect !== undefined) return dialect\n }\n } catch {\n // Malformed URL: fall through to the generic ladder.\n }\n }\n // No route-level 'gemini' guessing: the harness adapter's registry offers\n // only the three OpenAI/Anthropic wires, so a Gemini endpoint at route level\n // still speaks the OpenAI-compatible dialect. Native Gemini\n // ('google-generative-ai') is reached only through a per-key protocol pin\n // (see key-refs.ts), which needs no route inference.\n return 'openai-completions'\n}\n\n/**\n * The one wire protocol whose compat gate offers thinkingFormat /\n * supportsReasoningEffort (llm-pi-ai COMPLETIONS_COMPAT_GATE). pi-ai refuses\n * a model-level compat field its resolved protocol does not take\n * (assertServiceable throws at the write), so compat suggestions are gated to\n * this protocol only -- with one exception: the anthropic-messages gate\n * offers forceAdaptiveThinking, which is what makes declared efforts reach\n * the wire as output_config.effort (see {@link KnowledgeEntry.anthropicAdaptive}).\n */\nconst COMPAT_CAPABLE_PROTOCOL = 'openai-completions'\nconst ANTHROPIC_PROTOCOL = 'anthropic-messages'\n\n/** Whether a baseURL names a self-hosted endpoint (loopback, private LAN, .local, custom port). */\nexport function isSelfHostedEndpoint(baseURL: string | undefined): boolean {\n if (baseURL === undefined || baseURL.length === 0) return false\n let host = ''\n try {\n host = new URL(baseURL).hostname.toLowerCase()\n } catch {\n return false\n }\n if (host === 'localhost' || host === '::1' || host.endsWith('.local') || host.endsWith('.internal')) return true\n if (/^(127\\.|10\\.|192\\.168\\.)/.test(host)) return true\n if (/^172\\.(1[6-9]|2[0-9]|3[01])\\./.test(host)) return true\n return host.includes(':')\n}\n\n/**\n * Drop catalog-withheld keys pi-ai never accepts from a profile (defensive).\n *\n * openai-responses now falls through to `undefined`: the plugin suggests no\n * compat field on that gate since its max_output_tokens control was retired, so\n * such a profile keeps exactly what it already stores.\n */\nexport function sanitizeCompatForProtocol(compat: CompatSuggestion, api: string): CompatSuggestion | undefined {\n const norm = normalize(api)\n const copy: Record<string, unknown> = { ...compat }\n delete copy['supportsMidConvoEffort']\n delete copy['allowedFallbackModels']\n if (norm === ANTHROPIC_PROTOCOL) {\n for (const key of ['thinkingFormat', 'supportsReasoningEffort', 'thinkingTokenBudgetField', 'supportsThinkingTokenBudget', 'vllmPriority'] as const) delete copy[key]\n if (copy['forceAdaptiveThinking'] === undefined) return undefined\n return { forceAdaptiveThinking: copy['forceAdaptiveThinking'] as boolean }\n }\n if (norm !== COMPAT_CAPABLE_PROTOCOL) return undefined\n delete copy['forceAdaptiveThinking']\n return Object.keys(copy).length === 0 ? undefined : (copy as CompatSuggestion)\n}\n\n/** Gate a compat block against the route's real protocol. */\nfunction compatForRoute(entry: KnowledgeEntry, route: RouteFacts): CompatSuggestion | undefined {\n const api = normalize(route.api)\n if (api === COMPAT_CAPABLE_PROTOCOL) {\n let compat = entry.compat\n if (compat !== undefined) compat = sanitizeCompatForProtocol(compat, api) ?? undefined\n if (compat === undefined && !isSelfHostedEndpoint(route.baseURL)) return undefined\n if (compat === undefined) return { thinkingTokenBudgetField: 'thinking_token_budget' }\n if (compat.thinkingTokenBudgetField === undefined && compat.supportsThinkingTokenBudget !== true && isSelfHostedEndpoint(route.baseURL)) {\n return { ...compat, thinkingTokenBudgetField: 'thinking_token_budget' }\n }\n return compat\n }\n if (api === ANTHROPIC_PROTOCOL && entry.anthropicAdaptive === true) {\n return { forceAdaptiveThinking: true }\n }\n return undefined\n}\n\n/**\n * Official endpoint roots where pi-ai may send role:developer, so no pin is\n * needed. Matching is a DNS-suffix match, so multi-level roots (e.g.\n * openai.azure.com) work while a relay merely hosted on the same cloud\n * (e.g. *.cloudapp.azure.com) still counts as self-hosted.\n *\n * Deliberately fail-safe: hosts outside this set get the pin. `system` is\n * accepted everywhere, `developer` is not, so an unknown host keeps the\n * universally accepted role -- the pin is harmless on official endpoints\n * too. Only add a root after verifying its endpoints accept\n * role:developer (vendor docs or a wire capture); when in doubt, leave it\n * out. The pi-ai-parity entries change no bytes (pi-ai already detects\n * those hosts as nonstandard, i.e. supportsDeveloperRole false); they are\n * listed so the two detectors cannot drift apart silently.\n */\nconst OFFICIAL_RELAY_DOMAINS: readonly string[] = [\n // First-party OpenAI-compatible endpoints (developer accepted).\n 'openai.com',\n 'openai.azure.com',\n 'deepseek.com',\n 'openrouter.ai',\n 'z.ai',\n 'bigmodel.cn',\n 'moonshot.ai',\n 'moonshot.cn',\n 'aliyuncs.com',\n 'anthropic.com',\n 'x.ai',\n 'together.ai',\n 'together.xyz',\n 'nvidia.com',\n 'cerebras.ai',\n 'cloudflare.com',\n // pi-ai-parity: detected nonstandard upstream (pin would be a no-op).\n 'chutes.ai',\n 'opencode.ai',\n 'ant-ling.com',\n]\n\n/**\n * Whether a route is a self-hosted relay whose upstreams cannot be assumed\n * to accept role:developer: openai-completions protocol on a baseURL whose\n * host no official root claims. Absent or malformed URLs answer false --\n * with nothing to judge the host by, pi-ai's detection default stands.\n */\nexport function isSelfHostedRelay(route: RouteFacts): boolean {\n if (normalize(route.api) !== COMPAT_CAPABLE_PROTOCOL) return false\n const baseURL = route.baseURL\n if (baseURL === undefined || baseURL.length === 0) return false\n try {\n const host = new URL(baseURL).hostname.toLowerCase()\n if (!host.includes('.')) return false\n return !OFFICIAL_RELAY_DOMAINS.some((root) => host === root || host.endsWith('.' + root))\n } catch {\n return false\n }\n}\n\n/**\n * Pin the system role on self-hosted relays: merge\n * `supportsDeveloperRole: false` into a compat block that would otherwise\n * let pi-ai rewrite the system prompt to role:developer (issue #2 -- the\n * upstream answers \u89D2\u8272\u4FE1\u606F\u4E0D\u6B63\u786E). An explicitly declared value always\n * wins; non-reasoning suggestions (efforts === false) never carry compat.\n */\nfunction withRolePin(\n compat: CompatSuggestion | undefined,\n route: RouteFacts,\n reasons: boolean,\n): CompatSuggestion | undefined {\n if (compat === undefined || !reasons) return compat\n if (compat.supportsDeveloperRole !== undefined) return compat\n if (!isSelfHostedRelay(route)) return compat\n return { ...compat, supportsDeveloperRole: false }\n}\n\n/** Conservative ladder offered when the endpoint confirms reasoning but nothing names the levels. */\nconst ENDPOINT_CONFIRMED_LADDER: ReasoningEfforts = { off: null, low: 'low', medium: 'medium', high: 'high' }\n\n/**\n * Name-heuristic modality tokens -- the last-resort tier (the practice\n * one-api/new-api bake into code): vision-flavored tokens that appear in\n * vendor ids often enough to suggest image input at LOW confidence. Boundary\n * matching keeps 'vl' from hitting 'eval' or 'svelte'.\n */\nconst VISION_NAME_TOKENS: readonly string[] = [\n 'vl',\n 'vision',\n 'omni',\n '4o',\n 'pixtral',\n 'internvl',\n]\n\n/** Lowest-confidence modality guess from the model id alone, or undefined. */\nexport function inferModalitiesFromName(modelId: string): InputModalities | undefined {\n const haystack = normalizeLoose(modelId)\n for (const token of VISION_NAME_TOKENS) {\n const needle = normalizeLoose(token)\n let at = haystack.indexOf(needle)\n while (at >= 0) {\n if (onBoundary(haystack, at, needle.length)) return ['text', 'image']\n at = haystack.indexOf(needle, at + 1)\n }\n }\n return undefined\n}\n\n/**\n * Intersect a raw listing disclosure with the core vocabulary. Returns\n * undefined when the listing never named a modality field OR named one whose\n * members all fall outside the core vocabulary (an audio-only declaration\n * must NOT read as \"text only\"). A present disclosure always yields at least\n * text-only when image is absent -- so an explicit text-only listing can\n * strip an image claim.\n */\nfunction declaredCoreInput(raw: readonly string[] | undefined): InputModalities | undefined {\n if (raw === undefined) return undefined\n const lowered = raw.map(value => value.toLowerCase())\n if (!lowered.some(value => (INPUT_MODALITIES as readonly string[]).includes(value))) return undefined\n return lowered.includes('image') ? ['text', 'image'] : ['text']\n}\n\n/**\n * Resolve the suggestion for one model on one route, fusing the available\n * signals by confidence:\n *\n * L1 endpoint listing signal (when supplied) -- answers \"does it reason at\n * all\" and, independently, \"what does it accept\": an explicit false\n * wins the effort ladder outright (suggest false, high); a modality\n * disclosure or a context length feeds those parts regardless;\n * L2 knowledge base -- the ONLY source of wire spellings and compat, plus\n * modality/capacity references when the endpoint stays silent;\n * L3 name heuristic -- a low-confidence image guess for vision-flavored\n * ids when both sources above are silent;\n * L4 protocol inference -- level-ladder skeleton when nothing better exists.\n *\n * @param modelId - the model id (or display name) to match.\n * @param route - route facts used when the knowledge base misses; its\n * displayName participates in knowledge-base matching.\n * @param endpoint - optional raw-listing facts for this model (from the\n * host's same-origin probe route); omit when the endpoint was not asked.\n * @returns a suggestion (always derivable -- protocol inference has a fallback).\n */\nexport function suggestEfforts(\n modelId: string,\n route: RouteFacts,\n endpoint?: EndpointFacts,\n): EffortSuggestion {\n const entry = matchKnowledgeBase(modelId, route.displayName)\n\n // ---- Modality + capacity parts (orthogonal to the effort ladder) ----\n let input: InputModalities | undefined\n let inputSource: InputSource | undefined\n let contextWindow: number | undefined\n let maxTokens: number | undefined\n\n if (entry?.input !== undefined) {\n input = entry.input\n inputSource = 'knowledge'\n }\n if (entry?.contextWindow !== undefined) contextWindow = entry.contextWindow\n if (entry?.maxTokens !== undefined) maxTokens = entry.maxTokens\n\n // An endpoint disclosure outranks the knowledge base; a disclosed context\n // length likewise replaces the reference value. Silence changes nothing.\n const listedInput = declaredCoreInput(endpoint?.input)\n if (listedInput !== undefined) {\n input = listedInput\n inputSource = 'endpoint'\n }\n if (endpoint?.contextLength !== undefined && Number.isFinite(endpoint.contextLength) && endpoint.contextLength > 0) {\n contextWindow = endpoint.contextLength\n }\n\n // L3: nothing named the modalities -- fall back to the name heuristic.\n if (input === undefined) {\n const guessed = inferModalitiesFromName(modelId)\n if (guessed !== undefined) {\n input = guessed\n inputSource = 'heuristic'\n }\n }\n\n const modalityParts = {\n ...(input === undefined ? {} : { input }),\n ...(inputSource === undefined ? {} : { inputSource }),\n ...(contextWindow === undefined ? {} : { contextWindow }),\n ...(maxTokens === undefined ? {} : { maxTokens }),\n }\n\n const endpointPart = endpoint === undefined\n ? {}\n : { endpoint: { reasoning: endpoint.reasoning, source: endpoint.source } }\n\n // L1: an explicit \"does not reason\" from the endpoint outranks everything.\n if (endpoint?.reasoning === false) {\n return {\n efforts: false,\n matched: false,\n source: 'endpoint:' + (endpoint.source ?? 'listing'),\n confidence: 'high',\n ...endpointPart,\n ...modalityParts,\n }\n }\n\n if (entry !== undefined) {\n const compat = withRolePin(compatForRoute(entry, route), route, entry.efforts !== false)\n return {\n efforts: entry.efforts,\n // The vendor default rides along only when the suggested ladder\n // actually carries it (a declaration may deliberately drop a level).\n ...(entry.efforts !== false\n && entry.defaultEffort !== undefined\n && entry.efforts[entry.defaultEffort] !== undefined\n ? { defaultEffort: entry.defaultEffort }\n : {}),\n ...(compat === undefined ? {} : { compat }),\n matched: true,\n entryId: entry.id,\n source: entry.id,\n // Knowledge base carries the wire values; an agreeing endpoint signal\n // only reinforces it. A DISAGREEING signal (endpoint says no reasoning)\n // was handled above; unknown changes nothing.\n confidence: 'high',\n ...endpointPart,\n ...modalityParts,\n }\n }\n\n // L2 missed: the ladder comes from protocol inference. An explicit endpoint\n // \"reasons\" upgrades confidence to medium -- support is confirmed, but the\n // level set and spellings are inferred, so the user should double-check.\n const protocol = inferProtocol(route)\n const efforts = PROTOCOL_INFERENCE[protocol] ?? GENERIC_FALLBACK\n const compatBase: CompatSuggestion | undefined = normalize(route.api) === COMPAT_CAPABLE_PROTOCOL\n ? { thinkingFormat: 'openai', supportsReasoningEffort: true }\n : undefined\n const compatWithBudget = compatBase !== undefined && isSelfHostedEndpoint(route.baseURL)\n ? { ...compatBase, thinkingTokenBudgetField: 'thinking_token_budget' as const }\n : compatBase\n const compat = withRolePin(compatWithBudget, route, true)\n if (endpoint?.reasoning === true) {\n return {\n efforts: { ...ENDPOINT_CONFIRMED_LADDER },\n ...(ENDPOINT_CONFIRMED_LADDER['medium'] !== undefined ? { defaultEffort: 'medium' as const } : {}),\n // compat was already gated to the protocol above; no second gate.\n ...(compat === undefined ? {} : { compat }),\n matched: false,\n source: 'endpoint:' + (endpoint.source ?? 'listing'),\n confidence: 'medium',\n ...endpointPart,\n ...modalityParts,\n }\n }\n return {\n efforts,\n // Inferred ladders default to medium (the convention codex/OpenAI set for\n // their own ladders) whenever the inferred set carries it.\n ...(efforts['medium'] !== undefined ? { defaultEffort: 'medium' as const } : {}),\n ...(compat === undefined ? {} : { compat }),\n matched: false,\n source: 'protocol:' + protocol,\n confidence: 'low',\n ...endpointPart,\n ...modalityParts,\n }\n}\n", "/**\n * Default-guard decision: which effort-less calls may take the vendor\n * default instead of the wire's off-equivalent (issue #2).\n *\n * Pi-ai always emits a thinking parameter for reasoning models, so an\n * effort-less call to a forced-thinking ladder (no `off` key) becomes\n * `thinking: {type: disabled}` / `enable_thinking: false` -- a guaranteed\n * 400 on upstreams that cannot switch thinking off. Rewriting exactly that\n * class into the ladder's vendor default produces bytes identical to the\n * user picking the level by hand, a request class that already works.\n *\n * Pure data logic (no harness imports): the host half feeds it the declared\n * ladder, the knowledge-base vendor default, and the route default, and\n * injects the returned level -- or nothing when it answers undefined.\n *\n * @module dsh-model-think-level/guard\n */\n\nimport type { ReasoningEfforts, ThinkingLevel } from './knowledge.js'\n\n/** Inputs to the guard decision, all optional except the declaration. */\nexport interface GuardInput {\n /** The model's declared ladder (`false` = non-reasoning). */\n declared: ReasoningEfforts | false | undefined\n /** The knowledge-base vendor default for the family, when one is known. */\n vendorDefault?: ThinkingLevel\n /** The route profile's configured reasoning default, when one is set. */\n profileDefault?: string\n /** The call's explicit effort, when the caller named one. */\n requested?: string\n}\n\n/**\n * The level to inject for an effort-less call, or undefined to pass through.\n * Refusals are silent and total: explicit selections, off-capable ladders,\n * undeclared/non-reasoning models, an explicit route default, and vendor\n * defaults outside the ladder all pass through untouched.\n */\nexport function resolveGuardEffort(input: GuardInput): string | undefined {\n if (input.requested !== undefined) return undefined\n const declared = input.declared\n if (declared === undefined || declared === false) return undefined\n if ('off' in declared) return undefined\n if (input.profileDefault !== undefined) return undefined\n const fallback = input.vendorDefault\n if (fallback === undefined || !(fallback in declared)) return undefined\n return fallback\n}\n", "/**\n * Shape guards and settings-dict readers shared by the host and browser\n * halves. Pure data logic only: esbuild inlines this module into both\n * bundles, so it must never import a harness package or touch DOM/node APIs.\n *\n * @module dsh-model-think-level/shared\n */\n\nimport type { RouteFacts } from './knowledge.js'\n\n/** Whether a value is a plain-ish object (not null, not an array). */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * Whether a settings refusal reads like \"this kernel does not know the newer\n * compat keys\". The host autofill and the browser write path each downgrade\n * once on this signal, so they must answer identically.\n */\nexport function looksLikeCompatRefusal(message: string): boolean {\n const msg = message.toLowerCase()\n return msg.includes('compat')\n || msg.includes('thinkingtokenbudget')\n || msg.includes('vllmpriority')\n || msg.includes('supportsmaxoutput')\n}\n\n/** The models array of one route in a providers dict, as records. */\nexport function modelsOf(providers: unknown, route: string): Record<string, unknown>[] {\n if (!isRecord(providers)) return []\n const profile = providers[route]\n if (!isRecord(profile) || !Array.isArray(profile['models'])) return []\n return profile['models'].filter(isRecord)\n}\n\n/** One provider profile's route facts, as suggestion inference reads them. */\nexport function routeFactsOf(providers: unknown, route: string): RouteFacts {\n if (!isRecord(providers)) return {}\n const profile = providers[route]\n if (!isRecord(profile)) return {}\n const api = typeof profile['api'] === 'string' ? profile['api'] : undefined\n const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'] : undefined\n const displayName = typeof profile['displayName'] === 'string' ? profile['displayName'] : undefined\n return { api, baseURL, displayName }\n}\n", "/**\n * Reading one provider's raw model listing.\n *\n * The same rules govern every place this plugin interrogates an endpoint: the\n * probe route (the browser half's auto-adapt), the key panel's discover op, and\n * the merged model discovery the provider card performs. The listing URL,\n * the request headers, the response ceiling, and the one parser for both reply\n * shapes therefore live here once, and mirror the harness's own discovery\n * (`@deepseek-ai/dsh-llm-pi-ai`) exactly \u2014 a listing this module reads is a\n * listing the official fetch reads, character for character.\n *\n * @module dsh-model-think-level/listing\n */\n\nimport { isRecord } from './shared.js'\n\n/** Stable API version required by Anthropic's model-listing endpoint. */\nexport const ANTHROPIC_VERSION = '2023-06-01'\n\n/** Largest model-list page accepted by Anthropic's public endpoint. */\nexport const ANTHROPIC_MODEL_LIMIT = 1000\n\n/** Largest model-list page requested of Gemini's native endpoint. */\nexport const GEMINI_MODEL_LIMIT = 1000\n\n/** Largest listing reply a probe accepts (the official discovery's bound). */\nexport const MAX_RESPONSE_BYTES = 4 * 1024 * 1024\n\n/** Protocols whose model listing this module can read (the harness discovery set, plus the plugin's pinned Gemini). */\nexport const LISTABLE_PROTOCOLS: ReadonlySet<string> = new Set([\n 'anthropic-messages',\n 'openai-completions',\n 'openai-responses',\n 'google-generative-ai',\n])\n\n/**\n * A URL safe to echo in responses: a baseURL may carry userinfo\n * (https://user:pass@host), and failure messages must never repeat it.\n */\nexport function displayUrl(raw: string): string {\n try {\n const url = new URL(raw)\n url.username = ''\n url.password = ''\n return url.toString()\n } catch {\n return raw\n }\n}\n\n/**\n * Probe-listing URL, mirroring the harness's own model discovery:\n * OpenAI-compatible protocols list at `{baseURL}/models`; Anthropic Messages\n * uses its native route at `{root}/v1/models?limit=1000`, where the root is the\n * base without trailing slashes and without one trailing `/v1` segment\n * (gateway documentation publishes both spellings of the same root). Gemini's\n * native protocol lists at `{base}/v1beta/models?pageSize=1000` on the same\n * version-qualified base its requests speak (see {@link geminiRequestBaseUrl}).\n */\nexport function probeListingUrl(baseURL: string, api: string): string {\n const base = baseURL.replace(/\\/+$/, '')\n if (api === 'google-generative-ai') return `${geminiRequestBaseUrl(base)}/models?pageSize=${String(GEMINI_MODEL_LIMIT)}`\n if (api !== 'anthropic-messages') return `${base}/models`\n const root = base.endsWith('/v1') ? base.slice(0, -3) : base\n return `${root}/v1/models?limit=${String(ANTHROPIC_MODEL_LIMIT)}`\n}\n\n/**\n * pi-ai's Anthropic SDK appends `/v1/messages` to the model base URL. Accept\n * either gateway spelling (`https://host` or `https://host/v1`) while keeping\n * the request endpoint at exactly `/v1/messages`.\n */\nexport function anthropicRequestBaseUrl(baseURL: string): string {\n const base = baseURL.replace(/\\/+$/, '')\n return base.endsWith('/v1') ? base.slice(0, -3) : base\n}\n\n/**\n * The base URL a Gemini-native request needs. pi-ai's Google client takes\n * `model.baseUrl` verbatim with `apiVersion: ''`, so the version segment must\n * already sit in the path; a bare origin is completed with `/v1beta` (the\n * official spelling), while a path the user spelled out is kept as the\n * gateway's own.\n */\nexport function geminiRequestBaseUrl(baseURL: string): string {\n const base = baseURL.replace(/\\/+$/, '')\n try {\n return new URL(base).pathname === '/' ? `${base}/v1beta` : base\n } catch {\n return base\n }\n}\n\n/**\n * Compose the raw-models probe request's headers, mirroring the discipline of\n * the harness's own model discovery: the provider\n * profile's configured request headers form the base (deployment-owned\n * credentials like `x-api-key` ride along), `accept` is always JSON, and a\n * resolved credential's Bearer overwrites a profile `authorization` \u2014 which\n * survives only when no credential resolves (a route may authenticate through\n * its configured headers alone). Anthropic Messages answers through\n * `x-api-key` plus a fixed `anthropic-version`, and its Bearer arm is never\n * used (a profile `authorization` survives untouched there, exactly as the\n * official discovery leaves it). Entries Fetch would refuse are dropped\n * rather than failing the probe. Harness attribution headers are deliberately\n * not sent \u2014 this is a same-origin diagnostic, not a harness request.\n * @param profileHeaders - the profile's raw `headers` dict (simply absent\n * on older documents).\n * @param apiKey - the resolved credential, when one resolved.\n * @param api - the profile's wire protocol.\n */\nexport function composeProbeHeaders(\n profileHeaders: unknown,\n apiKey: string | undefined,\n api: string,\n): Record<string, string> {\n const headers = new Headers()\n if (isRecord(profileHeaders)) {\n for (const [name, value] of Object.entries(profileHeaders)) {\n if (typeof value !== 'string') continue\n try {\n headers.set(name, value)\n } catch {\n // Unrepresentable as a Fetch header: skip the entry, keep probing.\n }\n }\n }\n headers.set('accept', 'application/json')\n if (api === 'anthropic-messages') {\n headers.set('anthropic-version', ANTHROPIC_VERSION)\n if (apiKey !== undefined) headers.set('x-api-key', apiKey)\n } else if (api === 'google-generative-ai') {\n // The native Google wire authenticates through its own header and no\n // Bearer, exactly as the official client signs; a profile `authorization`\n // survives untouched, the same courtesy the Anthropic arm extends.\n if (apiKey !== undefined) headers.set('x-goog-api-key', apiKey)\n } else if (apiKey !== undefined) {\n headers.set('authorization', `Bearer ${apiKey}`)\n }\n return Object.fromEntries(headers.entries())\n}\n\n/**\n * Read a listing reply body, refusing one that outgrows the ceiling (the same\n * bound the official discovery applies). A declared length is checked first\n * so an honest server is turned away without transferring anything; the\n * accumulated total is what actually enforces the bound.\n */\nexport async function readBounded(response: Response, url: string): Promise<string> {\n const declared = Number(response.headers.get('content-length') ?? Number.NaN)\n if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {\n await response.body?.cancel()\n throw new Error(`${displayUrl(url)} overshoots the ${MAX_RESPONSE_BYTES}-byte listing ceiling`)\n }\n if (response.body === null) return ''\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n total += value.byteLength\n if (total > MAX_RESPONSE_BYTES) throw new Error(`${displayUrl(url)} overshoots the ${MAX_RESPONSE_BYTES}-byte listing ceiling`)\n chunks.push(value)\n }\n } finally {\n await reader.cancel().catch(() => {\n // Cancel after a drained read, or after this function walked away from\n // an oversized one, is cleanup; the reply is already decided either way.\n })\n }\n const body = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return new TextDecoder().decode(body)\n}\n\n/**\n * Normalize a supported listing reply into one entry array, mirroring the\n * official parser: the standard `data` array takes precedence; the\n * enriched `models` map uses each property key as the endpoint-facing id\n * (the nested `id` only falls back for an empty key \u2014 gateways may put a\n * canonical identity there instead of the alias they accept on requests);\n * Gemini's native `models` ARRAY unwraps each `models/<id>` resource name into\n * the bare id the request path needs, keeps only entries a chat request can\n * address (`generateContent`), and reads the display label from\n * `displayName` (the raw `name` is the resource path, not a label). Only\n * object-valued entries are models, and entries without a usable id are\n * dropped. Returns undefined when the listing names none of these shapes.\n */\nexport function listingEntries(body: unknown): Record<string, unknown>[] | undefined {\n const listing = isRecord(body) ? body : {}\n const data = listing['data']\n if (Array.isArray(data)) return data.filter(isRecord)\n const models = listing['models']\n if (Array.isArray(models)) {\n const out: Record<string, unknown>[] = []\n for (const raw of models) {\n if (!isRecord(raw)) continue\n const resource = typeof raw['name'] === 'string' ? raw['name'] : ''\n const id = resource.startsWith('models/') ? resource.slice('models/'.length) : resource\n if (id.length === 0) continue\n const methods = raw['supportedGenerationMethods']\n // A methods list names what the model can serve; without one there is\n // nothing to exclude and the entry keeps the benefit of the doubt.\n if (Array.isArray(methods) && !methods.includes('generateContent')) continue\n const display = typeof raw['displayName'] === 'string' ? raw['displayName'] : undefined\n const entry: Record<string, unknown> = { ...raw, id }\n if (display !== undefined && display.trim().length > 0) entry['name'] = display\n else delete entry['name']\n out.push(entry)\n }\n return out\n }\n if (isRecord(models)) {\n return Object.entries(models)\n .filter(([, raw]) => isRecord(raw))\n .map(([key, raw]) => {\n // The map key is the endpoint-facing id, but an EMPTY key falls back\n // to the entry's own id exactly as the official parser's\n // label(key, entry.id) does \u2014 gateways may put the canonical identity\n // there instead of the alias they accept on requests.\n const entry = raw as Record<string, unknown>\n const ownId = typeof entry['id'] === 'string' && entry['id'].length > 0 ? entry['id'] : ''\n return { ...entry, id: key.length > 0 ? key : ownId }\n })\n .filter(entry => typeof entry['id'] === 'string' && entry['id'].length > 0)\n }\n return undefined\n}\n\n/**\n * One model a listing advertises, in the shape the harness's model discovery\n * reports: the endpoint-facing id, and whatever presentation metadata the\n * endpoint offered. A source without the optional fields yields just the id,\n * which every consumer (`adopt()` on the Models card) treats as complete.\n */\nexport interface ListedModel {\n id: string\n name?: string\n contextWindow?: number\n maxTokens?: number\n /** Textual inputs a model advertises, when the endpoint names them. */\n inputModalities?: string[]\n}\n\n/** The first non-blank string among several candidate fields. */\nfunction label(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length === 0 ? undefined : trimmed\n}\n\n/** A positive capacity figure, or undefined when the value is not one. */\nfunction capacity(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined\n}\n\n/** One listing entry's capacity hint, read from every spelling gateways use. */\nfunction capacities(entry: Record<string, unknown>, keys: readonly string[]): number | undefined {\n const limit = isRecord(entry['limit']) ? entry['limit'] : undefined\n const top = isRecord(entry['top_provider']) ? entry['top_provider'] : undefined\n for (const key of keys) {\n const direct = capacity(entry[key])\n if (direct !== undefined) return direct\n }\n const tokenWindow = capacity(limit?.['context'])\n if (tokenWindow !== undefined) return tokenWindow\n return capacity(top?.['max_completion_tokens'])\n}\n\n/** Context-window field names, in the official parser's priority order (Gemini's native spelling included). */\nconst CONTEXT_WINDOW_KEYS = ['contextWindow', 'context_window', 'context_length', 'max_input_tokens', 'inputTokenLimit'] as const\n\n/** Output-limit field names, in the official parser's priority order (Gemini's native spelling included). */\nconst MAX_TOKENS_KEYS = ['maxOutputTokens', 'max_output_tokens', 'maxTokens', 'max_tokens', 'outputTokenLimit'] as const\n\n/**\n * Read a listing reply into the models it advertises, in endpoint order.\n *\n * This is the mirror of the official `readListing`, extended with the idle\n * metadata the Models page can adopt: a name/display label, a context window,\n * an output ceiling, and input modalities when the endpoint names them. Ids are\n * trimmed and de-duplicated because the merged discovery appends one endpoint's\n * list to another's, and a duplicate row would render twice in the picker.\n * @param body - the decoded JSON reply.\n * @returns the models, or undefined when the reply names neither listing shape.\n */\nexport function modelsFromListing(body: unknown): ListedModel[] | undefined {\n const entries = listingEntries(body)\n if (entries === undefined) return undefined\n const out: ListedModel[] = []\n const seen = new Set<string>()\n for (const entry of entries) {\n const id = label(entry['id'])\n if (id === undefined || seen.has(id)) continue\n seen.add(id)\n const model: ListedModel = { id }\n const name = label(entry['name']) ?? label(entry['display_name']) ?? label(entry['displayName'])\n if (name !== undefined) model.name = name\n const contextWindow = capacities(entry, CONTEXT_WINDOW_KEYS)\n if (contextWindow !== undefined) model.contextWindow = contextWindow\n const maxTokens = capacities(entry, MAX_TOKENS_KEYS)\n if (maxTokens !== undefined) model.maxTokens = maxTokens\n const input = entry['input']\n if (Array.isArray(input)) {\n const modalities = [...new Set(input.filter((item): item is string => typeof item === 'string' && item.length > 0))]\n if (modalities.length > 0) model.inputModalities = modalities\n }\n out.push(model)\n }\n return out\n}\n", "/**\n * One provider listing probe: ask an endpoint for the models it advertises.\n *\n * The same discipline governs every place this plugin interrogates an endpoint\n * \u2014 the probe route, the key panel's discover op, the per-key discovery pass\n * and the fetch overlay's aggregated catalogue \u2014 so the one bounded, signed,\n * redirect-refusing read lives here once: the profile's configured request\n * headers ride along, the credential is signed the way the protocol expects, a\n * listing is never a place to be forwarded, and the reply is bounded before it\n * is parsed.\n *\n * @module dsh-model-think-level/discovery-merge\n */\n\nimport { composeProbeHeaders, modelsFromListing, probeListingUrl, readBounded, type ListedModel } from './listing.js'\nimport type { RouteProtocol } from './key-refs.js'\n\n/** One listing request: where to ask, and which credential to sign it with. */\nexport interface ListingProbe {\n readonly baseURL: string\n readonly api: RouteProtocol\n readonly apiKey?: string | undefined\n readonly headers?: unknown\n readonly timeoutMs: number\n /** Transport override: the tests' stub, and the plugin's own fetch seam. */\n readonly send?: (url: string, init: RequestInit) => Promise<Response>\n}\n\n/**\n * Ask one endpoint for the models it advertises.\n *\n * A probe that cannot be read \u2014 network, status, malformed body \u2014 answers\n * undefined instead of throwing: a listing probe is always an enrichment,\n * never a precondition of the caller's own work.\n * @param probe - the endpoint, protocol, credential, and transport.\n * @returns the listing's models, or undefined when it could not be read.\n */\nexport async function probeListing(probe: ListingProbe): Promise<ListedModel[] | undefined> {\n const url = probeListingUrl(probe.baseURL, probe.api)\n const send = probe.send ?? ((input: string, init: RequestInit) => fetch(input, init))\n try {\n const response = await send(url, {\n method: 'GET',\n headers: composeProbeHeaders(probe.headers, probe.apiKey, probe.api),\n redirect: 'error',\n signal: AbortSignal.timeout(probe.timeoutMs),\n })\n if (!response.ok) {\n await response.body?.cancel().catch(() => {\n // The reply is already discarded; cancelling is cleanup only.\n })\n return undefined\n }\n const text = await readBounded(response, url)\n return modelsFromListing(JSON.parse(text) as unknown)\n } catch {\n return undefined\n }\n}\n", "/**\n * Which endpoint a key's model listing is asked of.\n *\n * A key is not tied to one protocol: a route can answer on an OpenAI-family\n * address, an Anthropic-family one and a Gemini-family one, and each key may\n * pin a protocol of its own. Probing every key against the route's default\n * wire would therefore ask half of them a question their credential cannot\n * answer \u2014 an Anthropic-pinned key returns `401` from an OpenAI gateway, and\n * the panel would conclude the key serves nothing. This module derives the\n * *protocols a key can actually be used with* from the same facts routing uses\n * (the pin, the route's api, and the stored endpoints), so a probe is only\n * sent where a request would go.\n *\n * The rules mirror routing ({@link module:key-route-core}):\n * - a pin is honoured only when its family has an address; a cross-family pin\n * with no address for that family is NOT probed, because no request could be\n * served that way either \u2014 the key keeps its previous scope and the plan says\n * why;\n * - a same-family pin (Responses vs Chat Completions) rides the route's own\n * address: only the wire changes, so the listing is asked there;\n * - a key with no pin is AUTOMATIC (the request speaks the model family's own\n * wire where the provider addressed it), so it is probed on the route's wire\n * and additionally on every other family's address the route configured \u2014\n * that is the only way to learn that the key also reaches the models of\n * those families.\n *\n * @module dsh-model-think-level/key-probe\n */\n\nimport { endpointFamilyOf, ENDPOINT_FAMILIES, type EndpointFamily, type RouteEndpoints, type RouteProtocol } from './key-refs.js'\nimport { LISTABLE_PROTOCOLS, displayUrl, listingEntries, probeListingUrl } from './listing.js'\n\nexport type { EndpointFamily }\n\n/** The protocol a probe speaks on a family when it has no more specific pin. */\nexport const FAMILY_PROTOCOL: Readonly<Record<EndpointFamily, RouteProtocol>> = {\n openai: 'openai-completions',\n anthropic: 'anthropic-messages',\n gemini: 'google-generative-ai',\n}\n\n/** The listing request one key should be sent. */\nexport interface ProbeTarget {\n readonly api: RouteProtocol\n readonly baseURL: string\n readonly family: EndpointFamily\n}\n\n/** What a key's probe would ask, and why it asks nothing when it asks nothing. */\nexport interface ProbePlan {\n readonly targets: readonly ProbeTarget[]\n /** Set when no legal request exists for this key (its pin cannot be honoured). */\n readonly skipped?: string\n}\n\n/** The routing facts a probe plan is derived from. */\nexport interface ProbeIntent {\n /** The route's own wire (the provider profile's `api`). */\n readonly api: unknown\n /** The route's own address. */\n readonly baseURL: string\n /** The protocol this key pinned, when it pinned one. */\n readonly pinned?: RouteProtocol | undefined\n /** The route's stored endpoint pair, when the storage has one. */\n readonly endpoints?: RouteEndpoints | undefined\n}\n\n/** The wire a route profile names, or undefined when it names none this plugin can speak. */\nfunction knownWire(api: unknown): RouteProtocol | undefined {\n return api === 'anthropic-messages' || api === 'openai-completions' || api === 'openai-responses' || api === 'google-generative-ai'\n ? api\n : undefined\n}\n\n/** A non-empty address, trimmed of surrounding whitespace. */\nfunction address(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length === 0 ? undefined : trimmed\n}\n\n/**\n * The listing requests one key should receive.\n *\n * Every target is a request a real call could also make: the protocol is one\n * the key would be dispatched to, and the address is the one that protocol\n * would use. Targets are de-duplicated by what they would actually fetch \u2014 a\n * same-family pin shares its family's address with the route's own wire, and a\n * gateway that spells one listing under both protocols must not be asked twice.\n * @param intent - the route's wire and address, the key's pin, the endpoint pair.\n * @returns the targets in preference order, or a skip reason when none apply.\n */\nexport function probePlanFor(intent: ProbeIntent): ProbePlan {\n // A probe is a real request on a real wire: when the route names a protocol\n // this plugin cannot speak, there is no wire to ask and no address to ask it\n // on \u2014 guessing one would report another provider's capabilities.\n const wire = knownWire(intent.api)\n const family = wire === undefined ? undefined : endpointFamilyOf(wire)\n const baseURL = address(intent.baseURL)\n const targets: ProbeTarget[] = []\n const seen = new Set<string>()\n const push = (target: ProbeTarget): void => {\n if (!LISTABLE_PROTOCOLS.has(target.api)) return\n const key = `${target.api}\\u0000${probeListingUrl(target.baseURL, target.api)}`\n if (seen.has(key)) return\n seen.add(key)\n targets.push(target)\n }\n\n if (intent.pinned !== undefined) {\n const pinFamily = endpointFamilyOf(intent.pinned)\n // A same-family pin keeps the route's address (possibly its other wire);\n // a cross-family pin must use that family's own configured address.\n const pinnedBase = pinFamily === family ? baseURL ?? address(intent.endpoints?.[pinFamily]) : address(intent.endpoints?.[pinFamily])\n if (pinnedBase === undefined) {\n // A pin without an address is not honoured by routing either, so asking\n // it would only manufacture a failure.\n return {\n targets: [],\n skipped: `the key pins ${intent.pinned} but this provider has no ${pinFamily} address`,\n }\n }\n push({ api: intent.pinned, baseURL: pinnedBase, family: pinFamily })\n return { targets }\n }\n\n if (wire !== undefined && family !== undefined) {\n if (baseURL !== undefined) push({ api: wire, baseURL, family })\n // A key with no pin serves every family the route addressed: each extra\n // address is a wire routing could legally dispatch this key on, so each\n // one is asked (a Gemini address is how a bare key proves it also reaches\n // the models of that family).\n for (const other of ENDPOINT_FAMILIES) {\n if (other === family) continue\n const otherBase = address(intent.endpoints?.[other])\n if (otherBase !== undefined) push({ api: FAMILY_PROTOCOL[other], baseURL: otherBase, family: other })\n }\n return { targets }\n }\n\n // Unknown route wire: ask only the families the provider explicitly addressed.\n for (const configured of ENDPOINT_FAMILIES) {\n const configuredBase = address(intent.endpoints?.[configured])\n if (configuredBase !== undefined) push({ api: FAMILY_PROTOCOL[configured], baseURL: configuredBase, family: configured })\n }\n return {\n targets,\n ...targets.length === 0\n ? { skipped: `this provider cannot be interrogated on ${String(intent.api)}; set each key's models by hand` }\n : {},\n }\n}\n\n/** One target's outcome, in the shape the panel can render. */\nexport interface ProbeTargetOutcome {\n readonly api: RouteProtocol\n readonly family: EndpointFamily\n /** The URL asked, with userinfo stripped so a stored `user:pass@` never leaks. */\n readonly url: string\n readonly ok: boolean\n /** HTTP status when the endpoint answered at all. */\n readonly status?: number\n /** How many distinct models this target advertised. */\n readonly models?: number\n /** Why this target did not answer, when it did not. */\n readonly error?: string\n}\n\n/** What one key's probe learned. */\nexport interface KeyProbeResult {\n readonly ref: string\n /**\n * The key's new scope: the union of every target that answered. Undefined\n * when no target answered \u2014 the caller must then keep the previous scope\n * rather than recording \"serves nothing\".\n */\n readonly models: string[] | undefined\n readonly targets: readonly ProbeTargetOutcome[]\n /** Set when the plan had no legal target at all (see {@link probePlanFor}). */\n readonly skipped?: string\n}\n\n/** Transport and credentials one key's probe needs. */\nexport interface ProbeKeyOptions {\n readonly ref: string\n readonly intent: ProbeIntent\n /** The resolved credential; a probe is always signed by the key it asks about. */\n readonly apiKey: string\n /** The route profile's configured headers (deployment-owned values ride along). */\n readonly profileHeaders: unknown\n readonly timeoutMs: number\n readonly send: (url: string, init: RequestInit) => Promise<Response>\n /** How to sign one listing request for one protocol. */\n readonly headersFor: (profileHeaders: unknown, apiKey: string, api: RouteProtocol) => Record<string, string>\n /** Reads a bounded listing body. */\n readonly read: (response: Response, url: string) => Promise<string>\n /** Parses a listing body into entries; undefined when it names no listing shape. */\n readonly entries: (body: unknown) => Record<string, unknown>[] | undefined\n}\n\n/**\n * Ask one key for its models on every address it can legitimately be used with.\n *\n * A target that fails is reported and does not cancel the others: a key that\n * serves only the Anthropic family still records those models when its OpenAI\n * family probe is refused. When at least one target answers, the key's scope\n * becomes the union of the answers; an endpoint answering with an empty listing\n * is a real answer (\"this key serves none\") and yields `[]`.\n * @param options - the key, its routing facts, and the transport readers.\n * @returns the scope to store and the per-target report.\n */\nexport async function probeKeyModels(options: ProbeKeyOptions): Promise<KeyProbeResult> {\n const plan = probePlanFor(options.intent)\n const outcomes: ProbeTargetOutcome[] = []\n const ids: string[] = []\n const seen = new Set<string>()\n let answered = 0\n for (const target of plan.targets) {\n const url = probeListingUrl(target.baseURL, target.api)\n const reported = displayUrl(url)\n let response: Response\n try {\n response = await options.send(url, {\n method: 'GET',\n headers: options.headersFor(options.profileHeaders, options.apiKey, target.api),\n redirect: 'error',\n signal: AbortSignal.timeout(options.timeoutMs),\n })\n } catch (error) {\n outcomes.push({\n api: target.api,\n family: target.family,\n url: reported,\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n })\n continue\n }\n if (!response.ok) {\n await response.body?.cancel().catch(() => {\n // Best-effort cleanup: the outcome is already decided by the status.\n })\n outcomes.push({ api: target.api, family: target.family, url: reported, ok: false, status: response.status })\n continue\n }\n let entries: Record<string, unknown>[] | undefined\n try {\n entries = options.entries(JSON.parse(await options.read(response, url)) as unknown)\n } catch (error) {\n outcomes.push({\n api: target.api,\n family: target.family,\n url: reported,\n ok: false,\n status: response.status,\n error: error instanceof Error ? error.message : String(error),\n })\n continue\n }\n if (entries === undefined) {\n outcomes.push({\n api: target.api,\n family: target.family,\n url: reported,\n ok: false,\n status: response.status,\n error: 'the reply names no model listing',\n })\n continue\n }\n answered += 1\n for (const entry of entries) {\n const id = entry['id']\n if (typeof id !== 'string' || id.length === 0 || seen.has(id)) continue\n seen.add(id)\n ids.push(id)\n }\n outcomes.push({\n api: target.api,\n family: target.family,\n url: reported,\n ok: true,\n status: response.status,\n models: entries.length,\n })\n }\n return {\n ref: options.ref,\n models: answered === 0 ? undefined : ids,\n targets: outcomes,\n ...plan.skipped === undefined ? {} : { skipped: plan.skipped },\n }\n}\n\n/** Re-exported so the entry module does not import two listing names for one op. */\nexport { listingEntries as parseListingEntries }\n", "/**\n * One model catalogue from a route's several keys.\n *\n * A provider route may hold more than one key, and the keys need not see the\n * same models: an Anthropic-pinned key answers a different listing than the\n * OpenAI-family one, and a gateway can give two OpenAI keys different quotas\n * while advertising different catalogues. Probing each key separately answers\n * \"what does THIS key serve\" \u2014 the question routing needs \u2014 but a picker and a\n * \"detect models\" button both ask the other question: \"what does this provider\n * serve at all?\". This module answers that one by keeping, per model, the keys\n * that advertised it.\n *\n * Two rules are inherited from the gateway practice this mirrors (magpie's\n * `fetchPerKey`):\n * - a model advertised by several keys is ONE model, listing every key that\n * serves it;\n * - a key whose listing could not be read this time keeps the models it was\n * last seen serving, instead of making them disappear from the catalogue\n * (those models are reported as `retained`, so a caller can say the scope is\n * stale rather than fresh).\n *\n * The catalogue reads in one natural id order (`numeric` collation, so a model\n * family keeps version order), not in the order the keys were asked: a\n * catalogue assembled key by key would read as one key's list with the next\n * key's extras appended, scattering one letter across both ends.\n *\n * Probing is the caller's job: {@link collectKeyListings} only bounds how many\n * probes run at once and merges what comes back, so the panel, the `discover`\n * operation and the fetch overlay all share one merge.\n *\n * @module dsh-model-think-level/multi-key-listing\n */\n\nimport type { KeyProbeResult } from './key-probe.js'\n\n/** How many probes run at once unless the caller says otherwise. */\nexport const DEFAULT_PROBE_CONCURRENCY = 4\n\n/**\n * How model ids read in the merged catalogue. `numeric` keeps a family in\n * version order (`glm-4.5` before `glm-4.6`), and `en` pins the alphabet so the\n * order does not drift with the host's locale.\n */\nconst MODEL_ORDER = new Intl.Collator('en', { numeric: true, sensitivity: 'base' })\n\n/** One model in the merged catalogue and the keys that advertised it. */\nexport interface MergedModel {\n readonly id: string\n /** The keys whose listing named this model, in key-list order. */\n readonly keys: readonly string[]\n}\n\n/** A route's whole catalogue, merged across the keys that were asked. */\nexport interface MergedListing {\n /** The models, in natural id order, each naming its keys. */\n readonly models: readonly MergedModel[]\n /** Just the ids, in the same order (what a picker or a patch needs). */\n readonly ids: readonly string[]\n /** Keys that answered this pass. */\n readonly answered: readonly string[]\n /**\n * Keys whose probe produced no scope at all. When a last-known scope exists\n * for one of them, its models are still in the catalogue and the key is\n * reported here \u2014 the caller decides whether \"stale\" is worth saying.\n */\n readonly unreadable: readonly string[]\n /** Keys whose models came from their last-known scope rather than this pass. */\n readonly retained: readonly string[]\n}\n\n/** Normalized model ids of one stored scope (blank ids dropped, order kept). */\nfunction idsOf(models: readonly string[] | undefined): string[] {\n if (models === undefined) return []\n const out: string[] = []\n const seen = new Set<string>()\n for (const id of models) {\n const trimmed = typeof id === 'string' ? id.trim() : ''\n if (trimmed.length === 0 || seen.has(trimmed)) continue\n seen.add(trimmed)\n out.push(trimmed)\n }\n return out\n}\n\n/**\n * Fold per-key probe results into one catalogue.\n *\n * A key with `models === undefined` did not answer; its last-known scope (when\n * one is supplied) keeps its models in the catalogue and marks it `retained`.\n * Without such a scope the key simply contributes nothing to this pass.\n * @param results - one result per key, in key-list order.\n * @param lastKnown - the scopes the keys were seen serving before this pass.\n * @returns the merged catalogue and the per-key bookkeeping.\n */\nexport function mergeKeyListings(\n results: readonly KeyProbeResult[],\n lastKnown?: ReadonlyMap<string, readonly string[]>,\n): MergedListing {\n const order: string[] = []\n const keysByModel = new Map<string, string[]>()\n const answered: string[] = []\n const unreadable: string[] = []\n const retained: string[] = []\n const seenKeys = new Set<string>()\n\n const add = (ref: string, ids: readonly string[]): void => {\n for (const id of ids) {\n const owners = keysByModel.get(id)\n if (owners === undefined) {\n keysByModel.set(id, [ref])\n order.push(id)\n } else if (!owners.includes(ref)) {\n owners.push(ref)\n }\n }\n }\n\n for (const result of results) {\n if (seenKeys.has(result.ref)) continue\n seenKeys.add(result.ref)\n if (result.models !== undefined) {\n answered.push(result.ref)\n add(result.ref, idsOf(result.models))\n continue\n }\n unreadable.push(result.ref)\n const known = idsOf(lastKnown?.get(result.ref))\n if (known.length === 0) continue\n retained.push(result.ref)\n add(result.ref, known)\n }\n\n order.sort(MODEL_ORDER.compare)\n const models = order.map(id => ({ id, keys: keysByModel.get(id) ?? [] }))\n return {\n models,\n ids: order,\n answered,\n unreadable,\n retained,\n }\n}\n\n/** What one collection run needs from its caller. */\nexport interface CollectKeyListingsOptions<Key> {\n /** The keys to ask, in the order the catalogue should read. */\n readonly keys: readonly Key[]\n /** Ask one key for its listing (typically `probeKeyModels`). */\n readonly probe: (key: Key) => Promise<KeyProbeResult>\n /**\n * The ref a key is known by. When given, a probe that THROWS is recorded as\n * that key having no answer (so its last-known scope still survives); without\n * it a throwing probe simply contributes nothing.\n */\n readonly refOf?: (key: Key) => string\n /** How many probes may be in flight; at least 1. Defaults to 4. */\n readonly concurrency?: number\n /** The scopes the keys were seen serving before this pass. */\n readonly lastKnown?: ReadonlyMap<string, readonly string[]>\n}\n\n/**\n * Probe every key with bounded concurrency, then merge the answers.\n *\n * Kept in key order regardless of which probe finished first: the per-key\n * bookkeeping reads in the keys' preference order, not by network luck. (The\n * catalogue itself reads in id order \u2014 see {@link mergeKeyListings}.) A probe\n * that throws contributes nothing for its key (the caller's own probe decides\n * what \"no answer\" means); the remaining probes still run.\n * @param options - the keys, how to probe one, and the concurrency bound.\n * @returns the results in key order, plus the merged catalogue.\n */\nexport async function collectKeyListings<Key>(\n options: CollectKeyListingsOptions<Key>,\n): Promise<{ results: KeyProbeResult[]; merged: MergedListing }> {\n const total = options.keys.length\n const results: (KeyProbeResult | undefined)[] = new Array<KeyProbeResult | undefined>(total)\n const bound = Math.max(1, Math.min(options.concurrency ?? DEFAULT_PROBE_CONCURRENCY, Math.max(total, 1)))\n let next = 0\n\n const worker = async (): Promise<void> => {\n for (;;) {\n const index = next\n next += 1\n if (index >= total) return\n const key = options.keys[index] as Key\n try {\n results[index] = await options.probe(key)\n } catch {\n // A probe that cannot even report a failure answers \"nothing this time\";\n // recording it that way (rather than dropping the key) is what lets the\n // merge keep the models the key was last seen serving.\n const ref = options.refOf?.(key)\n if (ref !== undefined) results[index] = { ref, models: undefined, targets: [] }\n }\n }\n }\n\n await Promise.all(Array.from({ length: bound }, async () => worker()))\n const settled = results.filter((result): result is KeyProbeResult => result !== undefined)\n return { results: settled, merged: mergeKeyListings(settled, options.lastKnown) }\n}\n", "/**\n * Provider request-header overlay, PURE half: the origin index and the header\n * value rules shared by the fetch-layer installer and the conflict report.\n *\n * Why this exists at all (issue #12): a route's `headers` dict can be merged or\n * overwritten by the official adapter's attribution headers, with `user-agent`\n * being the most visible case. A gateway that depends on any configured client\n * header therefore may not see the value stored in the profile. The overlay\n * reapplies the complete configured dictionary at the fetch layer, the last\n * public seam before the request reaches the wire.\n *\n * The index keeps every route's endpoint path and configured model ids. The URL\n * alone cannot distinguish two routes that share an origin, while an OpenAI-\n * compatible chat request carries the selected model in its JSON body. The\n * origin map remains as a backwards-compatible fallback for requests that do\n * not expose enough identity (for example a GET /models probe).\n *\n * @module dsh-model-think-level/headers-core\n */\n\nimport { isRecord } from './shared.js'\n\n/**\n * Upper bound on one header value the plugin will send. Fetch itself refuses\n * newline-bearing values (a header-injection guard); this plugin additionally\n * refuses anything unreasonable long rather than letting a paste of a whole\n * certificate turn every request into an upstream 400.\n */\nconst MAX_UA_LENGTH = 512\n\n/** One route's configured request headers and its fetch matching metadata. */\nexport interface HeaderOverride {\n /** `scheme://host:port` of the route's endpoint, exactly as Fetch would print it. */\n origin: string\n /** Normalized pathname prefix from the route's baseURL. */\n pathPrefix: string\n /**\n * The string header pairs to apply at the fetch layer. Empty when the route\n * declares none: the route still participates in matching, so a request that\n * clearly belongs to it is NOT given another route's headers.\n */\n headers: Record<string, string>\n /** The route key that declared them (diagnostics and UI labelling). */\n route: string\n /** Model IDs declared by this route, used to disambiguate shared endpoints. */\n modelIds: string[]\n /** The configured `user-agent`, retained for compatibility and diagnostics. */\n userAgent?: string\n /** Whether this route actually declares sendable request headers. */\n hasHeaders: boolean\n}\n\n/** Backwards-compatible name retained for callers that only knew the UA seam. */\nexport type UserAgentOverride = HeaderOverride\n\n/** A same-origin header disagreement that the URL-only fetch seam cannot disambiguate. */\nexport interface HeaderConflict {\n origin: string\n header: string\n routes: string[]\n values: string[]\n}\n\n/** The route index plus what could not be indexed or was ambiguous. */\nexport interface HeaderIndex {\n /** Every route with a usable endpoint, headers included or not. */\n routes: HeaderOverride[]\n /** Every route with sendable headers, retained for diagnostics and the UI. */\n overrides: HeaderOverride[]\n /** origin \u2192 first complete header override, used as a conservative fallback. */\n byOrigin: Map<string, HeaderOverride>\n /** Same-origin routes that declare different header values. */\n conflicts: { origin: string; routes: string[]; values: string[] }[]\n /** Same-origin disagreements for any configured header. */\n headerConflicts: HeaderConflict[]\n}\n\n/** Backwards-compatible name retained for the original public index contract. */\nexport type UserAgentIndex = HeaderIndex\n\n/** An empty index, for the \"no route declares headers\" case. */\nexport function emptyIndex(): HeaderIndex {\n return { routes: [], overrides: [], byOrigin: new Map(), conflicts: [], headerConflicts: [] }\n}\n\n/** The `scheme://host:port` of a URL string, or undefined when unparseable. */\nexport function originOf(url: string | undefined): string | undefined {\n if (url === undefined || url.trim().length === 0) return undefined\n try {\n return new URL(url).origin\n } catch {\n // A relative or malformed endpoint is not an origin this seam can match.\n return undefined\n }\n}\n\n/**\n * Whether a configured value can ride a Fetch `user-agent` field. Refused\n * rather than sanitized: a header carrying a newline is a request-splitting\n * hazard, and quietly rewriting the user's value would send something they\n * never asked for.\n * @param value - the configured header value.\n * @returns whether it is safe to `Headers.set()`.\n */\nexport function isSendableUserAgent(value: string): boolean {\n if (value.length === 0 || value.length > MAX_UA_LENGTH) return false\n // CR/LF and NUL are what Fetch's own guard rejects; refusing them here keeps\n // the refusal at configuration time instead of on every request.\n return !/[\\r\\n\\0]/.test(value)\n}\n\n/**\n * Whether a configured name/value pair can ride a Fetch header. Fetch is the\n * authority for the exact token grammar, so this accepts arbitrary legal names\n * instead of maintaining a brittle allow-list.\n */\nexport function isSendableHeader(name: string, value: string): boolean {\n if (name.length === 0) return false\n try {\n const headers = new Headers()\n headers.set(name, value)\n return true\n } catch {\n return false\n }\n}\n\n/** The `headers` dict of one route profile, as string pairs, or undefined. */\nexport function headersOf(profile: Record<string, unknown> | undefined): Record<string, string> | undefined {\n if (profile === undefined) return undefined\n const headers = profile['headers']\n if (!isRecord(headers)) return undefined\n const pairs: Record<string, string> = {}\n for (const [name, value] of Object.entries(headers)) {\n if (typeof value === 'string') pairs[name] = value\n }\n return Object.keys(pairs).length === 0 ? undefined : pairs\n}\n\n/**\n * The subset of a profile's headers that Fetch can send. An invalid stored\n * entry must not make the wrapper throw and break an otherwise valid request.\n */\nfunction sendableHeadersOf(profile: Record<string, unknown> | undefined): Record<string, string> | undefined {\n const headers = headersOf(profile)\n if (headers === undefined) return undefined\n const sendable: Record<string, string> = {}\n for (const [name, value] of Object.entries(headers)) {\n if (!isSendableHeader(name, value)) continue\n // Keep the historical UA guard: it avoids sending a malformed or\n // unexpectedly huge client identity while leaving every other legal header\n // available to the arbitrary-header editor.\n if (name.toLowerCase() === 'user-agent' && !isSendableUserAgent(value)) continue\n sendable[name] = value\n }\n return Object.keys(sendable).length === 0 ? undefined : sendable\n}\n\n/**\n * The `user-agent` a route's `headers` dict declares, case-insensitively.\n *\n * A `user-agent` stored here is the user's DECLARATION of the identity their\n * gateway wants, even though the official adapter discards it; the plugin reads\n * the same key so the settings document stays the single source of truth.\n * @param profile - one route's profile record.\n * @returns the value, or undefined when the route declares none.\n */\nexport function declaredUserAgent(profile: Record<string, unknown> | undefined): string | undefined {\n const headers = headersOf(profile)\n if (headers === undefined) return undefined\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() === 'user-agent') return isSendableUserAgent(value) ? value : undefined\n }\n return undefined\n}\n\n/** Normalize a route endpoint's pathname for boundary-safe prefix matching. */\nfunction pathPrefixOf(url: string): string {\n try {\n const pathname = new URL(url).pathname.replace(/\\/+$/, '')\n return pathname.length === 0 ? '/' : pathname\n } catch {\n return '/'\n }\n}\n\n/** Model IDs that can appear in a pi-ai request body for one route. */\nfunction modelIdsOf(profile: Record<string, unknown>): string[] {\n const ids = new Set<string>()\n const models = profile['models']\n if (Array.isArray(models)) {\n for (const model of models) {\n if (!isRecord(model) || typeof model['id'] !== 'string' || model['id'].length === 0) continue\n ids.add(model['id'])\n }\n }\n // modelOverrides is keyed by model id and can carry entries not repeated in\n // the explicit models array, so include it as another source of route identity.\n const overrides = profile['modelOverrides']\n if (isRecord(overrides)) {\n for (const id of Object.keys(overrides)) if (id.length > 0) ids.add(id)\n }\n return [...ids]\n}\n\n/** Normalize names the way Fetch's Headers object compares them. */\nfunction normalizedHeaders(headers: Record<string, string>): Map<string, { name: string; value: string }> {\n const normalized = new Map<string, { name: string; value: string }>()\n for (const [name, value] of Object.entries(headers)) {\n normalized.set(name.toLowerCase(), { name, value })\n }\n return normalized\n}\n\n/** Record a same-origin difference that the URL-only fetch seam cannot route. */\nfunction recordHeaderConflicts(index: HeaderIndex, existing: HeaderOverride, route: string, headers: Record<string, string>): void {\n const first = normalizedHeaders(existing.headers)\n const next = normalizedHeaders(headers)\n const names = new Set([...first.keys(), ...next.keys()])\n for (const name of names) {\n const oldEntry = first.get(name)\n const nextEntry = next.get(name)\n if (oldEntry?.value === nextEntry?.value) continue\n const reportedName = nextEntry?.name ?? oldEntry?.name ?? name\n const reported = index.headerConflicts.find(entry => entry.origin === existing.origin && entry.header.toLowerCase() === name)\n if (reported === undefined) {\n index.headerConflicts.push({\n origin: existing.origin,\n header: reportedName,\n routes: [existing.route, route],\n values: [oldEntry?.value ?? '<not configured>', nextEntry?.value ?? '<not configured>'],\n })\n } else if (!reported.routes.includes(route)) {\n reported.routes.push(route)\n reported.values.push(nextEntry?.value ?? '<not configured>')\n }\n }\n}\n\n/** Build the route index from each provider profile's endpoint and header declaration. */\nexport function buildHeaderIndex(\n providers: Record<string, Record<string, unknown>>,\n): HeaderIndex {\n const index = emptyIndex()\n const claimedUserAgents = new Map<string, { routes: string[]; values: string[] }>()\n for (const [route, profile] of Object.entries(providers)) {\n const baseURL = typeof profile['baseURL'] === 'string' ? profile['baseURL'] : undefined\n const origin = originOf(baseURL)\n if (origin === undefined) continue\n\n const sendable = sendableHeadersOf(profile) ?? {}\n const hasHeaders = Object.keys(sendable).length > 0\n const userAgent = Object.entries(sendable).find(([name]) => name.toLowerCase() === 'user-agent')?.[1]\n const override: HeaderOverride = {\n origin,\n pathPrefix: pathPrefixOf(baseURL ?? origin),\n headers: sendable,\n route,\n modelIds: modelIdsOf(profile),\n hasHeaders,\n ...(userAgent === undefined ? {} : { userAgent }),\n }\n // Every route is registered, headers or not: a route that declares no\n // headers must still be able to claim its own requests so another route on\n // the same endpoint cannot leak its headers onto them.\n index.routes.push(override)\n if (!hasHeaders) continue\n index.overrides.push(override)\n const existing = index.byOrigin.get(origin)\n if (existing === undefined) {\n index.byOrigin.set(origin, override)\n } else {\n recordHeaderConflicts(index, existing, route, sendable)\n }\n\n if (userAgent === undefined) continue\n const claimed = claimedUserAgents.get(origin)\n if (claimed === undefined) {\n claimedUserAgents.set(origin, { routes: [route], values: [userAgent] })\n continue\n }\n claimed.routes.push(route)\n claimed.values.push(userAgent)\n // Idempotent declaration (two routes, same identity) is not a UA conflict.\n if (claimed.values.every(value => value === claimed.values[0])) continue\n const reported = index.conflicts.find(entry => entry.origin === origin)\n if (reported === undefined) index.conflicts.push({ origin, routes: [...claimed.routes], values: [...claimed.values] })\n else {\n reported.routes = [...claimed.routes]\n reported.values = [...claimed.values]\n }\n }\n return index\n}\n\n/** Original public name retained while callers migrate to the generic index. */\nexport function buildUserAgentIndex(\n providers: Record<string, Record<string, unknown>>,\n): UserAgentIndex {\n return buildHeaderIndex(providers)\n}\n\n/** The pathname of a request URL, normalized the way {@link pathPrefixOf} is. */\nexport function requestPathOf(url: string): string | undefined {\n try {\n return new URL(url).pathname\n } catch {\n return undefined\n }\n}\n\n/** Whether a request path sits under a route's baseURL path prefix. */\nfunction pathMatches(requestPath: string, prefix: string): boolean {\n if (prefix === '/') return true\n return requestPath === prefix || requestPath.startsWith(`${prefix}/`)\n}\n\n/**\n * The model id carried by a JSON request body, or undefined when the body is\n * not JSON / names no string `model`. OpenAI-compatible chat completions and\n * responses both put the selected model in the top-level `model` field.\n */\nexport function modelOfJsonBody(body: string): string | undefined {\n try {\n const parsed: unknown = JSON.parse(body)\n if (!isRecord(parsed)) return undefined\n const model = parsed['model']\n return typeof model === 'string' && model.length > 0 ? model : undefined\n } catch {\n // A non-JSON body (multipart, SSE upload, empty) carries no model identity.\n return undefined\n }\n}\n\n/**\n * The routes that could own a request, narrowed by origin and endpoint path.\n *\n * The result is the set the fetch layer must disambiguate: one element means\n * the URL already identifies the route (no body read is needed), several means\n * only the request's own `model` can decide, and zero means no route matches.\n * @param index - the live route index.\n * @param url - the request URL.\n * @returns the candidate overrides, in declaration order.\n */\nexport function pathCandidatesOf(index: HeaderIndex, url: string): HeaderOverride[] {\n const origin = originOf(url)\n if (origin === undefined) return []\n // A hand-built index may carry only the origin map; honour it as the legacy\n // single-candidate shape.\n const known = index.routes.length === 0 ? index.overrides : index.routes\n const byOrigin = known.length === 0\n ? (() => { const only = index.byOrigin.get(origin); return only === undefined ? [] : [only] })()\n : known.filter(entry => entry.origin === origin)\n if (byOrigin.length <= 1) return byOrigin\n const requestPath = requestPathOf(url)\n if (requestPath === undefined) return byOrigin\n const matched = byOrigin.filter(entry => pathMatches(requestPath, entry.pathPrefix))\n // An empty path match means the route paths were not describable (or the\n // request targets a prefix no route declares): keep every candidate.\n return matched.length === 0 ? byOrigin : matched\n}\n\n/**\n * Pick one route out of already-narrowed candidates by the request body's model.\n *\n * The model only decides when exactly one candidate declares it; a model no\n * candidate declares, or a model several candidates share, falls back to the\n * first declarer \u2014 the same conservative rule as a request with no model at\n * all.\n * @param candidates - the path-narrowed candidates, in declaration order.\n * @param model - the model id read from the request body, when one was found.\n * @returns the override to apply, or undefined when there are no candidates.\n */\nexport function selectOverrideFrom(candidates: HeaderOverride[], model?: string): HeaderOverride | undefined {\n if (candidates.length <= 1) return candidates[0]\n if (model !== undefined) {\n const byModel = candidates.filter(entry => entry.modelIds.includes(model))\n if (byModel.length === 1) return byModel[0]\n }\n return candidates[0]\n}\n\n/**\n * Pick the route whose configured headers belong on one request.\n *\n * Two routes can share an origin, which the URL alone cannot separate. The\n * choice is therefore narrowed in three steps: the endpoint path prefix (see\n * {@link pathCandidatesOf}), then the `model` carried by the JSON body (see\n * {@link selectOverrideFrom}), then the first declarer. A request that cannot\n * be pinned down therefore keeps the conservative behaviour the plugin shipped\n * with, and the index's conflict report tells the user the endpoints overlap.\n * @param index - the live route index.\n * @param url - the request URL.\n * @param model - the model id read from the request body, when one was found.\n * @returns the override to apply, or undefined when no route matches.\n */\nexport function selectOverride(\n index: HeaderIndex,\n url: string,\n model?: string,\n): HeaderOverride | undefined {\n return selectOverrideFrom(pathCandidatesOf(index, url), model)\n}\n\n/**\n * The request URL a Fetch call is aimed at, or undefined when it cannot be\n * classified. A `Request` from another realm fails the `instanceof` test and is\n * reported as unclassifiable rather than mis-read \u2014 the same conservative\n * posture the official fetch seam takes.\n * @param input - the fetch input.\n * @returns the URL string, when one can be read.\n */\nexport function requestUrlOf(input: unknown): string | undefined {\n if (typeof input === 'string') return input\n if (typeof URL !== 'undefined' && input instanceof URL) return input.href\n if (typeof Request !== 'undefined' && input instanceof Request) return input.url\n return undefined\n}\n", "/**\n * The fetch-layer installer for provider request-header overrides AND multi-key\n * request signing. The decision of WHAT to send lives in `headers-core.ts` (which\n * headers a route declares) and `key-route-core.ts` (which key a route should\n * sign with, and whether a failed attempt deserves the next key); this module\n * owns the global seam and performs the retries.\n *\n * Shape of the seam: one process-wide wrapper owns `globalThis.fetch`, and\n * every activation is an ENTRY inside it. That is what makes the plugin safe\n * next to itself (an HMR remount, a second composer, two plugin instances) and\n * what makes unloading exact: an entry leaves the registry and the wrapper is\n * restored only once the last entry is gone \u2014 never a blind\n * `globalThis.fetch = original` that would clobber a wrapper installed after\n * this one, and never a wrapper left behind holding the process's fetch.\n *\n * The wrapper is deliberately narrow: a request whose URL is not in the index\n * passes through with its ORIGINAL arguments (same object identity), so\n * unconfigured traffic pays exactly one URL classification and one index\n * lookup \u2014 no allocation beyond that, and no way for a bug in the merge path\n * to alter a request that never matched.\n *\n * Why fetch rather than the pi-ai `transformHeaders` option, which would be\n * narrower: reaching that option means holding the adapter's private `models`\n * collection, and every sanctioned seam (`llm/stream` waterfall,\n * `registerAdapter`) stops at the stream, above the wire. Fetch is the only\n * public surface that sees the merged headers. Both were probed against the\n * real runtime \u2014 see `.tmp-rel/headers-probe/`.\n *\n * Why fetch is ALSO where multi-key failover lives: the provider pushes its\n * `start` event only after a successful HTTP response and turns a bad key\n * (401/403) or rate limit (429) into a thrown error, so by the time pi-ai sees\n * a failure the request has already been spent. This wrapper holds the raw\n * `Response` \u2014 status included \u2014 before the SDK interprets it, so it can cancel\n * a rejected attempt and re-issue it with the next key while the request body\n * is still available.\n *\n * @module dsh-model-think-level/headers-fetch\n */\n\nimport {\n emptyIndex,\n modelOfJsonBody,\n pathCandidatesOf,\n requestUrlOf,\n selectOverrideFrom,\n type HeaderIndex,\n type HeaderOverride,\n} from './headers-core.js'\nimport {\n applyKeyToHeaders,\n classifyFailure,\n keyRest,\n parseRetryAfter,\n restKeyOf,\n restLast,\n shouldFailover,\n WIRE_DISPATCH_HEADER,\n type KeyCandidate,\n} from './key-route-core.js'\n\n/** Registry key on `globalThis`, so a second plugin load shares the one wrapper. */\nconst REGISTRY = Symbol.for('dsh-model-think-level.fetch-overrides')\n\n/** What a key resolver is told about the request it must sign. */\nexport interface KeyRouteContext {\n /** The provider route whose profile matched the request URL. */\n readonly route: string\n /** The model id the request body named, when it could be read. */\n readonly model: string | undefined\n}\n\n/** Context for aggregating a provider's model listing across its keys. */\nexport interface ModelListingContext {\n readonly route: string\n readonly url: string\n readonly headers: Headers\n readonly keys: readonly KeyCandidate[]\n readonly signal?: AbortSignal | null\n /** The fetch below this plugin's wrapper, avoiding recursive interception. */\n readonly send: typeof globalThis.fetch\n}\n\n/** One activation's contribution to the process-wide wrapper. */\ninterface Entry {\n /**\n * Reads the current index. A source rather than a value because the settings\n * document is live: a route added, edited, or removed on the Models page must\n * reach the next request without a plugin reload.\n */\n index: () => HeaderIndex\n /**\n * Orders the keys this route may sign with, most-preferred first, each with\n * its secret already resolved. Absent when this activation does not route\n * keys. A live closure so a key added or re-scoped later is honoured without\n * reinstalling the wrapper.\n */\n keys?: (context: KeyRouteContext) => Promise<readonly KeyCandidate[]>\n /** Combines a GET model listing across the resolved key candidates. */\n modelListing?: (context: ModelListingContext) => Promise<Response | undefined>\n}\n\n/** The process-wide wrapper state. */\ninterface Registry {\n base: typeof globalThis.fetch\n wrapper: typeof globalThis.fetch\n entries: Map<symbol, Entry>\n}\n\nfunction registryOf(): Registry | undefined {\n const holder = globalThis as unknown as Record<symbol, Registry | undefined>\n return holder[REGISTRY]\n}\n\n/**\n * Read a request body as text without consuming the request itself.\n *\n * The body is only read when the URL alone leaves the route ambiguous, or when\n * a key resolver needs the model to pick a key \u2014 so the common single-route,\n * no-keys case still pays nothing. A `Request` is cloned (its stream must\n * survive for the real send); an `init.body` string is used directly, and any\n * other body shape (stream, FormData) yields undefined rather than being\n * disturbed.\n */\nasync function bodyTextOf(input: unknown, init: RequestInit | undefined): Promise<string | undefined> {\n if (typeof init?.body === 'string') return init.body\n if (typeof Request !== 'undefined' && input instanceof Request) {\n try {\n return await input.clone().text()\n } catch {\n // A body that cannot be cloned (already disturbed, or streamed) simply\n // leaves the route ambiguous and the first declarer serves.\n return undefined\n }\n }\n return undefined\n}\n\n/** Whether this matched route request is asking for its model catalogue. */\nfunction isModelListingRequest(url: string, method: string | undefined): boolean {\n if ((method ?? 'GET').toUpperCase() !== 'GET') return false\n try {\n return new URL(url).pathname.endsWith('/models')\n } catch {\n return false\n }\n}\n\n/**\n * Whether aggregating the model listing could answer more than the plain\n * request would.\n *\n * The merge began as a multi-key feature, but a SINGLE key can also reach\n * beyond the one URL the plain GET asks: an automatic key carries the\n * cross-family addresses the provider configured (\u66F4\u591A\u7AEF\u70B9), and a pinned key\n * dials its own family's address. In both cases the catalogue the merge\n * returns is the union of addresses, while the plain request would report\n * only the route's own protocol's models \u2014 so the merge runs for one key too.\n * A lone key with no extra address keeps the ordinary path, where the\n * endpoint's own response passes through verbatim.\n */\nfunction listingCouldExceedPlainRequest(keys: readonly KeyCandidate[]): boolean {\n if (keys.length > 1) return true\n return keys.some(candidate =>\n candidate.endpoint !== undefined ||\n (candidate.endpoints !== undefined && Object.keys(candidate.endpoints).length > 0))\n}\n\n/**\n * The caller's request headers as a mutable copy, seeded the way Fetch itself\n * resolves them: an explicit `init.headers` replaces a `Request`'s own headers,\n * and the `Request`'s are inherited only when the init names none. Seeding from\n * the wrong one would either drop the caller's headers or resurrect the ones\n * the caller replaced.\n */\n/**\n * Read at most `limit` characters of a response body WITHOUT pulling the rest.\n *\n * `response.clone().text()` would read the whole reply into one branch and tee\n * the entire remainder into memory for the other; a provider that answers a\n * failure with a page-sized body must not cost that. Reading the clone's\n * reader up to the limit and cancelling bounds the buffered bytes to what was\n * asked for.\n */\nasync function readBoundedText(response: Response, limit: number): Promise<string> {\n const body = response.clone().body\n if (body === null) return ''\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let text = ''\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n text += decoder.decode(value, { stream: true })\n if (text.length >= limit) break\n }\n } finally {\n await reader.cancel().catch(() => {\n // The answer is already decided; releasing the stream is cleanup only.\n })\n }\n return text.slice(0, limit)\n}\n\nfunction seedHeaders(input: unknown, init: RequestInit | undefined): Headers {\n if (init?.headers !== undefined && init.headers !== null) return new Headers(init.headers as HeadersInit)\n if (typeof Request !== 'undefined' && input instanceof Request) return new Headers(input.headers)\n return new Headers()\n}\n\n/**\n * The wrapper: inject the matched route's request headers, sign with the right\n * key, fail over to the next key on a retryable status, and delegate everything\n * else untouched.\n */\nfunction makeWrapper(base: typeof globalThis.fetch, entries: Map<symbol, Entry>): typeof globalThis.fetch {\n return async function fetchWithProviderHeaders(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const url = requestUrlOf(input)\n if (url === undefined) return base(input, init)\n // The URL (origin + endpoint path) narrows the route. Only when it leaves\n // several candidates does the request body's `model` have to decide -- so a\n // single-route deployment keeps the zero-read, zero-allocation fast path.\n let entry: Entry | undefined\n let candidates: HeaderOverride[] = []\n for (const candidate of entries.values()) {\n const found = pathCandidatesOf(candidate.index(), url)\n if (found.length > 0) {\n entry = candidate\n candidates = found\n break\n }\n }\n if (entry === undefined || candidates.length === 0) return base(input, init)\n\n const keyed = entry.keys !== undefined\n // The body model is needed to disambiguate sibling routes AND to pick a key.\n let model: string | undefined\n if (candidates.length > 1 || keyed) {\n const body = await bodyTextOf(input, init)\n model = body === undefined ? undefined : modelOfJsonBody(body)\n }\n const override = candidates.length === 1 ? candidates[0] : selectOverrideFrom(candidates, model)\n if (override === undefined) return base(input, init)\n\n // The route's stored request headers (static strings only). A route that\n // claims the request but declares none is a deliberate \"send nothing\": its\n // patch is simply empty, which is different from \"no route matched\".\n const patched = seedHeaders(input, init)\n let hasPatch = false\n if (override.hasHeaders) {\n for (const [name, value] of Object.entries(override.headers)) {\n // The index already filters invalid entries. Keep the seam defensive for\n // a live source supplied by another caller or a stale settings snapshot.\n try {\n patched.set(name, value)\n hasPatch = true\n } catch {\n // A malformed stored pair must not prevent the remaining headers or\n // the underlying request from being sent.\n }\n }\n }\n\n /**\n * Send one attempt, optionally re-signed with `keyValue`. A fresh `Headers`\n * is built per attempt so a rejected attempt's header tweaks never leak into\n * the retry, and a `Request` input is cloned so its body survives every\n * attempt (the first failed send consumed the clone, not the caller's\n * request).\n */\n const attempt = (keyValue: string | undefined): Promise<Response> => {\n const headers = new Headers(patched)\n if (keyValue !== undefined) applyKeyToHeaders(headers, keyValue)\n if (typeof Request !== 'undefined' && input instanceof Request) {\n return base(new Request(input.clone(), { headers }), { ...init, headers })\n }\n return base(input, { ...init, headers })\n }\n\n // A request the wire seam (headers-pi-ai) already dispatched: it chose the\n // key, the wire and the endpoint, and it owns the failover for them (see\n // WIRE_DISPATCH_HEADER). Strip the marker, send exactly once with the\n // signature already on the headers, and charge nothing \u2014 the wire seam\n // benches its own keys from the stream events it sees.\n if (patched.get(WIRE_DISPATCH_HEADER) === '1') {\n patched.delete(WIRE_DISPATCH_HEADER)\n if (!hasPatch) return base(input, init)\n return attempt(undefined)\n }\n\n // The ordered keys that may sign this request. Empty when this activation\n // does not route keys, in which case the request is sent exactly once with\n // only the header patch (preserving the original object identity when there\n // is no patch at all).\n //\n // This seam can neither switch a protocol nor choose another URL, so it does\n // NOT rank by wire: that ranking belongs to the request seam, which can act\n // on it, and a second opinion here could only contradict the wire actually\n // chosen there. What it does share is the cooldown memory \u2014 a key that was\n // just charged a rejection is deferred here too, because the failure happened\n // on a request that passed through both seams.\n const resolved = keyed ? await entry.keys!({ route: override.route, model }) : []\n const keyCandidates: readonly KeyCandidate[] = restLast(\n resolved,\n candidate => keyRest.isResting(restKeyOf(override.route, candidate.ref), Date.now()),\n )\n\n const method = init?.method ?? (typeof Request !== 'undefined' && input instanceof Request ? input.method : undefined)\n if (entry.modelListing !== undefined && isModelListingRequest(url, method) && listingCouldExceedPlainRequest(keyCandidates)) {\n const signal = init?.signal ?? (typeof Request !== 'undefined' && input instanceof Request ? input.signal : undefined)\n try {\n const listing = await entry.modelListing({\n route: override.route,\n url,\n headers: new Headers(patched),\n keys: keyCandidates,\n ...(signal === undefined ? {} : { signal }),\n send: base,\n })\n if (listing !== undefined) return listing\n } catch {\n // Aggregation is an enrichment: the ordinary request path remains the\n // fallback when no aggregate listing can be produced.\n }\n }\n\n if (!hasPatch && keyCandidates.length === 0) return base(input, init)\n\n /**\n * Charge one rejected attempt to the key that placed it: the status, the\n * provider's `Retry-After` and a bounded body (enough to tell \"out of quota\"\n * from \"too fast\") decide how long it rests. Best effort \u2014 a body that cannot\n * be read still leaves the status, which is the part that matters.\n */\n const chargeFailure = async (candidate: KeyCandidate, response: Response): Promise<void> => {\n const now = Date.now()\n const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'), now)\n let bodyText = ''\n try {\n bodyText = await readBoundedText(response, 4096)\n } catch {\n // The status alone still classifies most failures.\n }\n const kind = classifyFailure(response.status, bodyText)\n if (kind === undefined) return\n keyRest.note(\n restKeyOf(override.route, candidate.ref),\n kind,\n retryAfterMs === undefined ? { now } : { now, retryAfterMs },\n )\n }\n\n /** Whether the caller walked away; a cancelled request is not a key failure. */\n const callerAborted = (): boolean =>\n init?.signal?.aborted === true ||\n (typeof Request !== 'undefined' && input instanceof Request && input.signal.aborted)\n\n if (keyCandidates.length <= 1) {\n const solo = keyCandidates[0]\n const response = await attempt(solo?.value)\n if (solo !== undefined) {\n if (shouldFailover(response.status)) await chargeFailure(solo, response)\n else keyRest.clear(restKeyOf(override.route, solo.ref))\n }\n return response\n }\n // Try keys in preference order; a retryable status on a non-final attempt\n // releases the rejected body and moves to the next key. A 400/404/422 is a\n // request-shape failure every key would repeat, so it is returned as-is.\n let lastFailure: unknown\n for (let index = 0; index < keyCandidates.length; index += 1) {\n const candidate = keyCandidates[index]\n let response: Response\n try {\n response = await attempt(candidate.value)\n } catch (error) {\n // A transport failure (connection refused, DNS, a dropped connection) is\n // this attempt's failure too: the next key may still reach the provider.\n if (callerAborted()) throw error\n lastFailure = error\n keyRest.note(restKeyOf(override.route, candidate.ref), 'refused')\n continue\n }\n if (!shouldFailover(response.status)) {\n keyRest.clear(restKeyOf(override.route, candidate.ref))\n return response\n }\n await chargeFailure(candidate, response)\n if (index === keyCandidates.length - 1) return response\n await response.body?.cancel().catch(() => {\n // Releasing a rejected attempt's body is best-effort cleanup; the retry\n // decides the outcome either way.\n })\n }\n throw lastFailure ?? new Error('no key could place the request')\n }\n}\n\n/** Handle one activation keeps; `dispose` is idempotent. */\nexport interface HeaderOverlayHandle {\n /** Remove this activation's entry, restoring the original fetch when it was the last. */\n dispose(): void\n}\n\n/** Handle for tests and the caller to swap the index a live activation reads. */\nexport interface HeaderOverlay extends HeaderOverlayHandle {\n /** Whether this activation's entry is still installed. */\n readonly active: boolean\n}\n\n/** A mutable index source an activation reads on every request. */\nexport interface OverlaySource {\n /** The live header index this activation contributes. */\n current: HeaderIndex\n /**\n * Optional live key resolver. When present, requests to a matched route are\n * signed with the returned keys in order and failed over across them. Read as\n * a live property so an activation can begin routing keys after install.\n */\n keys?: (context: KeyRouteContext) => Promise<readonly KeyCandidate[]>\n /** Combines a GET model listing across the resolved key candidates. */\n modelListing?: (context: ModelListingContext) => Promise<Response | undefined>\n}\n\n/**\n * Install (or join) the process-wide header wrapper.\n * @param source - the live index (and optional key resolver) this activation contributes.\n * @returns a handle whose `dispose` removes exactly this activation.\n */\nexport function installHeaderOverlay(source: OverlaySource): HeaderOverlay {\n const holder = globalThis as unknown as Record<symbol, Registry | undefined>\n let registry = holder[REGISTRY]\n const token = Symbol('bre-header-overlay')\n if (registry === undefined) {\n const base = globalThis.fetch\n const entries = new Map<symbol, Entry>()\n const wrapper = makeWrapper(base, entries)\n registry = { base, wrapper, entries }\n holder[REGISTRY] = registry\n globalThis.fetch = wrapper\n }\n registry.entries.set(token, {\n index: () => source.current,\n // Delegate through the live source property so a resolver attached after\n // install is honoured, and its internal data stays current.\n keys: source.keys === undefined ? undefined : context => source.keys!(context),\n modelListing: source.modelListing === undefined ? undefined : context => source.modelListing!(context),\n })\n const owned = registry\n return {\n get active(): boolean {\n return owned.entries.has(token)\n },\n dispose(): void {\n owned.entries.delete(token)\n if (owned.entries.size > 0) return\n // Last one out restores the ORIGINAL function, and only when this\n // wrapper still holds the global: a later installer's wrapper must not be\n // clobbered by our teardown.\n if (globalThis.fetch === owned.wrapper) globalThis.fetch = owned.base\n if (holder[REGISTRY] === owned) delete holder[REGISTRY]\n },\n }\n}\n\n/** Whether this plugin's wrapper currently owns the global fetch (diagnostics). */\nexport function headerOverlayInstalled(): boolean {\n const registry = registryOf()\n return registry !== undefined && globalThis.fetch === registry.wrapper\n}\n\n/**\n * The fetch beneath this plugin's wrapper.\n *\n * Used by callers that compose their OWN credential for a request \u2014 the model\n * probe and the per-key discovery pass build the auth header from a specific\n * reference, so letting the wrapper re-sign them with the route's FIRST key\n * would probe the wrong credential. Reaching for the function under the wrapper\n * keeps their composed headers exactly as built, while still honouring any\n * wrapper some other plugin installed first. When this plugin's wrapper is not\n * the live global (nothing to bypass), the live fetch is returned unchanged.\n */\nexport function headerOverlayBypass(): typeof globalThis.fetch {\n const registry = registryOf()\n if (registry !== undefined && globalThis.fetch === registry.wrapper) return registry.base\n return globalThis.fetch\n}\n\n/** The empty index, re-exported so callers building one need a single import. */\nexport { emptyIndex }\n", "/**\n * Request-level header bridge for the pi-ai-backed Harness adapter.\n *\n * The model-list probe has its own direct fetch path, but conversation requests\n * are assembled inside dsh-llm-pi-ai and then passed to pi-ai's Models service.\n * pi-ai exposes `transformHeaders` exactly after auth and request headers have\n * been merged, so it is the right place to restore the profile values that the\n * Harness attribution layer reserves (most visibly `user-agent`).\n *\n * dsh-llm-pi-ai does not expose its private Models collection through a public\n * plugin API. Its adapter is nevertheless registered in the public llm runtime,\n * and the runtime object keeps that registration in a normal `adapters` Map. The\n * bridge uses a narrow structural adapter of that implementation detail and\n * fails open for other adapters or older runtimes.\n *\n * @module dsh-model-think-level/headers-pi-ai\n */\n\nimport { isRecord } from './shared.js'\nimport { selectOverride, type HeaderIndex, type HeaderOverride } from './headers-core.js'\nimport { anthropicRequestBaseUrl, geminiRequestBaseUrl } from './listing.js'\nimport {\n classifyFailure,\n isHonoured,\n keyRest,\n planKeys,\n recordRoutePlan,\n restKeyOf,\n wireOf,\n WIRE_DISPATCH_HEADER,\n type KeyCandidate,\n} from './key-route-core.js'\nimport { endpointFamilyOf, type RouteProtocol } from './key-refs.js'\n\n/**\n * The wire each (route, model) was last served on, learned from the request that\n * produced content.\n *\n * A route may hold two keys pinned to different protocols \u2014 one OpenAI-format\n * key and one Anthropic-format key, say \u2014 and then the first key in list order\n * is, for half the models, the wrong wire: the gateway rejects its body shape\n * before the model is ever reached and the answer only arrives through the\n * failover. That rejected round trip is paid on every request. Remembering the\n * protocol that actually served the model lets the next request start on the\n * right wire, so a mixed-protocol route settles after one request instead of\n * failing over forever.\n */\nconst servedWire = new Map<string, RouteProtocol>()\n\n/**\n * The wire each (route, model) last failed on before any content streamed.\n *\n * An automatic key picks its wire from the model id, and a relay may not serve\n * that family at all (`/v1/messages` answering 404 for a key whose models all\n * list under `/v1/chat/completions`). Without a memory, every request pays the\n * rejected round trip again once the key's cooldown expires \u2014 and clearing the\n * fact on a later success would only restart the cycle, since the automatic\n * resolution would pick the family wire again. The refusal therefore persists\n * for the model: the automatic resolution falls back to the route's own wire,\n * the dispatch that always works, until the process restarts. Only a failure of\n * an AUTOMATIC resolution is recorded \u2014 a pinned key's refusal blames that\n * key's credential, not the family's wire \u2014 and a pin is never second-guessed\n * by this memory.\n */\nconst failedWire = new Map<string, RouteProtocol>()\n\n/** Models in use are few, but a long-lived host can still churn through ids. */\nconst WIRE_MEMORY_LIMIT = 256\n\n/** Record one wire fact for a model, dropping stale ids when the map grows. */\nfunction rememberWireFact(map: Map<string, RouteProtocol>, key: string, wire: RouteProtocol): void {\n if (map.size >= WIRE_MEMORY_LIMIT) map.clear()\n map.set(key, wire)\n}\n\n/**\n * Forget which wire served or failed which model.\n *\n * The memories are process-wide optimisations: they may be dropped at any time\n * without changing an answer, only the number of rejected round trips it takes\n * to find one. Tests (and a host that swaps its provider configuration) call\n * this to start from a clean slate.\n */\nexport function resetWireMemories(): void {\n servedWire.clear()\n failedWire.clear()\n}\n\n/**\n * The protocol a key actually dispatches on this route, and how much the model\n * costs there, are decided by the one plan both seams share \u2014 see\n * `planKeys` in the routing module. Nothing here ranks keys on its own: a second\n * ordering would only be able to disagree with the wire the plan chose.\n */\n\n/** What a key resolver is told about the request it must sign and dispatch. */\nexport interface PiAiKeyContext {\n /** The provider route whose profile claims this request. */\n readonly route: string\n /** The model id the request names, when it could be read. */\n readonly model: string | undefined\n}\n\n/** A live route index shared with the fetch overlay, plus optional key routing. */\nexport interface PiAiHeaderSource {\n current: HeaderIndex\n /**\n * Optional live key resolver. When present, the proxy picks the ordered keys\n * that may sign this request and (a) signs with each in turn, (b) re-dispatches\n * the request through a pinned key's own protocol, and (c) fails over to the\n * next key when a stream errors before any content is emitted.\n */\n keys?: (context: PiAiKeyContext) => Promise<readonly KeyCandidate[]>\n}\n\ntype ProviderHeaders = Record<string, string | null>\ntype HeaderTransformer = (headers: ProviderHeaders) => ProviderHeaders | Promise<ProviderHeaders>\ntype UnknownFunction = (...args: unknown[]) => unknown\n\ntype ObjectLike = Record<PropertyKey, unknown>\n\n/** One pi-ai protocol implementation, imported lazily so a route never pays for it. */\ninterface ProtocolStreams {\n readonly streamSimple: (model: Record<string, unknown>, context: unknown, options: Record<string, unknown>) => AsyncIterable<Record<string, unknown>>\n}\n\nconst PROTOCOL_CACHE = new Map<RouteProtocol, Promise<ProtocolStreams>>()\n\ntype ContextNormalizer = (context: unknown) => unknown\n\nlet CONTEXT_NORMALIZER: Promise<ContextNormalizer | undefined> | undefined\n\n/**\n * The runtime's context normaliser, when this pi-ai ships one.\n *\n * `Models.streamSimple` folds a legacy `{ systemPrompt, messages, tools }`\n * context into the transcript shape before it dispatches (`normalizeContext`\n * folds both the prompt and the tool declarations into the leading system\n * message). A key that speaks another protocol has to reach that protocol's\n * module DIRECTLY, which bypasses the fold: the implementation then reads tool\n * declarations from the transcript only, so `context.tools` is invisible and\n * the request goes out with NO tools at all. The model answers as if it had\n * none \u2014 one text block, `stop`, `end_turn` \u2014 and the whole agent loop stalls\n * after a single request.\n *\n * Older pi-ai builds have no `utils/transcript` subpath; those implementations\n * still read `context.tools`, so the legacy context must be left untouched.\n */\nfunction loadContextNormalizer(): Promise<ContextNormalizer | undefined> {\n if (CONTEXT_NORMALIZER !== undefined) return CONTEXT_NORMALIZER\n CONTEXT_NORMALIZER = (async (): Promise<ContextNormalizer | undefined> => {\n try {\n // Kept in a variable: the build's pi-ai typings predate the subpath, and\n // the module only exists in the runtime the adapter is loaded from.\n const specifier: string = '@earendil-works/pi-ai/utils/transcript'\n const module = await import(/* @vite-ignore */ specifier) as unknown as { normalizeContext?: ContextNormalizer }\n return typeof module.normalizeContext === 'function' ? module.normalizeContext : undefined\n } catch {\n return undefined\n }\n })()\n return CONTEXT_NORMALIZER\n}\n\n/** Fold a legacy context once per request object; a no-op on transcript input. */\nconst NORMALIZED_CONTEXTS = new WeakMap<object, unknown>()\n\nasync function normalizeDispatchedContext(context: unknown): Promise<unknown> {\n const object = objectOf(context)\n if (object === undefined) return context\n if (NORMALIZED_CONTEXTS.has(object)) return NORMALIZED_CONTEXTS.get(object)\n if (!Array.isArray(object['messages'])) return context\n const normalize = await loadContextNormalizer()\n if (normalize === undefined) return context\n const normalized = normalize(context)\n if (objectOf(normalized) === undefined) return context\n NORMALIZED_CONTEXTS.set(object, normalized)\n return normalized\n}\n\n/**\n * Load one pi-ai protocol implementation on demand.\n *\n * A route in the Harness binds exactly ONE protocol for every model, and the\n * adapter's provider dispatches by that single implementation regardless of\n * `model.api` \u2014 so a key that must speak a DIFFERENT protocol needs the proxy to\n * reach that protocol's `streamSimple` directly. The modules are external to this\n * bundle (they ship with the runtime) and are cached by the host's import cache;\n * we additionally memoise the promise so a re-dispatch never re-awaits a cold\n * import twice.\n */\nfunction loadProtocol(protocol: RouteProtocol): Promise<ProtocolStreams> {\n let pending = PROTOCOL_CACHE.get(protocol)\n if (pending !== undefined) return pending\n pending = (async (): Promise<ProtocolStreams> => {\n switch (protocol) {\n case 'anthropic-messages':\n return await import('@earendil-works/pi-ai/api/anthropic-messages') as unknown as ProtocolStreams\n case 'openai-responses':\n return await import('@earendil-works/pi-ai/api/openai-responses') as unknown as ProtocolStreams\n case 'google-generative-ai':\n // Not offered by the harness adapter's registry \u2014 only a key pin ever\n // dispatches here, and a runtime older than the module rejects the\n // import, which the failover loop benches like any refused key.\n return await import('@earendil-works/pi-ai/api/google-generative-ai') as unknown as ProtocolStreams\n case 'openai-completions':\n default:\n return await import('@earendil-works/pi-ai/api/openai-completions') as unknown as ProtocolStreams\n }\n })()\n PROTOCOL_CACHE.set(protocol, pending)\n return pending\n}\n\ninterface PiAiPatchState {\n originalCurrent: UnknownFunction\n wrappedCurrent: UnknownFunction\n source: PiAiHeaderSource\n users: number\n}\n\ninterface RegisterPatchState {\n originalRegister: UnknownFunction\n wrappedRegister: UnknownFunction\n users: number\n}\n\nconst PATCH_STATE = Symbol.for('dsh-model-think-level.pi-ai-header-transform')\nconst REGISTER_PATCH_STATE = Symbol.for('dsh-model-think-level.pi-ai-header-register')\nconst CORDIS_ORIGINAL = Symbol.for('cordis.original')\n\nfunction objectOf(value: unknown): ObjectLike | undefined {\n return typeof value === 'object' && value !== null ? value as ObjectLike : undefined\n}\n\nfunction runtimeObjectOf(value: unknown): ObjectLike | undefined {\n const object = objectOf(value)\n if (object === undefined) return undefined\n const original = object[CORDIS_ORIGINAL]\n return objectOf(original) ?? object\n}\n\nfunction noOpHandle(): PiAiHeaderTransformHandle {\n return {\n active: false,\n dispose(): void {},\n }\n}\n\nfunction routeOverrideOf(source: PiAiHeaderSource, model: unknown): HeaderOverride | undefined {\n try {\n if (!isRecord(model)) return undefined\n const baseURL = model['baseUrl']\n if (typeof baseURL !== 'string' || baseURL.length === 0) return undefined\n const modelId = typeof model['id'] === 'string' ? model['id'] : undefined\n return selectOverride(source.current, baseURL, modelId)\n } catch {\n // A stale or partially written settings snapshot must never break a chat.\n return undefined\n }\n}\n\n/**\n * The text a stream error carries.\n *\n * pi-ai reports the provider's message in `error.message` (older shapes also use\n * `error.errorMessage`) and a short `reason` on the event itself. The words in\n * there are what tells a rate limit from a spent balance, which is the one\n * distinction the cooldown memory acts on, so all of them are read.\n */\nfunction errorTextOf(event: Record<string, unknown>): string {\n const error = isRecord(event['error']) ? event['error'] : undefined\n const parts: unknown[] = [error?.['message'], error?.['errorMessage'], event['reason']]\n return parts.filter((part): part is string => typeof part === 'string').join(' ')\n}\n\nfunction modelsProxyOf(models: ObjectLike, source: PiAiHeaderSource): ObjectLike {\n return new Proxy(models, {\n get(target, property, receiver): unknown {\n if (property !== 'streamSimple') return Reflect.get(target, property, receiver)\n const streamSimple = Reflect.get(target, property, target)\n if (typeof streamSimple !== 'function') return streamSimple\n return (...args: unknown[]): unknown => {\n const model = args[0]\n const context = args[1]\n const options = args[2]\n const modelObject = isRecord(model) ? model : undefined\n if (modelObject === undefined || typeof modelObject['baseUrl'] !== 'string' || !isRecord(options)) {\n return (streamSimple as UnknownFunction).call(target, model, context, options)\n }\n\n const existing = typeof options['transformHeaders'] === 'function'\n ? options['transformHeaders'] as HeaderTransformer\n : undefined\n const transformHeaders: HeaderTransformer = async (headers) => {\n // Preserve any transform supplied by the adapter/provider first; the\n // user's route headers are the final request-level values by design.\n const merged = existing === undefined ? headers : await existing(headers)\n const override = routeOverrideOf(source, model)\n return override?.hasHeaders ? { ...merged, ...override.headers } : merged\n }\n\n // Requests this proxy signs carry the wire-dispatch marker on top of\n // the header patch, so the fetch layer below applies its patch WITHOUT\n // re-signing them (see WIRE_DISPATCH_HEADER): the key, the wire and the\n // endpoint are THIS seam's choice, and this seam's failover loop owns\n // the retries. Constant value only \u2014 it is stripped in the fetch\n // wrapper before the request leaves the process.\n const markedTransformHeaders: HeaderTransformer = async (headers) => ({\n ...await transformHeaders(headers),\n [WIRE_DISPATCH_HEADER]: '1',\n })\n\n const modelId = typeof modelObject['id'] === 'string' ? modelObject['id'] : undefined\n const keyResolver = source.keys\n // Without a key resolver we are a pure header overlay: keep the exact\n // stream object the adapter expects (tests and the host rely on identity).\n if (keyResolver === undefined) {\n return (streamSimple as UnknownFunction).call(target, model, context, {\n ...options,\n transformHeaders,\n })\n }\n\n const route = routeOverrideOf(source, model)?.route\n const dispatch = (): Promise<readonly KeyCandidate[]> => {\n if (route === undefined) return Promise.resolve([])\n return Promise.resolve(keyResolver({ route, model: modelId })).catch(() => [])\n }\n // A key may force its own protocol / endpoint AND a per-request apiKey.\n // When it does, re-dispatch straight to that protocol's streamSimple;\n // otherwise delegate to the route provider (still honouring the key).\n // `avoid` keeps the attempt's resolution in step with the plan's: an\n // automatic key must not re-pick the wire the plan already skipped.\n const startAttempt = async (candidate: KeyCandidate, avoid?: RouteProtocol): Promise<AsyncIterable<Record<string, unknown>>> => {\n const api = typeof modelObject['api'] === 'string' ? modelObject['api'] as RouteProtocol : 'openai-completions'\n const protocol = wireOf(candidate, api, modelId, avoid)\n // An endpoint only rides along when its family is the one this request\n // actually speaks; a pin the route could not honour keeps its own URL.\n const honoured = isHonoured(candidate, api)\n // An automatic key carries its cross-family addresses in `endpoints`:\n // the wire `wireOf` resolved names the family whose address to use.\n // A same-family resolution (wire === api) keeps the route's own URL.\n const autoEndpoint = honoured && candidate.protocol === undefined && protocol !== api\n ? candidate.endpoints?.[endpointFamilyOf(protocol)]\n : undefined\n const selectedBaseUrl = honoured && candidate.endpoint !== undefined\n ? candidate.endpoint\n : autoEndpoint !== undefined\n ? autoEndpoint\n : modelObject['baseUrl'] as string\n const baseUrl = protocol === 'anthropic-messages'\n ? anthropicRequestBaseUrl(selectedBaseUrl)\n : protocol === 'google-generative-ai'\n // The Google client takes baseUrl verbatim with no apiVersion, so\n // the version segment must be in the path (a bare origin gains\n // /v1beta; a spelled-out path is the gateway's own spelling).\n ? geminiRequestBaseUrl(selectedBaseUrl)\n : selectedBaseUrl\n const switched = protocol !== api || baseUrl !== modelObject['baseUrl']\n if (!switched) {\n return (streamSimple as UnknownFunction).call(target, model, context, {\n ...options,\n apiKey: candidate.value,\n transformHeaders: markedTransformHeaders,\n }) as unknown as AsyncIterable<Record<string, unknown>>\n }\n // True protocol switch: the request body shape must change, so call the\n // target protocol directly. There is no ModelsImpl.applyAuth in this\n // path \u2014 sign and transform headers ourselves before handing over.\n const mergedHeaders = await transformHeaders(isRecord(options['headers'])\n ? options['headers'] as ProviderHeaders\n : {})\n const implementation = await loadProtocol(protocol)\n // The registry call the adapter normally makes folds the context for\n // us; this direct re-dispatch must do it itself or the target\n // implementation never sees the request's tool declarations.\n const dispatchedContext = await normalizeDispatchedContext(context)\n return implementation.streamSimple(\n { ...modelObject, api: protocol, baseUrl },\n dispatchedContext,\n {\n ...options,\n apiKey: candidate.value,\n headers: { ...mergedHeaders, [WIRE_DISPATCH_HEADER]: '1' },\n transformHeaders: undefined,\n },\n )\n }\n\n const run = async function* (): AsyncGenerator<Record<string, unknown>> {\n const routeCandidates = await dispatch()\n if (routeCandidates.length === 0) {\n // No key claims this route: fall back to the route's own credential.\n const stream = (streamSimple as UnknownFunction).call(target, model, context, {\n ...options,\n transformHeaders,\n }) as AsyncIterable<Record<string, unknown>>\n for await (const event of stream) yield event\n return\n }\n const api = typeof modelObject['api'] === 'string' ? modelObject['api'] as RouteProtocol : 'openai-completions'\n const servedKey = `${route ?? ''}\\u0000${modelId ?? ''}`\n // One decision, shared by both seams: fit for this model, the wire that\n // served it last time, the wire that refused it last time, honour of\n // each pin, the wire pool, and the keys that are cooling down \u2014 in that\n // order of authority.\n const avoidWire = failedWire.get(servedKey)\n const plan = planKeys(routeCandidates, {\n api,\n model: modelId,\n preferredWire: servedWire.get(servedKey),\n avoidWire,\n isResting: candidate => keyRest.isResting(restKeyOf(route ?? '', candidate.ref), Date.now()),\n })\n // The plan is reproduced in `?diag=1`; it carries references and ranks,\n // never a key value.\n recordRoutePlan(route ?? '', plan, { model: modelId })\n const wireOfAttempt = (candidate: KeyCandidate): RouteProtocol =>\n plan.entries.find(entry => entry.candidate === candidate)?.wire ?? wireOf(candidate, api, modelId, avoidWire)\n let lastErrorEvent: Record<string, unknown> | undefined\n let lastError: unknown\n for (const candidate of plan.ordered) {\n const restKey = restKeyOf(route ?? '', candidate.ref)\n let stream: AsyncIterable<Record<string, unknown>>\n try {\n stream = await startAttempt(candidate, avoidWire)\n } catch (error) {\n // A synchronous setup failure (e.g. a missing client key) is a\n // pre-content failure: bench the key and try the next one. An\n // AUTOMATIC resolution's wire is marked refused for this model, so\n // the next request resolves elsewhere; a pin's failure blames the\n // credential, not the wire.\n lastError = error\n if (candidate.protocol === undefined) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate))\n keyRest.note(restKey, classifyFailure(undefined, error instanceof Error ? error.message : '') ?? 'refused')\n continue\n }\n let committed = false\n let failed = false\n for await (const event of stream) {\n const type = isRecord(event) ? event['type'] : undefined\n if (!committed) {\n if (type === 'error') {\n // The key was rejected before any content streamed: fail over,\n // and remember why so the next request does not start here.\n lastErrorEvent = event as Record<string, unknown>\n failed = true\n if (candidate.protocol === undefined) rememberWireFact(failedWire, servedKey, wireOfAttempt(candidate))\n keyRest.note(restKey, classifyFailure(undefined, errorTextOf(event as Record<string, unknown>)) ?? 'refused')\n break\n }\n committed = true\n keyRest.clear(restKey)\n // This is the wire that actually serves the model; start here\n // next time instead of paying the rejected round trip again.\n // The refused-wire memory is deliberately kept: a wire that\n // refused the model stays out of the automatic resolution.\n rememberWireFact(servedWire, servedKey, wireOfAttempt(candidate))\n }\n yield event\n }\n if (failed) continue\n return\n }\n if (lastErrorEvent !== undefined) {\n yield lastErrorEvent\n return\n }\n // Every key failed synchronously, before producing any event.\n yield {\n type: 'error',\n reason: 'error',\n error: {\n role: 'assistant',\n content: [],\n stopReason: 'error',\n errorMessage: lastError instanceof Error ? lastError.message : 'No API key could serve this model.',\n usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 },\n },\n }\n }\n\n return run()\n }\n },\n })\n}\n\nfunction snapshotProxyOf(snapshot: ObjectLike, source: PiAiHeaderSource): ObjectLike {\n const models = snapshot['models']\n const modelObject = objectOf(models)\n if (modelObject === undefined || typeof modelObject['streamSimple'] !== 'function') return snapshot\n const proxiedModels = modelsProxyOf(modelObject, source)\n return new Proxy(snapshot, {\n get(target, property, receiver): unknown {\n if (property === 'models') return proxiedModels\n return Reflect.get(target, property, receiver)\n },\n })\n}\n\n/** Handle returned for one adapter patch. */\nexport interface PiAiHeaderTransformHandle {\n readonly active: boolean\n dispose(): void\n}\n\n/** Install the request-level transform on one pi-ai-shaped adapter. */\nexport function installPiAiHeaderTransform(adapter: unknown, source: PiAiHeaderSource): PiAiHeaderTransformHandle {\n const target = objectOf(adapter)\n if (target === undefined || typeof target['current'] !== 'function') return noOpHandle()\n\n const current = target['current'] as UnknownFunction\n const stored = target[PATCH_STATE] as PiAiPatchState | undefined\n if (stored !== undefined && current === stored.wrappedCurrent) {\n stored.source = source\n stored.users += 1\n let active = true\n return {\n get active(): boolean { return active && stored.users > 0 },\n dispose(): void {\n if (!active) return\n active = false\n stored.users -= 1\n if (stored.users > 0) return\n if (target['current'] === stored.wrappedCurrent) target['current'] = stored.originalCurrent\n if (target[PATCH_STATE] === stored) delete target[PATCH_STATE]\n },\n }\n }\n\n const originalCurrent = current\n const wrappedCurrent: UnknownFunction = function (this: unknown, ...args: unknown[]): unknown {\n const snapshot = originalCurrent.apply(this, args)\n const snapshotObject = objectOf(snapshot)\n return snapshotObject === undefined ? snapshot : snapshotProxyOf(snapshotObject, state.source)\n }\n const state: PiAiPatchState = { originalCurrent, wrappedCurrent, source, users: 1 }\n target['current'] = wrappedCurrent\n Object.defineProperty(target, PATCH_STATE, { configurable: true, value: state })\n\n let active = true\n return {\n get active(): boolean { return active && state.users > 0 },\n dispose(): void {\n if (!active) return\n active = false\n state.users -= 1\n if (state.users > 0) return\n if (target['current'] === state.wrappedCurrent) target['current'] = state.originalCurrent\n if (target[PATCH_STATE] === state) delete target[PATCH_STATE]\n },\n }\n}\n\n/** Diagnostic snapshot of the bridge's live attach state. */\nexport interface PiAiHeaderBridgeState {\n runtimeFound: boolean\n registerPatched: boolean\n adaptersInRuntime: number\n adaptersPatched: number\n adapters: string[]\n routes: number\n overrides: number\n}\n\n/**\n * Describe what the bridge is currently attached to. Read-only; used by the\n * probe route's `?diag=1` arm to make the request-header takeover observable\n * from the running host instead of only from a test harness.\n */\nexport function describePiAiHeaderState(llm: unknown, source: PiAiHeaderSource): PiAiHeaderBridgeState {\n const runtime = runtimeObjectOf(llm)\n const adapters = runtime?.['adapters']\n const names: string[] = []\n let total = 0\n let patched = 0\n if (adapters instanceof Map) {\n for (const registration of adapters.values()) {\n const adapter = objectOf(objectOf(registration)?.['adapter'])\n if (adapter === undefined || typeof adapter['current'] !== 'function') continue\n total += 1\n const state = adapter[PATCH_STATE] as PiAiPatchState | undefined\n const isPatched = state !== undefined && adapter['current'] === state.wrappedCurrent\n if (isPatched) patched += 1\n const name = typeof adapter['constructor'] === 'function' ? adapter['constructor'].name : 'unknown'\n names.push(`${name}${isPatched ? '+' : '-'}`)\n }\n }\n const registerState = runtime?.[REGISTER_PATCH_STATE] as RegisterPatchState | undefined\n return {\n runtimeFound: runtime !== undefined,\n registerPatched: registerState !== undefined && runtime?.['registerAdapter'] === registerState.wrappedRegister,\n adaptersInRuntime: total,\n adaptersPatched: patched,\n adapters: names,\n routes: source.current.routes.length,\n overrides: source.current.overrides.length,\n }\n}\n\n/**\n * Install the bridge on every current pi-ai-shaped registration and expose a\n * refresh for the runtime's `llm/adapters-updated` event.\n */\nexport interface PiAiHeaderTransformsHandle {\n refresh(): void\n dispose(): void\n}\n\nexport function installPiAiHeaderTransforms(llm: unknown, source: PiAiHeaderSource): PiAiHeaderTransformsHandle {\n const installed = new Map<object, PiAiHeaderTransformHandle>()\n const runtime = runtimeObjectOf(llm)\n let disposed = false\n\n const install = (adapter: unknown): void => {\n if (disposed) return\n const adapterObject = objectOf(adapter)\n if (adapterObject === undefined || typeof adapterObject['current'] !== 'function') return\n if (!installed.has(adapterObject)) installed.set(adapterObject, installPiAiHeaderTransform(adapterObject, source))\n }\n\n const refresh = (): void => {\n if (disposed) return\n const adapters = runtime?.['adapters']\n if (!(adapters instanceof Map)) return\n const seen = new Set<object>()\n for (const registration of adapters.values()) {\n const registrationObject = objectOf(registration)\n const adapterObject = objectOf(registrationObject?.['adapter'])\n if (adapterObject === undefined || typeof adapterObject['current'] !== 'function') continue\n seen.add(adapterObject)\n install(adapterObject)\n }\n for (const [adapter, handle] of installed) {\n if (seen.has(adapter)) continue\n handle.dispose()\n installed.delete(adapter)\n }\n }\n\n // dsh-llm-pi-ai registers its adapter through this public method. Install\n // before delegating so a registration cannot emit an update and dispatch a\n // request in between the registry mutation and our refresh listener.\n let registerHandle: PiAiHeaderTransformHandle | undefined\n const originalRegister = runtime?.['registerAdapter']\n if (runtime !== undefined && typeof originalRegister === 'function') {\n const registerState = runtime[REGISTER_PATCH_STATE] as RegisterPatchState | undefined\n if (registerState !== undefined && runtime['registerAdapter'] === registerState.wrappedRegister) {\n registerState.users += 1\n registerHandle = {\n get active(): boolean { return !disposed && registerState.users > 0 },\n dispose(): void {\n if (registerState.users <= 0) return\n registerState.users -= 1\n if (registerState.users > 0) return\n if (runtime['registerAdapter'] === registerState.wrappedRegister) runtime['registerAdapter'] = registerState.originalRegister\n if (runtime[REGISTER_PATCH_STATE] === registerState) delete runtime[REGISTER_PATCH_STATE]\n },\n }\n } else {\n const original = originalRegister as UnknownFunction\n const wrappedRegister: UnknownFunction = function (this: unknown, ...args: unknown[]): unknown {\n const adapter = args[1]\n install(adapter)\n try {\n return original.apply(this, args)\n } finally {\n refresh()\n }\n }\n const state: RegisterPatchState = {\n originalRegister: original,\n wrappedRegister,\n users: 1,\n }\n runtime['registerAdapter'] = wrappedRegister\n Object.defineProperty(runtime, REGISTER_PATCH_STATE, { configurable: true, value: state })\n registerHandle = {\n get active(): boolean { return !disposed && state.users > 0 },\n dispose(): void {\n if (state.users <= 0) return\n state.users -= 1\n if (state.users > 0) return\n if (runtime['registerAdapter'] === state.wrappedRegister) runtime['registerAdapter'] = state.originalRegister\n if (runtime[REGISTER_PATCH_STATE] === state) delete runtime[REGISTER_PATCH_STATE]\n },\n }\n }\n }\n refresh()\n\n return {\n refresh,\n dispose(): void {\n if (disposed) return\n disposed = true\n registerHandle?.dispose()\n for (const handle of installed.values()) handle.dispose()\n installed.clear()\n },\n }\n}\n", "/**\n * Coexistence report for the user-agent takeover (issue #12, MVP-3).\n *\n * Overriding `user-agent` is not a private act: the stock adapter drops the\n * profile's value, so at least one published plugin patches the adapter itself\n * to keep it, and several more wrap fetch. Two of them active at once means the\n * LAST writer on the wire wins and the user sees a `user-agent` they did not\n * choose \u2014 with no error anywhere. This module reports what it found instead of\n * silently fighting.\n *\n * Three signals, in descending reliability:\n * 1. The adapter file already carries a user-agent patch (its `requestHeaders`\n * body no longer drops the profile's `user-agent`) \u2014 readable fact.\n * 2. A known sibling plugin's package is installed in a reachable tree.\n * 3. Nothing found.\n *\n * Everything here is best-effort and side-effect-free: an unreadable path, an\n * absent tree, or a hostile `package.json` yields `unknown`, never a throw \u2014\n * this report must not be able to disable the plugin.\n *\n * @module dsh-model-think-level/headers-conflict\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join, resolve } from 'node:path'\n\n/**\n * Sibling plugins that rewrite the same request surface. The list is by PACKAGE\n * NAME, matched anywhere in a reachable `node_modules`: a plugin installed\n * under a profile but not enabled is reported as installed, and the report says\n * so rather than guessing at enablement (which a patch file or a hand-edited\n * profile can decide several ways).\n */\nconst SIBLING_PACKAGES = [\n 'dsh-client-masquerade',\n 'dsh-llm-headers',\n 'dsh-llm-pi-ai-headers',\n 'dsh-custom-provider-settings',\n] as const\n\n/**\n * Fragments proving the installed adapter already preserves a profile\n * `user-agent`. The published patch rewrites `requestHeaders()` to look for a\n * configured value; older revisions of it used the same identifier, so the\n * check survives their textual reshuffle while staying specific enough that the\n * stock function cannot match (it contains neither).\n */\nconst ADAPTER_PATCH_MARKERS = ['configuredUserAgent', 'masquerade routes rely on'] as const\n\n/** What the report found about the adapter the requests actually flow through. */\nexport type AdapterPatchState = 'patched' | 'stock' | 'unknown'\n\n/** One sibling plugin package found on disk. */\nexport interface InstalledSibling {\n /** Package name. */\n name: string\n /** Absolute path of the resolved package directory (or entry file). */\n path: string\n}\n\n/** The coexistence report. */\nexport interface HeaderConflictReport {\n /** Whether the installed `@deepseek-ai/dsh-llm-pi-ai` adapter carries a UA patch. */\n adapter: AdapterPatchState\n /** Path of the inspected adapter file, when one was found. */\n adapterPath?: string\n /** Known sibling plugins present on disk. */\n siblings: InstalledSibling[]\n /**\n * Whether this deployment should prefer the official layer instead of this\n * plugin's fetch takeover: true exactly when the adapter is already patched\n * (a profile `user-agent` reaches the wire on its own then, and a fetch\n * override on top would fight the patch).\n */\n preferOfficialLayer: boolean\n}\n\n/** Candidate `node_modules` roots to look in, most specific first. */\nfunction searchRoots(): string[] {\n const roots = new Set<string>()\n const entry = process.argv[1]\n if (typeof entry === 'string' && entry.length > 0) {\n let dir = dirname(resolve(entry))\n // Walk up a bounded number of levels: the shim, the bin dir, the package,\n // the install root.\n for (let depth = 0; depth < 8; depth += 1) {\n roots.add(join(dir, 'node_modules'))\n const parent = dirname(dir)\n if (parent === dir) break\n dir = parent\n }\n }\n // The cwd tree covers a profile-relative launch; the require chain covers\n // everything the process itself can no longer name.\n roots.add(join(process.cwd(), 'node_modules'))\n try {\n const require = createRequire(import.meta.url)\n for (const name of SIBLING_PACKAGES) {\n try {\n roots.add(join(dirname(dirname(dirname(require.resolve(`${name}/package.json`)))), 'node_modules'))\n } catch {\n // Not resolvable from here; the path search below covers the rest.\n }\n }\n } catch {\n // No require chain: path search alone.\n }\n return [...roots]\n}\n\n/** Locate the installed pi-ai adapter's bundle, or undefined when unreachable. */\nfunction findAdapterFile(): string | undefined {\n const relative = join('@deepseek-ai', 'dsh-llm-pi-ai', 'lib', 'index.js')\n const candidates: string[] = []\n try {\n const require = createRequire(import.meta.url)\n candidates.push(require.resolve('@deepseek-ai/dsh-llm-pi-ai'))\n } catch {\n // Resolve by location instead.\n }\n // dsh ships the adapter inside its own tree; probing the entry's ancestry\n // finds it for a global install, a profile install, and a monorepo alike.\n for (const root of searchRoots()) candidates.push(join(root, relative))\n for (const candidate of candidates) {\n if (existsSync(candidate)) return candidate\n }\n return undefined\n}\n\n/**\n * Whether a source text of the pi-ai adapter bundle carries a user-agent patch.\n *\n * Pure, so the decision is testable without touching a real installation: the\n * stock `requestHeaders()` filters the profile's `user-agent` into the reserved\n * set and contains neither marker, while every published revision of the patch\n * names the value it found.\n * @param source - the adapter bundle's text.\n * @returns whether the patch is present.\n */\nexport function adapterSourcePatched(source: string): boolean {\n return ADAPTER_PATCH_MARKERS.some(marker => source.includes(marker))\n}\n\n/** Whether the adapter bundle at one path carries a user-agent patch. */\nfunction adapterPatchState(path: string): AdapterPatchState {\n try {\n return adapterSourcePatched(readFileSync(path, 'utf8')) ? 'patched' : 'stock'\n } catch {\n return 'unknown'\n }\n}\n\n/** Known sibling plugins present in a reachable tree. */\nfunction findSiblings(): InstalledSibling[] {\n const found: InstalledSibling[] = []\n const seen = new Set<string>()\n for (const root of searchRoots()) {\n for (const name of SIBLING_PACKAGES) {\n if (seen.has(name)) continue\n const dir = join(root, name)\n const manifest = join(dir, 'package.json')\n if (!existsSync(manifest)) continue\n seen.add(name)\n found.push({ name, path: dir })\n }\n }\n return found\n}\n\n/**\n * Produce the coexistence report. Never throws: every probe degrades to\n * `unknown` / an empty list.\n * @returns the report.\n */\nexport function detectHeaderConflicts(): HeaderConflictReport {\n let adapter: AdapterPatchState = 'unknown'\n let adapterPath: string | undefined\n let siblings: InstalledSibling[] = []\n try {\n adapterPath = findAdapterFile()\n if (adapterPath !== undefined) adapter = adapterPatchState(adapterPath)\n } catch {\n adapter = 'unknown'\n }\n try {\n siblings = findSiblings()\n } catch {\n siblings = []\n }\n return {\n adapter,\n ...(adapterPath === undefined ? {} : { adapterPath }),\n siblings,\n preferOfficialLayer: adapter === 'patched',\n }\n}\n", "/**\n * The knowledge-base auto-fill: build the settings patch that declares\n * `reasoningEfforts` -- and, unless declined, the input-modality declaration --\n * on every undeclared model of a providers dict.\n *\n * Shared by BOTH halves on purpose. The host builds its boot fill with it, and\n * the browser half builds the very same patch from its own read, so one\n * suggestion can never produce two different documents. Pure data logic: no\n * harness package, no node or DOM API.\n *\n * @module dsh-model-think-level/autofill\n */\n\nimport { AUTOFILL_MARKER, INPUT_UNSET_MARKER, UNSET_MARKER } from './constants.js'\nimport { isSelfHostedRelay, NEW_COMPAT_KEYS, suggestEfforts } from './knowledge.js'\nimport { isRecord, routeFactsOf } from './shared.js'\n\n/** A JSON object patch. */\ntype JsonObject = Record<string, unknown>\n\n/**\n * Whether a model row carries an input-modality declaration the document\n * already answers with. An absent key and an empty array both read as \"no\n * answer here\" -- mirroring how llm-pi-ai's own resolution treats them.\n */\nfunction declaresInput(model: JsonObject): boolean {\n const input = model['input']\n return Array.isArray(input) && input.length > 0\n}\n\n/**\n * Build a patch that adds reasoningEfforts -- and, unless declined, the\n * input-modality declaration -- to every undeclared model of the given\n * routes, from the knowledge base / protocol inference. Returns the partial\n * providers patch, or undefined when nothing needs filling.\n * @param providers - the resolved providers dict.\n * @param routeFilter - optional route filter (defaults to all routes).\n * @param options - fill switches; both default on.\n * @param revision - settings revision this read is based on; recorded as the\n * provenance marker of every ladder filled here (see {@link AUTOFILL_MARKER}).\n */\nexport function buildAutofillPatch(\n providers: unknown,\n routeFilter: (route: string) => boolean = () => true,\n options: { efforts?: boolean; modalities?: boolean } = {},\n revision = 0,\n): JsonObject | undefined {\n const fillEfforts = options.efforts !== false\n const fillModalities = options.modalities !== false\n if (!isRecord(providers)) return undefined\n const patchRoutes: JsonObject = {}\n for (const route of Object.keys(providers)) {\n if (!routeFilter(route)) continue\n // Read the RAW models array: this builder rebuilds the array verbatim,\n // so a route carrying a row it cannot represent (non-record) is left\n // alone \u2014 a filtered rebuild would silently DELETE that row.\n const profile = providers[route]\n const rawModels = isRecord(profile) && Array.isArray(profile['models']) ? profile['models'] : undefined\n if (rawModels === undefined || rawModels.length === 0) continue\n if (!rawModels.every(isRecord)) continue\n const models = rawModels as Record<string, unknown>[]\n const nextModels: JsonObject[] = []\n let changed = false\n for (const model of models) {\n // Declared parts are untouched \u2014 and so are parts the user\n // deliberately unset: the durable markers record those absences as\n // decisions, so auto-fill never reads them back as gaps (the bug this\n // guards: a refill one event after every user \"unset\").\n const effortsDeclared = model['reasoningEfforts'] !== undefined || model[UNSET_MARKER] === true\n const inputDeclared = declaresInput(model) || model[INPUT_UNSET_MARKER] === true\n if ((effortsDeclared || !fillEfforts) && (inputDeclared || !fillModalities)) {\n // Versioned exception to never-touch-declared (issue #2): a declared\n // ladder whose compat lacks the role pin on a self-hosted relay gets\n // exactly that field merged in -- the declaration itself is untouched.\n const backfilled = backfillRolePin(model, providers, route)\n if (backfilled !== undefined) {\n changed = true\n nextModels.push(backfilled)\n } else {\n nextModels.push(model)\n }\n continue\n }\n const id = typeof model['id'] === 'string' ? model['id'] : ''\n if (id.length === 0) {\n nextModels.push(model)\n continue\n }\n const routeInfo = routeFactsOf(providers, route)\n const name = typeof model['name'] === 'string' ? model['name'] : undefined\n const suggestion = suggestEfforts(id, { ...routeInfo, displayName: name ?? routeInfo.displayName })\n if (suggestion.efforts === undefined) {\n nextModels.push(model)\n continue\n }\n const fill: JsonObject = { ...model }\n let touched = false\n // Capacities are never filled here: contextWindow / maxTokens are\n // display-only reference values in the browser half, and writing them\n // host-side would silently override the route defaults.\n // Reaching this branch means neither part was declared and no durable\n // unset marker stands on the row -- so there is no stale marker inside\n // `fill` to scrub; the guards above already excluded it.\n if (!effortsDeclared && fillEfforts) {\n touched = true\n fill['reasoningEfforts'] = suggestion.efforts as JsonObject\n // Provenance: the browser flush has to be able to tell this knowledge\n // base suggestion apart from a declaration the user made, or a staged\n // intent that differs in one spelling is dropped as a takeover (see\n // AUTOFILL_MARKER). The value is the revision this fill read.\n fill[AUTOFILL_MARKER] = revision\n if (suggestion.compat !== undefined) {\n const stored = isRecord(model['compat']) ? (model['compat'] as JsonObject) : {}\n fill['compat'] = { ...stored, ...(suggestion.compat as JsonObject) }\n }\n }\n if (!inputDeclared && fillModalities && suggestion.input !== undefined) {\n touched = true\n fill['input'] = [...suggestion.input]\n }\n if (!touched) {\n nextModels.push(model)\n continue\n }\n changed = true\n nextModels.push(fill)\n }\n if (changed) patchRoutes[route] = { models: nextModels }\n }\n return Object.keys(patchRoutes).length === 0 ? undefined : { providers: patchRoutes }\n}\n\n/** Strip newer-only compat keys from an autofill patch (older-kernel downgrade). */\nexport function stripNewCompatKeysDeep(patch: JsonObject): JsonObject | undefined {\n const providers = isRecord(patch['providers']) ? (patch['providers'] as JsonObject) : undefined\n if (providers === undefined) return undefined\n let strippedAny = false\n const nextProviders: JsonObject = {}\n for (const [route, profile] of Object.entries(providers)) {\n if (!isRecord(profile) || !Array.isArray(profile['models'])) {\n nextProviders[route] = profile as JsonObject\n continue\n }\n nextProviders[route] = {\n ...(profile as JsonObject),\n models: (profile['models'] as JsonObject[]).map(model => {\n if (!isRecord(model) || !isRecord(model['compat'])) return model\n const compat = { ...(model['compat'] as JsonObject) }\n for (const key of NEW_COMPAT_KEYS) {\n if (key in compat) {\n delete compat[key]\n strippedAny = true\n }\n }\n return { ...model, compat }\n }),\n }\n }\n if (!strippedAny) return undefined\n return { providers: nextProviders }\n}\n\n/**\n * Merge the role pin into one declared model row, or refuse it.\n *\n * Refusals (all silent, all deliberate): the row carries no ladder dict\n * (`false`, absent, or a deliberate-unset marker -- bare rows keep the bare\n * wire behavior they were chosen for); its compat already names an explicit\n * role value; or the route is not a self-hosted relay. A refusal changes\n * nothing; an acceptance touches exactly one compat field.\n */\nfunction backfillRolePin(\n model: Record<string, unknown>,\n providers: unknown,\n route: string,\n): JsonObject | undefined {\n if (!isRecord(model['reasoningEfforts'])) return undefined\n if (model[UNSET_MARKER] === true) return undefined\n const compat = model['compat']\n const base: JsonObject = isRecord(compat) ? { ...compat } : {}\n if (base['supportsDeveloperRole'] !== undefined) return undefined\n if (!isSelfHostedRelay(routeFactsOf(providers, route))) return undefined\n return { ...model, compat: { ...base, supportsDeveloperRole: false } }\n}\n"],
5
+ "mappings": ";AA0BA,OAAO,YAAY;;;ACnBZ,IAAM,YAAY;AAGlB,IAAM,aAAa;AAEnB,IAAM,YAA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qBAAqB,CAAC;AAC7D;AAAA,UACF;AACA,mBAAS,KAAK,KAAK;AAAA,YACjB,IAAI;AAAA,YACJ,MAAM,EAAE,UAAU,SAAS,UAAU,kBAAkB,SAAS,iBAAiB;AAAA,UACnF,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,MACH;AAAA,IACF;AAMA,QAAI;AAAA,MACF,MACE,aAAa,UAAU,SAAS;AAAA,QAC9B,MAAM;AAAA,QACN,MAAM;AAAA,QACN,SAAS,OAAO,KAAK,QAAQ;AAC3B,cAAI,CAAC,iBAAiB,GAAG,GAAG;AAC1B,qBAAS,KAAK,KAAK,EAAE,IAAI,OAAO,OAAO,YAAY,CAAC;AACpD;AAAA,UACF;AACA,cAAI,IAAI,WAAW,OAAO;AACxB,qBAAS,KAAK,KAAK,EAAE,IAAI,OAAO,OAAO,qBAAqB,CAAC;AAC7D;AAAA,UACF;AACA,gBAAM,QAAQ,cAAc;AAC5B,mBAAS,KAAK,KAAK;AAAA,YACjB,IAAI;AAAA,YACJ,MAAM;AAAA;AAAA,cAEJ,SAAS,SAAS;AAAA;AAAA,cAElB,WAAW,uBAAuB;AAAA;AAAA,cAElC,WAAW,MAAM,UAAU,IAAI,YAAU;AAAA,gBACvC,QAAQ,MAAM;AAAA,gBACd,OAAO,MAAM;AAAA,gBACb,SAAS,MAAM;AAAA,gBACf,GAAI,MAAM,cAAc,SAAY,CAAC,IAAI,EAAE,WAAW,MAAM,UAAU;AAAA,cACxE,EAAE;AAAA;AAAA,cAEF,WAAW,MAAM;AAAA;AAAA,cAEjB,iBAAiB,MAAM;AAAA;AAAA,cAEvB,aAAa;AAAA,YACf;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF,CAAC;AACH;",
6
+ "names": ["label", "state", "compat", "name", "name", "name", "name", "normalize", "active", "name", "readFileSync", "dirname", "join", "require", "name", "name", "resolved", "name", "records", "resolve", "ref"]
7
7
  }